Ethereum Smart Contract Development Complete Guide
Overview
Ethereum smart contract development encompasses the entire lifecycle from design to deployment. This guide covers every aspect with working code examples.
Project Structure
my-eth-project/
āāā contracts/
ā āāā interfaces/
ā ā āāā IToken.sol
ā āāā libraries/
ā ā āāā SafeMath.sol
ā āāā tokens/
ā ā āāā ERC20Token.sol
ā ā āāā ERC721NFT.sol
ā āāā multisig/
ā ā āāā MultiSigWallet.sol
ā āāā proxy/
ā āāā Proxy.sol
āāā scripts/
ā āāā deploy-erc20.ts
ā āāā deploy-nft.ts
ā āāā verify.ts
āāā test/
ā āāā ERC20Token.test.ts
ā āāā ERC721NFT.test.ts
ā āāā MultiSig.test.ts
āāā hardhat.config.ts
āāā package.json
āāā .env
Complete Hardhat Setup
# Initialize project
mkdir my-eth-project && cd my-eth-project
npm init -y
# Install dependencies
npm install --save-dev hardhat @nomicfoundation/hardhat-toolbox
npm install dotenv @openzeppelin/contracts
# Initialize Hardhat
npx hardhat init
{
"name": "my-eth-project",
"version": "1.0.0",
"scripts": {
"compile": "hardhat compile",
"test": "hardhat test",
"deploy:goerli": "hardhat run scripts/deploy.ts --network goerli",
"deploy:mainnet": "hardhat run scripts/deploy.ts --network mainnet",
"verify": "hardhat verify --network mainnet"
},
"devDependencies": {
"hardhat": "^2.19.0",
"@nomicfoundation/hardhat-toolbox": "^3.0.0",
"dotenv": "^16.3.1"
},
"dependencies": {
"@openzeppelin/contracts": "^5.0.0"
}
}
// hardhat.config.ts
import { HardhatUserConfig } from "hardhat/config";
import "@nomicfoundation/hardhat-toolbox";
import dotenv from "dotenv";
dotenv.config();
const config: HardhatUserConfig = {
solidity: {
version: "0.8.19",
settings: {
optimizer: {
enabled: true,
runs: 200,
},
viaIR: true,
},
},
networks: {
hardhat: {
forking: {
url: `https://eth-mainnet.g.alchemy.com/v2/${process.env.ALCHEMY_API_KEY}`,
},
},
goerli: {
url: `https://eth-goerli.g.alchemy.com/v2/${process.env.ALCHEMY_API_KEY}`,
accounts: [process.env.PRIVATE_KEY!],
},
mainnet: {
url: `https://eth-mainnet.g.alchemy.com/v2/${process.env.ALCHEMY_API_KEY}`,
accounts: [process.env.PRIVATE_KEY!],
},
},
etherscan: {
apiKey: process.env.ETHERSCAN_API_KEY,
},
};
export default config;
ERC20 Token Contract
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
contract MyToken is ERC20, ERC20Burnable, ERC20Permit, AccessControl {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
uint256 public constant MAX_SUPPLY = 1_000_000 * 10 ** 18;
bool private _paused;
event TokensMinted(address indexed to, uint256 amount);
event TokensBurned(address indexed from, uint256 amount);
modifier whenNotPaused() {
require(!_paused, "Token is paused");
_;
}
constructor(
string memory name,
string memory symbol,
uint256 initialSupply
) ERC20(name, symbol) ERC20Permit(name) {
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(MINTER_ROLE, msg.sender);
_grantRole(PAUSER_ROLE, msg.sender);
if (initialSupply > 0) {
_mint(msg.sender, initialSupply * 10 ** decimals());
}
}
function mint(address to, uint256 amount)
public
onlyRole(MINTER_ROLE)
whenNotPaused
{
require(totalSupply() + amount <= MAX_SUPPLY, "Exceeds max supply");
_mint(to, amount);
emit TokensMinted(to, amount);
}
function burn(uint256 amount) public override(ERC20Burnable) whenNotPaused {
super.burn(amount);
emit TokensBurned(msg.sender, amount);
}
function pause() public onlyRole(PAUSER_ROLE) {
_paused = true;
}
function unpause() public onlyRole(PAUSER_ROLE) {
_paused = false;
}
function supportsInterface(bytes4 interfaceId)
public
view
override(AccessControl)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
ERC721 NFT Contract
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
contract MyNFT is ERC721, ERC721URIStorage, ERC721Enumerable, Ownable {
using Strings for uint256;
uint256 private _tokenIdCounter;
uint256 public mintPrice;
uint256 public maxSupply;
string private _baseTokenURI;
mapping(uint256 => uint256) public royalties;
constructor(
string memory name,
string memory symbol,
string memory baseURI,
uint256 _mintPrice,
uint256 _maxSupply
) ERC721(name, symbol) {
_baseTokenURI = baseURI;
mintPrice = _mintPrice;
maxSupply = _maxSupply;
}
function mint(uint256 quantity) public payable {
require(quantity > 0, "Quantity must be > 0");
require(
_tokenIdCounter + quantity <= maxSupply,
"Exceeds max supply"
);
require(
msg.value >= mintPrice * quantity,
"Insufficient payment"
);
for (uint256 i = 0; i < quantity; i++) {
_safeMint(msg.sender, _tokenIdCounter);
_tokenIdCounter++;
}
}
function setTokenURI(uint256 tokenId, string memory tokenURI)
public
onlyOwner
{
_setTokenURI(tokenId, tokenURI);
}
function setBaseURI(string memory baseURI) public onlyOwner {
_baseTokenURI = baseURI;
}
function setMintPrice(uint256 _mintPrice) public onlyOwner {
mintPrice = _mintPrice;
}
function setRoyalties(uint256 tokenId, uint256 royaltyPercent)
public
onlyOwner
{
require(royaltyPercent <= 10, "Max 10% royalty");
royalties[tokenId] = royaltyPercent;
}
function _baseURI() internal view override returns (string memory) {
return _baseTokenURI;
}
function tokenURI(uint256 tokenId)
public
view
override(ERC721, ERC721URIStorage)
returns (string memory)
{
return super.tokenURI(tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721URIStorage, ERC721Enumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function totalSupply() public view override returns (uint256) {
return _tokenIdCounter;
}
}
Multi-Sig Wallet Contract
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
contract MultiSigWallet {
event SubmitTransaction(
address indexed owner,
uint256 indexed txIndex,
address indexed to,
uint256 value,
bytes data
);
event ConfirmTransaction(address indexed owner, uint256 indexed txIndex);
event RevokeConfirmation(address indexed owner, uint256 indexed txIndex);
event ExecuteTransaction(address indexed owner, uint256 indexed txIndex);
struct Transaction {
address to;
uint256 value;
bytes data;
bool executed;
uint256 numConfirmations;
}
address[] public owners;
mapping(address => bool) public isOwner;
uint256 public numConfirmationsRequired;
Transaction[] public transactions;
mapping(uint256 => mapping(address => bool)) public isConfirmed;
modifier onlyOwner() {
require(isOwner[msg.sender], "not owner");
_;
}
modifier txExists(uint256 _txIndex) {
require(_txIndex < transactions.length, "tx does not exist");
_;
}
modifier notExecuted(uint256 _txIndex) {
require(!transactions[_txIndex].executed, "tx already executed");
_;
}
modifier notConfirmed(uint256 _txIndex) {
require(!isConfirmed[_txIndex][msg.sender], "tx already confirmed");
_;
}
constructor(address[] memory _owners, uint256 _numConfirmationsRequired) {
require(_owners.length > 0, "owners required");
require(
_numConfirmationsRequired > 0 &&
_numConfirmationsRequired <= _owners.length,
"invalid number of confirmations"
);
for (uint256 i = 0; i < _owners.length; i++) {
address owner = _owners[i];
require(owner != address(0), "invalid owner");
require(!isOwner[owner], "owner not unique");
isOwner[owner] = true;
owners.push(owner);
}
numConfirmationsRequired = _numConfirmationsRequired;
}
function submitTransaction(
address _to,
uint256 _value,
bytes memory _data
) public onlyOwner {
uint256 txIndex = transactions.length;
transactions.push(
Transaction({
to: _to,
value: _value,
data: _data,
executed: false,
numConfirmations: 0
})
);
emit SubmitTransaction(msg.sender, txIndex, _to, _value, _data);
}
function confirmTransaction(uint256 _txIndex)
public
onlyOwner
txExists(_txIndex)
notExecuted(_txIndex)
notConfirmed(_txIndex)
{
Transaction storage transaction = transactions[_txIndex];
transaction.numConfirmations += 1;
isConfirmed[_txIndex][msg.sender] = true;
emit ConfirmTransaction(msg.sender, _txIndex);
}
function executeTransaction(uint256 _txIndex)
public
onlyOwner
txExists(_txIndex)
notExecuted(_txIndex)
{
Transaction storage transaction = transactions[_txIndex];
require(
transaction.numConfirmations >= numConfirmationsRequired,
"cannot execute tx - not enough confirmations"
);
transaction.executed = true;
(bool success, ) = transaction.to.call{value: transaction.value}(
transaction.data
);
require(success, "tx failed");
emit ExecuteTransaction(msg.sender, _txIndex);
}
function revokeConfirmation(uint256 _txIndex)
public
onlyOwner
txExists(_txIndex)
notExecuted(_txIndex)
{
Transaction storage transaction = transactions[_txIndex];
require(isConfirmed[_txIndex][msg.sender], "tx not confirmed");
transaction.numConfirmations -= 1;
isConfirmed[_txIndex][msg.sender] = false;
emit RevokeConfirmation(msg.sender, _txIndex);
}
function getTransactionCount() public view returns (uint256) {
return transactions.length;
}
function getOwners() public view returns (address[] memory) {
return owners;
}
}
Deployment Scripts
// scripts/deploy-erc20.ts
import { ethers } from "hardhat";
async function main() {
const [deployer] = await ethers.getSigners();
console.log("Deploying with:", deployer.address);
const Token = await ethers.getContractFactory("MyToken");
const token = await Token.deploy(
"My Token",
"MTK",
1000000 // 1M tokens
);
await token.waitForDeployment();
const address = await token.getAddress();
console.log("MyToken deployed to:", address);
// Verify on Etherscan
console.log("Waiting for block confirmations...");
await token.deploymentTransaction()?.wait(5);
console.log("Verifying contract...");
await run("verify:verify", {
address: address,
constructorArguments: ["My Token", "MTK", 1000000],
});
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});
// scripts/deploy-nft.ts
import { ethers } from "hardhat";
async function main() {
const [deployer] = await ethers.getSigners();
const NFT = await ethers.getContractFactory("MyNFT");
const nft = await NFT.deploy(
"My NFT Collection",
"MNFT",
"ipfs://QmYourBaseURI/",
ethers.parseEther("0.05"), // 0.05 ETH mint price
10000 // max supply
);
await nft.waitForDeployment();
const address = await nft.getAddress();
console.log("MyNFT deployed to:", address);
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});
Testing with Chai/Mocha
// test/ERC20Token.test.ts
import { expect } from "chai";
import { ethers } from "hardhat";
import { loadFixture } from "@nomicfoundation/hardhat-toolbox/network-helpers";
describe("MyToken", function () {
async function deployFixture() {
const [owner, addr1, addr2] = await ethers.getSigners();
const Token = await ethers.getContractFactory("MyToken");
const token = await Token.deploy("My Token", "MTK", 1000000);
return { token, owner, addr1, addr2 };
}
describe("Deployment", function () {
it("Should set correct name and symbol", async function () {
const { token } = await loadFixture(deployFixture);
expect(await token.name()).to.equal("My Token");
expect(await token.symbol()).to.equal("MTK");
});
it("Should mint initial supply to deployer", async function () {
const { token, owner } = await loadFixture(deployFixture);
const totalSupply = await token.totalSupply();
expect(await token.balanceOf(owner.address)).to.equal(totalSupply);
});
it("Should have correct max supply", async function () {
const { token } = await loadFixture(deployFixture);
expect(await token.MAX_SUPPLY()).to.equal(
ethers.parseEther("1000000")
);
});
});
describe("Minting", function () {
it("Should mint tokens when called by minter", async function () {
const { token, addr1 } = await loadFixture(deployFixture);
await token.mint(addr1.address, ethers.parseEther("100"));
expect(await token.balanceOf(addr1.address)).to.equal(
ethers.parseEther("100")
);
});
it("Should fail when non-minter tries to mint", async function () {
const { token, addr1 } = await loadFixture(deployFixture);
await expect(
token.connect(addr1).mint(addr1.address, ethers.parseEther("100"))
).to.be.revertedWith("AccessControl");
});
it("Should fail when exceeding max supply", async function () {
const { token, owner } = await loadFixture(deployFixture);
const maxSupply = await token.MAX_SUPPLY();
const currentSupply = await token.totalSupply();
const mintAmount = maxSupply - currentSupply + 1n;
await expect(
token.mint(owner.address, mintAmount)
).to.be.revertedWith("Exceeds max supply");
});
});
describe("Burning", function () {
it("Should burn tokens", async function () {
const { token, owner } = await loadFixture(deployFixture);
const burnAmount = ethers.parseEther("100");
const initialBalance = await token.balanceOf(owner.address);
await token.burn(burnAmount);
expect(await token.balanceOf(owner.address)).to.equal(
initialBalance - burnAmount
);
});
});
describe("Pausing", function () {
it("Should pause and unpause", async function () {
const { token, owner } = await loadFixture(deployFixture);
await token.pause();
expect(await token.paused()).to.be.true;
await token.unpause();
expect(await token.paused()).to.be.false;
});
it("Should not allow minting when paused", async function () {
const { token, addr1 } = await loadFixture(deployFixture);
await token.pause();
await expect(
token.mint(addr1.address, ethers.parseEther("100"))
).to.be.revertedWith("Token is paused");
});
});
});
// test/MultiSig.test.ts
import { expect } from "chai";
import { ethers } from "hardhat";
import { loadFixture } from "@nomicfoundation/hardhat-toolbox/network-helpers";
describe("MultiSigWallet", function () {
async function deployFixture() {
const [owner1, owner2, owner3, nonOwner] = await ethers.getSigners();
const owners = [owner1.address, owner2.address, owner3.address];
const numConfirmationsRequired = 2;
const Wallet = await ethers.getContractFactory("MultiSigWallet");
const wallet = await Wallet.deploy(owners, numConfirmationsRequired);
// Fund the wallet
await owner1.sendTransaction({
to: await wallet.getAddress(),
value: ethers.parseEther("10"),
});
return { wallet, owner1, owner2, owner3, nonOwner };
}
describe("Deployment", function () {
it("Should set correct owners", async function () {
const { wallet, owner1, owner2, owner3 } = await loadFixture(
deployFixture
);
expect(await wallet.isOwner(owner1.address)).to.be.true;
expect(await wallet.isOwner(owner2.address)).to.be.true;
expect(await wallet.isOwner(owner3.address)).to.be.true;
});
it("Should set correct confirmations required", async function () {
const { wallet } = await loadFixture(deployFixture);
expect(await wallet.numConfirmationsRequired()).to.equal(2);
});
});
describe("Transactions", function () {
it("Should submit transaction", async function () {
const { wallet, owner1, nonOwner } = await loadFixture(deployFixture);
await wallet
.connect(owner1)
.submitTransaction(nonOwner.address, ethers.parseEther("1"), "0x");
expect(await wallet.getTransactionCount()).to.equal(1);
});
it("Should confirm and execute transaction", async function () {
const { wallet, owner1, owner2, nonOwner } = await loadFixture(
deployFixture
);
await wallet
.connect(owner1)
.submitTransaction(nonOwner.address, ethers.parseEther("1"), "0x");
await wallet.connect(owner1).confirmTransaction(0);
await wallet.connect(owner2).confirmTransaction(0);
const initialBalance = await ethers.provider.getBalance(
nonOwner.address
);
await wallet.connect(owner1).executeTransaction(0);
const finalBalance = await ethers.provider.getBalance(nonOwner.address);
expect(finalBalance - initialBalance).to.equal(ethers.parseEther("1"));
});
});
});
Gas Optimization Techniques
| Technique | Gas Saved | Complexity |
|---|---|---|
| Storage Packing | 20-50% | Medium |
| Calldata vs Memory | 10-30% | Low |
| Short-Circuiting | 5-15% | Low |
| Unchecked Math | 10-20% | Low |
| Batch Operations | 30-60% | High |
| Assembly/Yul | 40-80% | Very High |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
contract GasOptimized {
// Storage packing - bools and small uints together
struct PackedData {
uint128 amount; // 16 bytes
uint64 timestamp; // 8 bytes
uint32 counter; // 4 bytes
bool isActive; // 1 byte
bool isPaused; // 1 byte
// Total: 30 bytes (fits in 2 storage slots)
}
// Use calldata for read-only function params
function processArray(uint256[] calldata data) external pure returns (uint256) {
uint256 sum = 0;
for (uint256 i = 0; i < data.length; i++) {
sum += data[i];
}
return sum;
}
// Unchecked math for safe operations
function unsafeIncrement(uint256[] storage data) external {
for (uint256 i = 0; i < data.length;) {
data[i] += 1;
unchecked { i++; } // Safe because i < length
}
}
// Batch operations
mapping(address => uint256) public balances;
function batchTransfer(
address[] calldata recipients,
uint256[] calldata amounts
) external {
require(recipients.length == amounts.length, "Length mismatch");
for (uint256 i = 0; i < recipients.length;) {
balances[recipients[i]] += amounts[i];
unchecked { i++; }
}
}
}
Etherscan Verification
// scripts/verify.ts
import { run } from "hardhat";
async function verifyContract(
address: string,
constructorArgs: any[]
) {
try {
await run("verify:verify", {
address: address,
constructorArguments: constructorArgs,
});
console.log("Contract verified successfully!");
} catch (error: any) {
if (error.message.includes("Already Verified")) {
console.log("Contract is already verified");
} else {
console.error("Verification failed:", error);
}
}
}
// Usage
verifyContract("0x1234...", ["My Token", "MTK", 1000000]);
Security Best Practices
| Vulnerability | Prevention | Severity |
|---|---|---|
| Reentrancy | Checks-Effects-Interactions | Critical |
| Integer Overflow | Solidity 0.8+ / SafeMath | Critical |
| Front-Running | Commit-Reveal | High |
| Access Control | OpenZeppelin RBAC | Critical |
| Flash Loan Attacks | Time-Weighted Prices | High |
| Oracle Manipulation | Multiple Oracles | High |
Gas Cost Formula
The total gas cost for a transaction can be calculated as:
Where:
- Base Gas = 21,000 (for simple transfers)
- OpCost = operation-specific gas cost
- Gas Price = current network gas price (in Gwei)
Real-World Example: Uniswap V2 Pair
// Simplified Uniswap V2 Pair concept
contract SimpleAMM {
uint256 public constant LIQUIDITY_MINIMUM = 10 ** 15;
uint112 private reserve0;
uint112 private reserve1;
uint32 private blockTimestampLast;
function getReserves() public view returns (
uint112 _reserve0,
uint112 _reserve1,
uint32 _blockTimestampLast
) {
_reserve0 = reserve0;
_reserve1 = reserve1;
_blockTimestampLast = blockTimestampLast;
}
function _update(
uint256 balance0,
uint256 balance1,
uint112 _reserve0,
uint112 _reserve1
) private {
require(balance0 <= uint112(-1) && balance1 <= uint112(-1), "OVERFLOW");
uint32 blockTimestamp = uint32(block.timestamp % 2 ** 32);
uint32 timeElapsed;
unchecked { timeElapsed = blockTimestamp - blockTimestampLast; }
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// Price oracle calculation
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
}
}
Trade-Offs
| Approach | Pros | Cons | Use Case |
|---|---|---|---|
| Upgradeable Proxy | Can fix bugs | Centralization risk | Long-lived protocols |
| Immutable Contracts | Trustless | Cannot fix bugs | Simple tokens |
| Multi-Sig | Distributed control | Slower execution | Treasury management |
| Diamond Pattern | Unlimited size | Complexity | Large systems |
Interview Questions
-
What is the Checks-Effects-Interactions pattern and why is it important?
- Answer: The pattern requires performing all validations (checks) first, then updating state (effects), and finally interacting with external contracts (interactions). This prevents reentrancy attacks by ensuring state is updated before external calls.
-
Explain the difference between
tx.originandmsg.sender. Why shouldtx.originnot be used for authorization?- Answer:
tx.originis the original external account that initiated the transaction, whilemsg.senderis the immediate caller. Usingtx.originfor authorization is dangerous because it can be exploited through phishing attacks where a malicious contract calls your contract while the user's account istx.origin.
- Answer:
-
What are the trade-offs between using
selfdestructand a pause mechanism?- Answer:
selfdestructpermanently destroys the contract and sends remaining ETH to a designated address, which is irreversible. A pause mechanism allows temporary disabling of functionality while maintaining the ability to resume.selfdestructshould only be used for emergency recovery, while pausing is better for temporary issues.
- Answer:
Quiz Questions
-
What is the minimum gas required for a simple ETH transfer?
- A) 21,000
- B) 53,000
- C) 100,000
- D) 200,000
-
Which OpenZeppelin contract provides reentrancy protection?
- A) Ownable
- B) Pausable
- C) ReentrancyGuard
- D) AccessControl
-
What is the maximum value that can be stored in a
uint128?- A) 2^128
- B) 2^128 - 1
- C) 2^256
- D) 2^256 - 1