Smart Contracts: Complete Guide to Self-Executing Code on Blockchain
Explore smart contract development including lifecycle management, security vulnerabilities, gas optimization, testing frameworks, development tools, upgrade patterns, and evolution from simple scripts to complex decentralized applications.
Smart contracts represent a fundamental innovation in how agreements and logic execute in decentralized systems. These self-executing programs running on blockchain infrastructure enable trustless execution, eliminating intermediaries while ensuring code executes exactly as written. Understanding smart contract development enables developers to build applications ranging from simple token transfers to complex decentralized finance protocols.
The evolution of smart contracts from basic scripts to sophisticated decentralized applications demonstrates the technology's maturation. Security considerations, gas optimization, and testing strategies have become disciplines in their own right as billions of dollars in value depend on contract correctness. This comprehensive guide covers all aspects of smart contract development and deployment.
Smart Contract Lifecycle
Design and Planning Phase
Smart contract development begins with clear specification of the application's logic, state, and interaction patterns. Unlike traditional software, deployed contracts cannot be modified, making upfront design critical. The specification should define:
- State variables: What data the contract stores and its mutability
- Functions: External and internal callable interfaces
- Access control: Who can call what functions and under what conditions
- Error handling: How the contract responds to invalid states
- Upgrade strategy: If and how the contract can be modified
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
/**
* @title TokenVesting
* @notice Vesting contract for team tokens with cliff and linear release
*/
contract TokenVesting {
// State variables
mapping(address => VestingSchedule) public vestingSchedules;
address public immutable beneficiary;
uint256 public immutable startTime;
uint256 public immutable cliffDuration;
uint256 public immutable vestingDuration;
uint256 public immutable totalAllocated;
uint256 public immutable tokenAddress;
uint256 public released;
struct VestingSchedule {
uint256 totalAmount;
uint256 releasedAmount;
bool revoked;
}
// Events for transparency
event TokensReleased(uint256 amount);
event VestingRevoked();
constructor(
address _beneficiary,
uint256 _startTime,
uint256 _cliffDuration,
uint256 _vestingDuration,
uint256 _totalAllocated,
address _tokenAddress
) {
require(_beneficiary != address(0), "Invalid beneficiary");
require(_vestingDuration > 0, "Vesting duration must be > 0");
beneficiary = _beneficiary;
startTime = _startTime;
cliffDuration = _cliffDuration;
vestingDuration = _vestingDuration;
totalAllocated = _totalAllocated;
tokenAddress = _tokenAddress;
}
/**
* @notice Calculate releasable amount based on vesting schedule
*/
function getReleasableAmount() public view returns (uint256) {
uint256 vested = getVestedAmount();
uint256 unreleased = vested - released;
return unreleased;
}
/**
* @notice Calculate total vested amount (including released)
*/
function getVestedAmount() public view returns (uint256) {
if (block.timestamp < startTime + cliffDuration) {
return 0;
} else if (block.timestamp >= startTime + vestingDuration) {
return totalAllocated;
} else {
uint256 timeVested = block.timestamp - startTime - cliffDuration;
uint256 vestedPercentage = (timeVested * 1e18) /
(vestingDuration - cliffDuration);
return (totalAllocated * vestedPercentage) / 1e18;
}
}
/**
* @notice Release vested tokens to beneficiary
*/
function release() public {
require(msg.sender == beneficiary, "Only beneficiary can release");
uint256 releasable = getReleasableAmount();
require(releasable > 0, "No tokens to release");
released += releasable;
IERC20(tokenAddress).transfer(beneficiary, releasable);
emit TokensReleased(releasable);
}
}
interface IERC20 {
function transfer(address recipient, uint256 amount)
external returns (bool);
}Development Phase
Writing smart contracts requires understanding the blockchain's execution model. Solidity remains the dominant language for EVM-compatible chains, while Rust powers Solana and other non-EVM platforms. Development involves implementing the designed logic with careful attention to:
- Integer overflow/underflow: Modern Solidity (0.8+) includes checks
- Reentrancy: External calls before state updates
- Gas consumption: Minimize expensive operations
- Storage optimization: Minimize storage writes
- Proxy patterns: If upgradeability required
Testing Phase
Comprehensive testing is non-negotiable for contracts handling value. Testing strategies include:
- Unit testing: Individual function behavior
- Integration testing: Contract interactions
- Fuzz testing: Random inputs to find edge cases
- Formal verification: Mathematical proofs of correctness
// Hardhat test example
const { expect } = require("chai");
const { ethers } = require("hardhat");
describe("TokenVesting", function () {
let TokenVesting;
let MockToken;
let vesting;
let token;
let beneficiary;
let owner;
const START_DELAY = 0; // For testing
const CLIFF_DURATION = 365 * 24 * 60 * 60; // 1 year
const VESTING_DURATION = 4 * 365 * 24 * 60 * 60; // 4 years
const TOTAL_ALLOCATED = ethers.utils.parseEther("1000000");
beforeEach(async function () {
[owner, beneficiary] = await ethers.getSigners();
// Deploy mock token
MockToken = await ethers.getContractFactory("MockERC20");
token = await MockToken.deploy("Test Token", "TEST");
await token.deployTransaction.wait();
// Mint tokens to vesting contract
await token.mint(owner.address, TOTAL_ALLOCATED);
await token.transfer(token.address, TOTAL_ALLOCATED);
// Deploy vesting contract
TokenVesting = await ethers.getContractFactory("TokenVesting");
vesting = await TokenVesting.deploy(
beneficiary.address,
(await ethers.provider.getBlock("latest")).timestamp + START_DELAY,
CLIFF_DURATION,
VESTING_DURATION,
TOTAL_ALLOCATED,
token.address
);
await vesting.deployTransaction.wait();
});
describe("Vesting Schedule", function () {
it("Should have correct initial state", async function () {
expect(await vesting.beneficiary()).to.equal(beneficiary.address);
expect(await vesting.totalAllocated()).to.equal(TOTAL_ALLOCATED);
});
it("Should have zero vested before cliff", async function () {
expect(await vesting.getVestedAmount()).to.equal(0);
});
it("Should have correct vesting after cliff", async function () {
// Advance to after cliff
await ethers.provider.send("evm_setNextBlockTimestamp", [
(await ethers.provider.getBlock("latest")).timestamp +
CLIFF_DURATION + 1
]);
await ethers.provider.send("evm_mine");
// At cliff, still nothing vested
expect(await vesting.getVestedAmount()).to.equal(0);
// Advance to mid-vesting
await ethers.provider.send("evm_setNextBlockTimestamp", [
(await ethers.provider.getBlock("latest")).timestamp +
(VESTING_DURATION - CLIFF_DURATION) / 2
]);
await ethers.provider.send("evm_mine");
const vested = await vesting.getVestedAmount();
expect(vested).to.be.gt(0);
expect(vested).to.lt(TOTAL_ALLOCATED);
});
});
});Deployment Phase
Contract deployment involves paying gas fees, receiving a contract address, and verifying the code on block explorers. Deployment considerations include:
- Constructor arguments: Encoded with deployment transaction
- Gas estimation: Account for variable gas costs
- Address generation: Deterministic addresses via CREATE2
- Verification: Source code published for transparency
Security Vulnerabilities and Best Practices
Reentrancy Attack
Reentrancy occurs when a malicious contract calls back into the vulnerable contract before the first execution completes. The classic DAO hack exploited this vulnerability.
// VULNERABLE - Reentrancy
function withdraw() external {
uint256 balance = balances[msg.sender];
require(balance > 0, "No balance");
// External call before state update
(bool success, ) = msg.sender.call{value: balance}("");
require(success, "Transfer failed");
// State update after external call - TOO LATE
balances[msg.sender] = 0;
}
// SECURE - Reentrancy guard
function withdraw() external nonReentrant {
uint256 balance = balances[msg.sender];
require(balance > 0, "No balance");
// State update before external call
balances[msg.sender] = 0;
// External call after state update
(bool success, ) = msg.sender.call{value: balance}("");
require(success, "Transfer failed");
}Integer Overflow and Underflow
Before Solidity 0.8, arithmetic operations could wrap around. The King of the Hill bug demonstrated this vulnerability.
// VULNERABLE (pre-0.8)
function addToPool(uint256 _amount) external {
require(participants[msg.sender] == 0, "Already participating");
participantCount += 1;
participants[msg.sender] = _amount;
poolBalance += _amount; // Could overflow
}
// SECURE (0.8+) - Built-in overflow checks
function addToPool(uint256 _amount) external {
require(participants[msg.sender] == 0, "Already participating");
participantCount += 1;
participants[msg.sender] = _amount;
poolBalance += _amount; // Checks automatically in 0.8+
}
// SECURE (explicit, any version)
using SafeMath for uint256;
function addToPool(uint256 _amount) external {
require(participants[msg.sender] == 0, "Already participating");
participantCount = participantCount.add(1);
participants[msg.sender] = _amount;
poolBalance = poolBalance.add(_amount);
}Front-Running
Transactions are visible in mempool before inclusion, enabling front-running. Solutions include:
// Commit-reveal scheme
contract DutchAuction {
bytes32 public commitment;
uint256 public revealTime;
function commit(bytes32 _commitment) external payable {
require(commitment == bytes32(0), "Already committed");
commitment = _commitment;
}
function reveal(uint256 _secret, uint256 _amount) external {
require(block.timestamp >= revealTime, "Not yet");
require(
keccak256(abi.encodePacked(msg.sender, _secret, _amount))
== commitment,
"Invalid reveal"
);
// Process purchase
// ...
}
}Access Control Vulnerabilities
Missing or incorrect access control enables unauthorized actions.
// VULNERABLE - No access control
function setOwner(address _newOwner) external {
owner = _newOwner;
}
// SECURE - Explicit access control
address public owner;
modifier onlyOwner() {
require(msg.sender == owner, "Not owner");
_;
}
function setOwner(address _newOwner) external onlyOwner {
owner = _newOwner;
}Frontend-Run Attack Patterns
| Vulnerability | Description | Mitigation |
|---|---|---|
| Reentrancy | External calls before state updates | Checks-effects-interactions pattern |
| Integer Overflow | Arithmetic wrapping | SafeMath or Solidity 0.8+ |
| Front-Running | MEV extraction | Commit-reveal, private mempools |
| Access Control | Missing auth modifiers | OpenZeppelin AccessControl |
| Oracle Manipulation | Price feeds exploited | TWAP, multiple sources, Uniswap V3 |
| Flash Loan Attacks | Mass liquidation | Rate limiting, circuit breakers |
Gas Optimization Strategies
Storage vs Memory
Storage operations cost significantly more than memory. Minimize storage writes.
// EXPENSIVE - Multiple storage writes
function updateUserPoints(address user, uint256 points) external {
users[user].points = points; // SLOAD + SSTORE
users[user].lastUpdated = block.timestamp; // SLOAD + SSTORE
}
// CHEAPER - Single storage write with struct
function updateUserPoints(address user, uint256 points) external {
User storage u = users[user];
uint256 oldPoints = u.points;
u.points = points;
u.lastUpdated = block.timestamp;
// Additional processing using memory copies
emit PointsUpdated(user, oldPoints, points);
}Unchecked External Calls
External calls cost at least 2600 gas. Use them wisely.
// Minimize external calls through batching
// Instead of multiple calls:
IERC20(token).transfer(a, amount);
IERC20(token).transfer(b, amount);
IERC20(token).transfer(c, amount);
// Use batch transfer
function batchTransfer(address[] calldata recipients, uint256[] calldata amounts)
external
{
require(recipients.length == amounts.length, "Length mismatch");
// Cache token address
address tokenAddr = address(token);
for (uint256 i = 0; i < recipients.length; i++) {
// Unchecked external call per recipient
IERC20(tokenAddr).transfer(recipients[i], amounts[i]);
}
}Packing and Packing
Solidity packs multiple variables into single storage slot when possible.
// INEFFICIENT - Multiple slots
struct User {
uint256 id; // Slot 1
uint256 score; // Slot 2
uint256 lastActive; // Slot 3
}
// EFFICIENT - Packed into fewer slots
struct User {
uint128 id; // Slot 1 (128 bits)
uint128 score; // Slot 1 (continued)
uint256 lastActive; // Slot 2
}Gas Optimization Checklist
- Use calldata instead of memory for external function parameters
- Cache storage variables in memory before loops
- Use immutable for constants that don't change
- Emit events after state changes efficiently
- Use bit shifts for multiplication/division by powers of 2
- Avoid string concatenation in production
Development Tools and Frameworks
Hardhat
Hardhat provides a flexible development environment with Solidity debugging, testing, and deployment.
// hardhat.config.js
require("@nomicfoundation/hardhat-toolbox");
require("hardhat-deploy");
require("dotenv").config();
module.exports = {
solidity: {
version: "0.8.19",
settings: {
optimizer: {
enabled: true,
runs: 200,
},
viaIR: true,
},
},
networks: {
hardhat: {
forking: {
url: process.env.MAINNET_RPC_URL,
blockNumber: 17500000,
},
},
mainnet: {
url: process.env.MAINNET_RPC_URL,
accounts: [process.env.PRIVATE_KEY],
},
},
gasReporter: {
enabled: true,
currency: "USD",
gasPrice: 30,
},
etherscan: {
apiKey: process.env.ETHERSCAN_API_KEY,
},
};Foundry
Foundry offers extremely fast testing with Forge and Cast CLI tools.
// test/Vesting.t.sol
pragma solidity ^0.8.19;
import { Test, console2 } from "forge-std/Test.sol";
import { TokenVesting } from "../src/TokenVesting.sol";
import { MockERC20 } from "../src/MockERC20.sol";
contract VestingTest is Test {
TokenVesting public vesting;
MockERC20 public token;
address public beneficiary;
address public owner;
uint256 START_DELAY = 0;
uint256 CLIFF_DURATION = 365 days;
uint256 VESTING_DURATION = 4 * 365 days;
uint256 TOTAL_ALLOCATED = 1_000_000 ether;
function setUp() public {
owner = makeAddr("owner");
beneficiary = makeAddr("beneficiary");
vm.deal(owner, 0);
// Deploy token
token = new MockERC20("Test", "TEST");
// Mint and setup
token.mint(owner, TOTAL_ALLOCATED);
token.transfer(address(vesting), TOTAL_ALLOCATED);
// Deploy vesting
vesting = new TokenVesting(
beneficiary,
block.timestamp + START_DELAY,
CLIFF_DURATION,
VESTING_DURATION,
TOTAL_ALLOCATED,
address(token)
);
}
function testInitialState() public {
assertEq(vesting.beneficiary(), beneficiary);
assertEq(vesting.totalAllocated(), TOTAL_ALLOCATED);
}
function testNoVestingBeforeCliff() public {
vm.warp(block.timestamp + CLIFF_DURATION - 1);
assertEq(vesting.getVestedAmount(), 0);
}
}Security Analysis Tools
| Tool | Purpose | Strengths |
|---|---|---|
| Slither | Static analysis | Detects common vulnerabilities |
| Mythril | Security analysis | Symbolic execution |
| Echidna | Fuzz testing | Property-based testing |
| Manticore | Symbolic execution | Bug hunting |
| Certora | Formal verification | Mathematical proofs |
Upgrade Patterns
Proxy Pattern
Upgradeability enables fixing bugs and adding features after deployment.
// Transparent Proxy Pattern
contract TransparentProxy {
address public implementation;
address public admin;
modifier ifAdmin() {
require(msg.sender == admin, "Not admin");
_;
}
constructor(address _implementation) {
admin = msg.sender;
implementation = _implementation;
}
function upgradeTo(address _newImplementation) external ifAdmin {
implementation = _newImplementation;
}
fallback() external payable {
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()) }
}
}
}
// Diamond Pattern (ERC-2535)
interface IDiamondCut {
enum FacetCutAction { Add, Replace, Remove }
struct FacetCut {
address facetAddress;
FacetCutAction action;
bytes4[] functionSelectors;
}
function diamondCut(
FacetCut[] calldata _diamondCut,
address _init,
bytes calldata _calldata
) external;
function facetFunctionSelectors(address _facet)
external view returns (bytes4[] memory);
}Diamond Standard (ERC-2535)
The Diamond pattern enables modular contracts with multiple facet implementations.
contract Diamond is IDiamondCut {
struct DiamondStorage {
mapping(bytes4 => address) selectorToFacet;
mapping(address => uint16) facetToFunctionCount;
address owner;
}
DiamondStorage ds;
function diamondCut(
FacetCut[] calldata _diamondCut,
address _init,
bytes calldata _calldata
) external {
require(msg.sender == ds.owner, "Not owner");
for (uint256 i = 0; i < _diamondCut.length; i++) {
address facet = _diamondCut[i].facetAddress;
bytes4[] memory selectors = _diamondCut[i].functionSelectors;
FacetCutAction action = _diamondCut[i].action;
if (action == FacetCutAction.Add) {
addFunctions(facet, selectors);
} else if (action == FacetCutAction.Replace) {
replaceFunctions(facet, selectors);
} else if (action == FacetCutAction.Remove) {
removeFunctions(facet, selectors);
}
}
}
function addFunctions(address _facet, bytes4[] memory _selectors)
internal
{
require(_facet != address(0), "Invalid facet");
for (uint256 i = 0; i < _selectors.length; i++) {
ds.selectorToFacet[_selectors[i]] = _facet;
}
}
// ... other functions
}UUPS vs Transparent Proxy
UUPS (Universal Upgradeable Proxy Standard) moves upgrade logic into the implementation, enabling cheaper proxies.
Conclusion
Smart contract development requires mastery of blockchain execution models, security patterns, and optimization techniques. The field continues evolving with new languages, frameworks, and verification methods. Developers must balance security, efficiency, and functionality while building applications that handle real value.
The investment in testing, auditing, and formal verification pays dividends through reduced exploits and user trust. Understanding these fundamentals enables building the next generation of decentralized applications.