Skip to content

ERC20 Token Sale

In the previous lecture we already implemented an ERC20 token. But somehow, we can either mint it for someone, but nobody can obtain those tokens otherwise.

We are going to change it in this lecture.

If you have a look at famous DeFi projects, such as Uniswap{target=blank}, you'll see they are _using other smart contract, they are not integrating everything themselves.

This is also something we want to utilize in this project!

We will use the Token from the previous lecture. But instead of integrating a token sale directly, we let another contract take control of some of the tokens through an allowance functionality.

Give it a try yourself first, otherwise, here's my sample solution:

//SPDX-License-Identifier: MIT
pragma solidity 0.8.16;

interface IERC20 {
    function transfer(address to, uint amount) external;
    function decimals() external view returns(uint);

contract TokenSale {
    uint tokenPriceInWei = 1 ether;

    IERC20 token;

    constructor(address _token) {
        token = IERC20(_token);

    function purchase() public payable {
        require(msg.value >= tokenPriceInWei, "Not enough money sent");
        uint tokensToTransfer = msg.value / tokenPriceInWei;
        uint remainder = msg.value - tokensToTransfer * tokenPriceInWei;
        token.transfer(msg.sender, tokensToTransfer * 10 ** token.decimals());
        payable(msg.sender).transfer(remainder); //send the rest back


Last update: September 3, 2022