ERC20 ERC721 Token Development Masterclass
Overview
Token development is fundamental to Ethereum. This masterclass covers all major token standards with complete implementations and real-world examples.
ERC20 Full Implementation
// 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/token/ERC20/extensions/ERC20Votes.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
contract GovernanceToken is
ERC20,
ERC20Burnable,
ERC20Permit,
ERC20Votes,
AccessControl
{
using Counters for Counters.Counter;
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
uint256 public constant MAX_SUPPLY = 100_000_000 * 10 ** 18; // 100M tokens
Counters.Counter private _nonce;
mapping(address => uint256) public votingPower;
mapping(address => uint256) public lastClaimTime;
uint256 public constant CLAIM_INTERVAL = 1 days;
uint256 public rewardRate = 100 * 10 ** 18; // 100 tokens per claim
event RewardClaimed(address indexed account, uint256 amount);
event RewardRateUpdated(uint256 oldRate, uint256 newRate);
constructor(
string memory name,
string memory symbol,
uint256 initialSupply
) ERC20(name, symbol) ERC20Permit(name) {
require(initialSupply <= MAX_SUPPLY, "Exceeds max supply");
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(MINTER_ROLE, msg.sender);
_grantRole(PAUSER_ROLE, msg.sender);
if (initialSupply > 0) {
_mint(msg.sender, initialSupply);
}
}
function mint(address to, uint256 amount)
public
onlyRole(MINTER_ROLE)
{
require(totalSupply() + amount <= MAX_SUPPLY, "Exceeds max supply");
_mint(to, amount);
}
function claimReward() external {
require(
block.timestamp >= lastClaimTime[msg.sender] + CLAIM_INTERVAL,
"Too soon to claim"
);
lastClaimTime[msg.sender] = block.timestamp;
_mint(msg.sender, rewardRate);
emit RewardClaimed(msg.sender, rewardRate);
}
function setRewardRate(uint256 _rate) external onlyRole(DEFAULT_ADMIN_ROLE) {
uint256 oldRate = rewardRate;
rewardRate = _rate;
emit RewardRateUpdated(oldRate, _rate);
}
// Required overrides
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal override(ERC20, ERC20Votes) {
super._afterTokenTransfer(from, to, amount);
}
function _mint(address to, uint256 amount)
internal
override(ERC20, ERC20Votes)
{
super._mint(to, amount);
}
function _burn(address account, uint256 amount)
internal
override(ERC20, ERC20Votes)
{
super._burn(account, amount);
}
function nonces(address owner)
public
view
override(ERC20Permit)
returns (uint256)
{
return super.nonces(owner);
}
}
ERC721 NFT Implementation
// 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/token/ERC721/extensions/ERC721Burnable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
contract ArtNFT is
ERC721,
ERC721URIStorage,
ERC721Enumerable,
ERC721Burnable,
Ownable
{
using Strings for uint256;
uint256 private _tokenIdCounter;
uint256 public mintPrice;
uint256 public maxSupply;
uint256 public maxPerWallet;
mapping(address => uint256) public walletMints;
struct RoyaltyInfo {
address recipient;
uint256 percentage; // basis points (100 = 1%)
}
mapping(uint256 => RoyaltyInfo) public royalties;
RoyaltyInfo public defaultRoyalty;
string private _baseTokenURI;
event NFTMinted(address indexed minter, uint256 indexed tokenId);
event RoyaltySet(uint256 indexed tokenId, address recipient, uint256 percentage);
constructor(
string memory name,
string memory symbol,
string memory baseURI,
uint256 _mintPrice,
uint256 _maxSupply,
uint256 _maxPerWallet
) ERC721(name, symbol) {
_baseTokenURI = baseURI;
mintPrice = _mintPrice;
maxSupply = _maxSupply;
maxPerWallet = _maxPerWallet;
defaultRoyalty = RoyaltyInfo({
recipient: msg.sender,
percentage: 500 // 5%
});
}
function mint(uint256 quantity) public payable {
require(quantity > 0, "Quantity must be > 0");
require(
_tokenIdCounter + quantity <= maxSupply,
"Exceeds max supply"
);
require(
walletMints[msg.sender] + quantity <= maxPerWallet,
"Exceeds max per wallet"
);
require(
msg.value >= mintPrice * quantity,
"Insufficient payment"
);
for (uint256 i = 0; i < quantity; i++) {
_safeMint(msg.sender, _tokenIdCounter);
// Set default royalty
royalties[_tokenIdCounter] = defaultRoyalty;
emit NFTMinted(msg.sender, _tokenIdCounter);
_tokenIdCounter++;
}
walletMints[msg.sender] += quantity;
}
function setBaseURI(string calldata baseURI) public onlyOwner {
_baseTokenURI = baseURI;
}
function setMintPrice(uint256 _mintPrice) public onlyOwner {
mintPrice = _mintPrice;
}
function setMaxPerWallet(uint256 _max) public onlyOwner {
maxPerWallet = _max;
}
function setRoyalty(uint256 tokenId, address recipient, uint256 percentage)
public
onlyOwner
{
require(percentage <= 1000, "Max 10% royalty");
royalties[tokenId] = RoyaltyInfo({
recipient: recipient,
percentage: percentage
});
emit RoyaltySet(tokenId, recipient, percentage);
}
function setDefaultRoyalty(address recipient, uint256 percentage)
public
onlyOwner
{
require(percentage <= 1000, "Max 10% royalty");
defaultRoyalty = RoyaltyInfo({
recipient: recipient,
percentage: percentage
});
}
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount)
{
RoyaltyInfo memory royalty = royalties[tokenId];
if (royalty.recipient == address(0)) {
royalty = defaultRoyalty;
}
royaltyAmount = (salePrice * royalty.percentage) / 10000;
receiver = royalty.recipient;
}
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;
}
}
ERC1155 Multi-Token
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
contract GameItems is ERC1155, ERC1155Supply, Ownable {
using Strings for uint256;
uint256 public nextTokenId = 1;
struct ItemInfo {
string name;
string uri;
uint256 maxSupply;
uint256 price;
bool exists;
}
mapping(uint256 => ItemInfo) public items;
mapping(uint256 => uint256) public itemSupply;
event ItemCreated(uint256 indexed tokenId, string name, uint256 maxSupply);
event ItemMinted(address indexed to, uint256 indexed tokenId, uint256 quantity);
constructor() ERC1155("") {}
function createItem(
string calldata name,
string calldata uri,
uint256 maxSupply,
uint256 price
) external onlyOwner returns (uint256) {
uint256 tokenId = nextTokenId;
items[tokenId] = ItemInfo({
name: name,
uri: uri,
maxSupply: maxSupply,
price: price,
exists: true
});
nextTokenId++;
emit ItemCreated(tokenId, name, maxSupply);
return tokenId;
}
function mint(
address to,
uint256 tokenId,
uint256 quantity
) public payable {
require(items[tokenId].exists, "Item does not exist");
require(quantity > 0, "Quantity must be > 0");
require(
itemSupply[tokenId] + quantity <= items[tokenId].maxSupply,
"Exceeds max supply"
);
require(
msg.value >= items[tokenId].price * quantity,
"Insufficient payment"
);
_mint(to, tokenId, quantity, "");
itemSupply[tokenId] += quantity;
emit ItemMinted(to, tokenId, quantity);
}
function mintBatch(
address to,
uint256[] calldata ids,
uint256[] calldata quantities
) public payable {
require(ids.length == quantities.length, "Length mismatch");
uint256 totalCost = 0;
for (uint256 i = 0; i < ids.length; i++) {
require(items[ids[i]].exists, "Item does not exist");
require(quantities[i] > 0, "Quantity must be > 0");
require(
itemSupply[ids[i]] + quantities[i] <= items[ids[i]].maxSupply,
"Exceeds max supply"
);
totalCost += items[ids[i]].price * quantities[i];
}
require(msg.value >= totalCost, "Insufficient payment");
_mintBatch(to, ids, quantities, "");
for (uint256 i = 0; i < ids.length; i++) {
itemSupply[ids[i]] += quantities[i];
emit ItemMinted(to, ids[i], quantities[i]);
}
}
function burn(
address from,
uint256 tokenId,
uint256 quantity
) public {
_burn(from, tokenId, quantity);
itemSupply[tokenId] -= quantity;
}
function setItemURI(uint256 tokenId, string calldata uri) public onlyOwner {
require(items[tokenId].exists, "Item does not exist");
items[tokenId].uri = uri;
}
function setItemPrice(uint256 tokenId, uint256 price) public onlyOwner {
require(items[tokenId].exists, "Item does not exist");
items[tokenId].price = price;
}
function uri(uint256 tokenId) public view override returns (string memory) {
return items[tokenId].uri;
}
function getItemsCount() external view returns (uint256) {
return nextTokenId - 1;
}
}
ERC4626 Tokenized Vault
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC4626.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
contract YieldVault is ERC4626, ERC20Permit, Ownable {
using SafeERC20 for IERC20;
IERC20 public immutable underlying;
uint256 public depositFee = 0; // basis points
uint256 public withdrawalFee = 0; // basis points
uint256 public totalDeposits;
uint256 public totalWithdrawals;
address public feeRecipient;
uint256 public lastYieldUpdate;
uint256 public accumulatedYield;
event DepositFeeUpdated(uint256 oldFee, uint256 newFee);
event WithdrawalFeeUpdated(uint256 oldFee, uint256 newFee);
event YieldAccrued(uint256 amount);
constructor(
IERC20 _asset,
string memory name,
string memory symbol
) ERC20(name, symbol) ERC4626(_asset) ERC20Permit(name) {
underlying = _asset;
feeRecipient = msg.sender;
}
function deposit(uint256 assets, address receiver)
public
override
returns (uint256)
{
uint256 fee = (assets * depositFee) / 10000;
uint256 assetsAfterFee = assets - fee;
if (fee > 0) {
SafeERC20.safeTransfer(underlying, feeRecipient, fee);
}
uint256 shares = super.deposit(assetsAfterFee, receiver);
totalDeposits += assetsAfterFee;
return shares;
}
function withdraw(
uint256 assets,
address receiver,
address owner
) public override returns (uint256) {
uint256 fee = (assets * withdrawalFee) / 10000;
uint256 assetsAfterFee = assets - fee;
uint256 shares = super.withdraw(assetsAfterFee, receiver, owner);
if (fee > 0) {
SafeERC20.safeTransfer(underlying, feeRecipient, fee);
}
totalWithdrawals += assetsAfterFee;
return shares;
}
function convertToAssets(uint256 shares)
public
view
override
returns (uint256)
{
uint256 totalAssets = IERC20(asset()).balanceOf(address(this));
return (shares * totalAssets) / totalSupply();
}
function convertToShares(uint256 assets)
public
view
override
returns (uint256)
{
uint256 totalAssets = IERC20(asset()).balanceOf(address(this));
if (totalAssets == 0) return assets;
return (assets * totalSupply()) / totalAssets;
}
function setDepositFee(uint256 _fee) external onlyOwner {
require(_fee <= 500, "Fee too high"); // Max 5%
uint256 oldFee = depositFee;
depositFee = _fee;
emit DepositFeeUpdated(oldFee, _fee);
}
function setWithdrawalFee(uint256 _fee) external onlyOwner {
require(_fee <= 500, "Fee too high"); // Max 5%
uint256 oldFee = withdrawalFee;
withdrawalFee = _fee;
emit WithdrawalFeeUpdated(oldFee, _fee);
}
function setFeeRecipient(address _recipient) external onlyOwner {
feeRecipient = _recipient;
}
function accrueYield(uint256 amount) external onlyOwner {
accumulatedYield += amount;
lastYieldUpdate = block.timestamp;
emit YieldAccrued(amount);
}
}
Token Vesting
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract TokenVesting is Ownable {
using SafeERC20 for IERC20;
struct VestingSchedule {
address beneficiary;
uint256 totalAmount;
uint256 releasedAmount;
uint256 startTime;
uint256 cliffDuration;
uint256 vestingDuration;
bool revocable;
bool revoked;
}
IERC20 public token;
uint256 public scheduleCount;
mapping(uint256 => VestingSchedule) public schedules;
mapping(address => uint256[]) public beneficiarySchedules;
event VestingCreated(
uint256 indexed scheduleId,
address indexed beneficiary,
uint256 totalAmount,
uint256 startTime
);
event TokensReleased(
uint256 indexed scheduleId,
address indexed beneficiary,
uint256 amount
);
event VestingRevoked(uint256 indexed scheduleId);
constructor(address _token) {
token = IERC20(_token);
}
function createVestingSchedule(
address beneficiary,
uint256 totalAmount,
uint256 startTime,
uint256 cliffDuration,
uint256 vestingDuration,
bool revocable
) external onlyOwner returns (uint256) {
require(beneficiary != address(0), "Invalid beneficiary");
require(totalAmount > 0, "Amount must be > 0");
require(vestingDuration > 0, "Duration must be > 0");
require(cliffDuration <= vestingDuration, "Cliff > duration");
uint256 scheduleId = scheduleCount;
schedules[scheduleId] = VestingSchedule({
beneficiary: beneficiary,
totalAmount: totalAmount,
releasedAmount: 0,
startTime: startTime,
cliffDuration: cliffDuration,
vestingDuration: vestingDuration,
revocable: revocable,
revoked: false
});
beneficiarySchedules[beneficiary].push(scheduleId);
scheduleCount++;
// Transfer tokens to vesting contract
SafeERC20.safeTransferFrom(token, msg.sender, address(this), totalAmount);
emit VestingCreated(scheduleId, beneficiary, totalAmount, startTime);
return scheduleId;
}
function release(uint256 scheduleId) external {
VestingSchedule storage schedule = schedules[scheduleId];
require(schedule.beneficiary == msg.sender, "Not beneficiary");
require(!schedule.revoked, "Vesting revoked");
uint256 releasable = getReleasableAmount(scheduleId);
require(releasable > 0, "No tokens to release");
schedule.releasedAmount += releasable;
SafeERC20.safeTransfer(token, schedule.beneficiary, releasable);
emit TokensReleased(scheduleId, schedule.beneficiary, releasable);
}
function getReleasableAmount(uint256 scheduleId)
public
view
returns (uint256)
{
VestingSchedule storage schedule = schedules[scheduleId];
if (schedule.revoked) return 0;
uint256 vested = getVestedAmount(scheduleId);
return vested - schedule.releasedAmount;
}
function getVestedAmount(uint256 scheduleId)
public
view
returns (uint256)
{
VestingSchedule storage schedule = schedules[scheduleId];
if (block.timestamp < schedule.startTime + schedule.cliffDuration) {
return 0;
}
uint256 elapsed = block.timestamp - schedule.startTime;
if (elapsed >= schedule.vestingDuration) {
return schedule.totalAmount;
}
return (schedule.totalAmount * elapsed) / schedule.vestingDuration;
}
function revoke(uint256 scheduleId) external onlyOwner {
VestingSchedule storage schedule = schedules[scheduleId];
require(schedule.revocable, "Not revocable");
require(!schedule.revoked, "Already revoked");
schedule.revoked = true;
// Return unreleased tokens
uint256 unreleased = schedule.totalAmount - schedule.releasedAmount;
SafeERC20.safeTransfer(token, owner(), unreleased);
emit VestingRevoked(scheduleId);
}
function getBeneficiarySchedules(address beneficiary)
external
view
returns (uint256[] memory)
{
return beneficiarySchedules[beneficiary];
}
}
Governance Token
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Votes.sol";
import "@openzeppelin/contracts/governance/Governor.sol";
import "@openzeppelin/contracts/governance/extensions/GovernorSettings.sol";
import "@openzeppelin/contracts/governance/extensions/GovernorCountingSimple.sol";
import "@openzeppelin/contracts/governance/extensions/GovernorVotes.sol";
import "@openzeppelin/contracts/governance/extensions/GovernorVotesQuorumFraction.sol";
import "@openzeppelin/contracts/governance/extensions/GovernorTimelockControl.sol";
contract GovernorToken is ERC20, ERC20Permit, ERC20Votes {
uint256 private _nonces;
constructor(string memory name, string memory symbol)
ERC20(name, symbol)
ERC20Permit(name)
{}
function mint(address to, uint256 amount) external {
_mint(to, amount);
}
function delegates(address account) public view override returns (address) {
return super.delegates(account);
}
function delegate(address delegatee) public override {
super.delegate(delegatee);
}
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public override {
super.delegateBySig(delegatee, nonce, expiry, v, r, s);
}
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal override(ERC20, ERC20Votes) {
super._afterTokenTransfer(from, to, amount);
}
function _mint(address to, uint256 amount) internal override(ERC20, ERC20Votes) {
super._mint(to, amount);
}
function _burn(address account, uint256 amount) internal override(ERC20, ERC20Votes) {
super._burn(account, amount);
}
function nonces(address owner) public view override returns (uint256) {
return super.nonces(owner);
}
}
contract MyGovernor is
Governor,
GovernorSettings,
GovernorCountingSimple,
GovernorVotes,
GovernorVotesQuorumFraction,
GovernorTimelockControl
{
constructor(IVotes token)
Governor("MyGovernor")
GovernorSettings(7200, 50400, 0) // 1 day voting, 7 days timelock, 0 threshold
GovernorVotes(token)
GovernorVotesQuorumFraction(4)
GovernorTimelockControl(TimelockController)
{}
function votingDelay() public view override(GovernorSettings) returns (uint256) {
return super.votingDelay();
}
function votingPeriod() public view override(GovernorSettings) returns (uint256) {
return super.votingPeriod();
}
function quorum(uint256 blockNumber)
public
view
override(Governor, GovernorVotesQuorumFraction)
returns (uint256)
{
return super.quorum(blockNumber);
}
function state(uint256 proposalId)
public
view
override(Governor, GovernorTimelockControl)
returns (ProposalState)
{
return super.state(proposalId);
}
function proposalNeedsQueuing(uint256 proposalId)
public
view
override(Governor, GovernorTimelockControl)
returns (bool)
{
return super.proposalNeedsQueuing(proposalId);
}
function _queueOperations(
uint256 proposalId,
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) internal override(Governor, GovernorTimelockControl) returns (uint48) {
return super._queueOperations(proposalId, targets, values, calldatas, descriptionHash);
}
function _executeOperations(
uint256 proposalId,
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) internal override(Governor, GovernorTimelockControl) {
super._executeOperations(proposalId, targets, values, calldatas, descriptionHash);
}
function _cancel(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) internal override(Governor, GovernorTimelockControl) returns (uint48) {
return super._cancel(targets, values, calldatas, descriptionHash);
}
function _executor()
internal
view
override(Governor, GovernorTimelockControl)
returns (address)
{
return super._executor();
}
}
Token Economics
| Metric | Formula | Importance |
|---|---|---|
| Market Cap | Supply à Price | Valuation |
| FDV | Total Supply à Price | Long-term value |
| TVL | Total Deposits | Protocol usage |
| Velocity | Volume / Supply | Token demand |
| Burn Rate | Tokens Burned / Time | Deflationary pressure |
Interview Questions
-
What is the difference between ERC20 and ERC721? When would you use each?
- Answer: ERC20 tokens are fungible (interchangeable), while ERC721 tokens are non-fungible (unique). Use ERC20 for currencies, utility tokens, or governance tokens where all tokens are equal. Use ERC721 for NFTs representing unique assets like art, collectibles, or real-world assets where each token has distinct properties.
-
Explain the ERC4626 standard and its benefits.
- Answer: ERC4626 is a standard for tokenized vaults that represent shares in a yield-bearing strategy. Benefits include: composability (shares are ERC20 tokens), standardization (easy integration with other protocols), and transparency (share price and total assets are trackable). It's used for yield farming, lending protocols, and liquid staking.
-
How does token vesting work and why is it important?
- Answer: Token vesting gradually releases tokens over time, typically with a cliff period before any tokens are released. It's important for: aligning team incentives (they earn tokens over years), preventing dumps (early investors can't sell immediately), and building trust (demonstrates long-term commitment). Common schedules include 4-year vesting with 1-year cliff.
Quiz Questions
-
Which ERC standard is used for non-fungible tokens?
- A) ERC20
- B) ERC721
- C) ERC1155
- D) ERC4626
-
What is the purpose of the ERC20 permit extension?
- A) Allow gasless transfers
- B) Enable meta-transactions
- C) Add voting rights
- D) Implement burning
-
What is the maximum royalty percentage typically allowed on NFTs?
- A) 1%
- B) 5%
- C) 10%
- D) 25%