Skip to content

Creating an ERC-20 contract

Course: Ganache, Trufle, Hardhat and Foundry - chapter 9

Now that we have ERC-20 in our codebase, lets extend it to create our own ERC-20 contract

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;
import "forge-std/Script.sol";
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract MyToken is ERC20 {
uint256 public number;
constructor() ERC20("MyToken", "MTK") {}
function mint(address to, uint256 amount) public {
_mint(to, amount);
}
}

Add tests for the standard functions in an ERC-20 contract

  1. test minting
  2. Test transfers
  3. Test approvals

💡

You need to learn about some cheat codes in forge before you attempt this assignment. Ref - https://book.getfoundry.sh/forge/cheatcodes (read about pranks)

Solution
$1d

Add tests that expect failures

  1. User tries to spend tokens they dont have
  2. User tries to spend on someone elses behalf what they dont have
Solution
function testFail_Mint() public {
assertEq(token.balanceOf(address(this)), 200);
token.mint(0x075c299cf3b9FCF7C9fD5272cd2ed21A4688bEeD, 100);
assertEq(token.balanceOf(0x075c299cf3b9FCF7C9fD5272cd2ed21A4688bEeD), 200);
}
function testFail_Transfer() public {
token.transfer(0x075c299cf3b9FCF7C9fD5272cd2ed21A4688bEeD, 100);
}
function testFail_Allowance() public {
token.mint(address(this), 100);
vm.prank(0x075c299cf3b9FCF7C9fD5272cd2ed21A4688bEeD);
token.transferFrom(address(this), 0x075c299cf3b9FCF7C9fD5272cd2ed21A4688bEeD, 100);
assertEq(token.balanceOf(address(this)), 0);
assertEq(token.balanceOf(0x075c299cf3b9FCF7C9fD5272cd2ed21A4688bEeD), 100);
}
$1b