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: UNLICENSEDpragma 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); }}Positive tests
Section titled “Positive tests”Add tests for the standard functions in an ERC-20 contract
- test minting
- Test transfers
- 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
$1dNegative tests
Section titled “Negative tests”Add tests that expect failures
- User tries to spend tokens they dont have
- 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);}Class tests
Section titled “Class tests”$1b