Introduction

Hi, I'm cardene, a software engineer and technical writer focused on blockchain and AI.

I've also authored Japanese technical books on specification-driven development with LLMs and decentralized application (DApp) development.

I also build and publish a variety of tools, libraries, and open-source projects.

This article covers ERC-20 token deposits and withdrawals.

It is intended for readers who understand what ERC-20 is but wonder how to use it in practice.

Once you understand ERC-20, a useful next step is to build something with it.

Learning how ERC-20 deposits and withdrawals work will also deepen your understanding of DeFi applications such as Uniswap.

Let's get started.

This article draws heavily on the following code.

https://gist.github.com/BlockmanCodes/83d995ec9de0c4f5201c3556cba489e0

What is ERC-20?

Illustration of ERC-20

You may be wondering what ERC-20 is in the first place.

ERC-20 is a standardized token interface for the Ethereum blockchain.

A standardized token interface means that tokens follow a common set of rules.

Without common rules, each token could require a separate wallet.

Creating a wallet for every new token would be cumbersome.

By designing tokens according to the ERC-20 standard, a single wallet can manage them.

ERC-20 tokens are also known as fungible tokens.

Fungible tokens are interchangeable with other tokens of equal value.

In contrast, NFTs are non-fungible tokens, which are not interchangeable in this way.

For a more detailed explanation, see the following article.

It is written to be accessible even to non-engineers.

/articles/aeefe2d89dd5332c9f43

Setting up the development environment

Development environment setup

Before implementing ERC-20 deposits and withdrawals, set up the development environment.

This tutorial assumes that Node.js and npm are already installed.

If you have not installed them, refer to a guide such as the following.

Open a terminal and run the following commands in a directory of your choice.

bash
$ mkdir erc20
$ cd erc20

Install Hardhat.

Hardhat is a development environment for Solidity.

bash
$ npm install --save-dev hardhat
bash
added 300 packages in 27s

61 packages are looking for funding
  run `npm fund` for details

If the output looks like the example above, run the following command to initialize a Hardhat project.

bash
$ npx hardhat

You will be asked several questions. Press Enter to accept each default.

bash
✔ What do you want to do? · Create a JavaScript project
✔ Hardhat project root: · /Users/.../ERC20
✔ Do you want to add a .gitignore? (Y/n) · y
✔ Do you want to install this sample project's dependencies with npm (@nomicfoundation/hardhat-toolbox)? (Y/n) · y
bash
To address all issues (including breaking changes), run:
  npm audit fix --force

Run `npm audit` for details.

✨ Project created ✨

See the README.md file for some example tasks you can run

Give Hardhat a star on Github if you're enjoying it! 💞✨

     https://github.com/NomicFoundation/hardhat

Please take a moment to complete the 2022 Solidity Survey: https://hardhat.org/solidity-survey-2022

Once you see output like the example above, the starter project should have been created with the following directory structure.

The listing has been shortened for readability.

bash
.
├── README.md
├── artifacts
│   ├── build-info
│   │   └── ....json
│   └── contracts
│       └── Lock.sol
│           ├── Lock.dbg.json
│           └── Lock.json
├── cache
│   └── solidity-files-cache.json
├── contracts
│   └── Lock.sol
├── hardhat.config.js
├── node_modules
│   └── ...
├── package-lock.json
├── package.json
├── scripts
│   └── deploy.js
└── test
    └── Lock.js

Install the following additional libraries.

bash
$ npm i chai
$ npm i @openzeppelin/contracts

First, compile the contracts.

Run the following command.

bash
$ npx hardhat compile
bash
Compiled 1 Solidity file successfully

Output like the example above indicates a successful compilation.

Finally, run the tests.

bash
$ npx hardhat test

If you see output like the following, the tests have passed.

bash

  Lock
    Deployment
      ✔ Should set the right unlockTime (1206ms)
      ✔ Should set the right owner
      ✔ Should receive and store the funds to lock
      ✔ Should fail if the unlockTime is not in the future (39ms)
    Withdrawals
      Validations
        ✔ Should revert with the right error if called too soon
        ✔ Should revert with the right error if called from another account
        ✔ Shouldn't fail if the unlockTime has arrived and the owner calls it
      Events
        ✔ Should emit an event on withdrawals
      Transfers
        ✔ Should transfer the funds to the owner

  9 passing (1s)

The development environment is now set up.

Creating the contracts

Creating the contracts

With the environment ready, create contracts that support ERC-20 token deposits and withdrawals.

Token.sol

Start by creating an ERC-20 token.

Run the following command in your terminal.

bash
$ touch contracts/Token.sol

This creates a file named Token.sol inside the contracts directory.

Paste the following code into Token.sol.

solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract CardeneToken is ERC20 {
  constructor() ERC20("CARD", "Cardene Token") {
    _mint(msg.sender, 10000);
  }
}

Let's examine the code piece by piece.

Imports

solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

This declares the Solidity version and imports the ERC-20 contract.

Creating the ERC-20 token

solidity
contract CardeneToken is ERC20 {
  constructor() ERC20("CARD", "Cardene Token") {
    _mint(msg.sender, 3000);
  }
}

This defines the ERC-20 token.

The original explanation specifies Cardene Token as the name and CARD as the symbol.

It describes minting 3000 tokens. Note that the code shown above instead passes 10000 to _mint, in base units, and places CARD first in the constructor arguments.

Bank.sol

Now create a contract that allows users to deposit and withdraw ERC-20 tokens.

Run the following command in your terminal.

bash
$ touch contracts/Bank.sol

This creates a file named Bank.sol inside the contracts directory.

Paste the following code into Bank.sol.

solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract Bank {
    // Address that deployed the contract.
    address public owner;

    // Mapping from token symbol to token address.
    // Only the owner can add entries.
    mapping(bytes32 => address) public whitelistedTokens;
    // Mapping from wallet address to token symbol and token amount.
    mapping(address => mapping(bytes32 => uint256)) public accountBalances;

    constructor() {
        owner = msg.sender;
    }

    /// @notice Adds a token to the whitelistedTokens mapping.
    ///         Only the owner can call this function.
    /// @param symbol Token symbol.
    /// @param tokenAddress Token address.
    function whitelistToken(bytes32 symbol, address tokenAddress) external {
        require(msg.sender == owner, 'This function is not public');

        // Add the token symbol and token address to the mapping.
        whitelistedTokens[symbol] = tokenAddress;
    }

    /// @notice Checks whether a token is registered in whitelistedTokens.
    /// @param token Token symbol.
    /// @return Token address.
    function getWhitelistedTokenAddresses(bytes32 token) external view returns(address) {
        return whitelistedTokens[token];
    }

    /// @notice Deposits tokens.
    /// @param amount Amount of tokens to deposit.
    /// @param symbol Symbol of the token to deposit.
    function depositTokens(uint256 amount, bytes32 symbol) external {
        accountBalances[msg.sender][symbol] += amount;
        // Get the token address and transfer tokens from the wallet to this contract.
        ERC20(whitelistedTokens[symbol]).transferFrom(msg.sender, address(this), amount);
    }

    /// @notice Withdraws tokens.
    /// @dev The deposited balance must be at least the withdrawal amount.
    /// @param amount Amount of tokens to withdraw.
    /// @param symbol Symbol of the token to withdraw.
    function withdrawTokens(uint256 amount, bytes32 symbol) external {
        require(accountBalances[msg.sender][symbol] >= amount, 'Insufficent funds');

        // Update the record of the user's deposited token balance.
        accountBalances[msg.sender][symbol] -= amount;
        // Get the token address and transfer tokens from the contract to the user's wallet.
        ERC20(whitelistedTokens[symbol]).transfer(msg.sender, amount);
    }
}

There is a fair amount of code here.

Let's examine it one piece at a time.

Imports

solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

This is the same as in Token.sol.

It declares the Solidity version and imports the ERC-20 contract.

Contract and variable declarations

solidity
contract Bank {
    // Address that deployed the contract.
    address public owner;

    // Mapping from token symbol to token address.
    // Only the owner can add entries.
    mapping(bytes32 => address) public whitelistedTokens;
    // Mapping from wallet address to token symbol and token amount.
    mapping(address => mapping(bytes32 => uint256)) public accountBalances;

The contract declares three state variables.

owner stores the wallet address that deployed the contract.

whitelistedTokens records the tokens that users can deposit and withdraw.

accountBalances records how much of each token, identified by its symbol, a particular wallet address has deposited.

constructor

javascript
    constructor() {
        owner = msg.sender;
    }

The constructor is called once when the contract is deployed.

It stores the deploying user's wallet address in owner.

whitelistToken

javascript
    /// @notice Adds a token to the whitelistedTokens mapping.
    ///         Only the owner can call this function.
    /// @param symbol Token symbol.
    /// @param tokenAddress Token address.
    function whitelistToken(bytes32 symbol, address tokenAddress) external {
        require(msg.sender == owner, 'This function is not public');

        // Add the token symbol and token address to the mapping.
        whitelistedTokens[symbol] = tokenAddress;
    }

This function takes a token symbol and address and adds an entry to the whitelistedTokens mapping.

Registering a token in whitelistedTokens enables deposits and withdrawals of that token.

Only the owner, the user who deployed the contract, can call the function.

getWhitelistedTokenAddresses

javascript
    /// @notice Checks whether a token is registered in whitelistedTokens.
    /// @param token Token symbol.
    /// @return Token address.
    function getWhitelistedTokenAddresses(bytes32 token) external view returns(address) {
        return whitelistedTokens[token];
    }

This function takes a token symbol and looks up the registered token address in whitelistedTokens.

depositTokens

javascript
    /// @notice Deposits tokens.
    /// @param amount Amount of tokens to deposit.
    /// @param symbol Symbol of the token to deposit.
    function depositTokens(uint256 amount, bytes32 symbol) external {
        accountBalances[msg.sender][symbol] += amount;
        // Get the token address and transfer tokens from the wallet to this contract.
        ERC20(whitelistedTokens[symbol]).transferFrom(msg.sender, address(this), amount);
    }

This function takes an amount and token symbol, allowing the user to deposit ERC-20 tokens into the contract.

The amount of each token deposited by each wallet address is recorded in accountBalances.

whitelistedTokens[symbol] retrieves the address of the ERC-20 token authorized for deposits and withdrawals. Casting that address to ERC20 allows the contract to call its transferFrom function.

When transferFrom executes, the specified amount of ERC-20 tokens is transferred from the user's wallet to the Bank contract.

How does this function call work?

In this example, the address belongs to the Token contract, so the call invokes that contract's transferFrom function.

But the Token contract does not define a transferFrom function, does it?

It does not declare the function directly, but it does inherit it.

By inheriting the ERC-20 contract in the following declaration, the Token contract can use the inherited transferFrom implementation.

solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract CardeneToken is ERC20 {
  constructor() ERC20("CARD", "Cardene Token") {
    _mint(msg.sender, 10000);
  }
}

See the following link for the ERC-20 contract source code.

You can find the transferFrom function defined there.

withdrawTokens

plain
    /// @notice Withdraws tokens.
    /// @dev The deposited balance must be at least the withdrawal amount.
    /// @param amount Amount of tokens to withdraw.
    /// @param symbol Symbol of the token to withdraw.
    function withdrawTokens(uint256 amount, bytes32 symbol) external {
        require(accountBalances[msg.sender][symbol] >= amount, 'Insufficent funds');

        // Update the record of the user's deposited token balance.
        accountBalances[msg.sender][symbol] -= amount;
        // Get the token address and transfer tokens from the contract to the user's wallet.
        ERC20(whitelistedTokens[symbol]).transfer(msg.sender, amount);
    }
}

This function takes an amount and token symbol, allowing the user to withdraw ERC-20 tokens from the contract.

To prevent a user from withdrawing more than they deposited, it checks accountBalances and ensures that the withdrawal amount does not exceed the recorded balance.

It also updates accountBalances to reflect how much of the token remains deposited.

That completes the explanation of Bank.sol.

The next section covers the code used to test the contracts created in this section.

Creating the test file

Creating the test file

Create a file that executes and tests the contracts.

Run the following command.

javascript
$ touch test/Bank.js

This creates a test file named Bank.js in the test directory.

Paste the following code into Bank.js.

javascript
const { expect } = require("chai");

describe('Bank', function () {
    beforeEach(async function() {
        [owner, wallet1, wallet2] = await ethers.getSigners();

        // Get the Bank and Token contract factories.
        Bank = await ethers.getContractFactory('Bank', owner);
        CardeneToken = await ethers.getContractFactory('CardeneToken', wallet1);

        // Deploy the Bank and Token contracts.
        bank = await Bank.deploy();
        token = await CardeneToken.deploy();

        // Send 1000 CARD tokens from wallet1 to wallet2.
        token.connect(wallet1).transfer(wallet2.address, 1000);

        // From wallet1, which minted the CARD tokens,
        // grant the Bank contract permission to transfer 5000 CARD tokens.
        await token.connect(wallet1).approve(
            bank.address,
            2000
        );

        // From wallet1, which minted the CARD tokens,
        // grant wallet2 permission to transfer 1000 CARD tokens.
        await token.connect(wallet2).approve(
            bank.address,
            1000
        );

        // Convert the token identifier to bytes32.
        CARD_TOKEN = ethers.utils.formatBytes32String('CardeneToken');

        // Call whitelistToken on the Bank contract
        // to register CARD tokens for deposits and withdrawals.
        await bank.whitelistToken(
            CARD_TOKEN,
            token.address
        );
    });

    describe('deployment', function () {
        // Check whether wallet1 received 5000 CARD tokens.
        it('should mint tokens to wallet 1', async function () {
            expect(await token.balanceOf(wallet1.address)).to.equal(2000);
        })

        // Check whether wallet2 received 1000 CARD tokens.
        it('should transfer tokens to wallet 2', async function () {
        expect(await token.balanceOf(wallet2.address)).to.equal(1000);
        })

        // Call whitelistedTokens on the Bank contract
        // to check whether CARD tokens are available for deposits and withdrawals.
        it('should whitelist CARD token on the contract', async function () {
        expect(
            await bank.whitelistedTokens(CARD_TOKEN)
            ).to.equal(token.address);
        })
    })

    describe('depositTokens', function () {
        it('should deposit CARD token', async function () {
            // Deposit 100 CARD tokens from wallet1.
            await bank.connect(wallet1).depositTokens(
                500,
                CARD_TOKEN,
            );

            // Deposit 50 CARD tokens from wallet2.
            await bank.connect(wallet2).depositTokens(
                300,
                CARD_TOKEN,
            );

            // Check the token balances of wallet1 and wallet2.
            expect(await token.balanceOf(wallet1.address)).to.equal(1500);
            expect(await token.balanceOf(wallet2.address)).to.equal(700);

            // Check that the Bank contract recorded the deposits.
            expect(
                await bank.accountBalances(wallet1.address, CARD_TOKEN)
            ).to.equal(500);
            expect(
                await bank.accountBalances(wallet2.address, CARD_TOKEN)
            ).to.equal(300);
        });
    })

    describe('withdraw', function () {
        it('should withdraw CARD token from the contract', async function () {
            // Deposit another 600 CARD tokens from wallet1.
            await bank.connect(wallet1).depositTokens(
                1000,
                CARD_TOKEN,
            );
            // Withdraw 100 CARD tokens.
            await bank.connect(wallet1).withdrawTokens(
                500,
                CARD_TOKEN,
            );

            // After depositing 600 CARD tokens and withdrawing 100 CARD tokens,
            // wallet1 should hold 4500 CARD tokens. Check the balance.
            expect(await token.balanceOf(wallet1.address)).to.equal(1500);

            // Check how many CARD tokens wallet1 has deposited in the Bank contract.
            expect(
                await bank.accountBalances(wallet1.address, CARD_TOKEN)
            ).to.equal(500);
            })

            // Check that withdrawing more CARD tokens than deposited causes an error.
            it('should not allow withdrawing more than has been deposited', async function () {
                await expect(
                    bank.connect(wallet1).withdrawTokens(1000, CARD_TOKEN)
                ).to.be.revertedWith("Insufficent funds")
            }
        )
    })
})

Let's work through this longer example one section at a time. The original code and its comments contain mismatched amounts; the examples below retain the published values rather than presenting them as newly verified tests.

Imports

javascript
const { expect } = require("chai");

This imports a library called Chai.

chai makes smart contract tests easier to write and read.

Test setup

javascript
beforeEach(async function() {
        // Create three accounts.
        [owner, wallet1, wallet2] = await ethers.getSigners();

        // Get the Bank and Token contract factories.
        Bank = await ethers.getContractFactory('Bank', owner);
        CardeneToken = await ethers.getContractFactory('CardeneToken', wallet1);

        // Deploy the Bank and Token contracts.
        bank = await Bank.deploy();
        token = await CardeneToken.deploy();

        // Send 1000 CARD tokens from wallet1 to wallet2.
        token.connect(wallet1).transfer(wallet2.address, 1000);

        // From wallet1, which minted the CARD tokens,
        // grant the Bank contract permission to transfer 5000 CARD tokens.
        await token.connect(wallet1).approve(
            bank.address,
            2000
        );

        // From wallet1, which minted the CARD tokens,
        // grant wallet2 permission to transfer 1000 CARD tokens.
        await token.connect(wallet2).approve(
            bank.address,
            1000
        );

        // Convert the token identifier to bytes32.
        CARD_TOKEN = ethers.utils.formatBytes32String('CardeneToken');

        // Call whitelistToken on the Bank contract
        // to register CARD tokens for deposits and withdrawals.
        await bank.whitelistToken(
            CARD_TOKEN,
            token.address
        );
    });

This section implements the setup needed for the other tests.

Although the setup is fairly long, it performs the following tasks.

Setup tasks

  • Create accounts.
  • Deploy the Token and Bank contracts.
  • Give wallet1 and wallet2 token balances.
  • Add the CARD token to the Bank contract's whitelistedTokens mapping to enable deposits and withdrawals.

Checking the initial state

javascript
    describe('deployment', function () {
        // Check whether wallet1 received 5000 CARD tokens.
        it('should mint tokens to wallet 1', async function () {
            expect(await token.balanceOf(wallet1.address)).to.equal(2000);
        })

        // Check whether wallet2 received 1000 CARD tokens.
        it('should transfer tokens to wallet 2', async function () {
        expect(await token.balanceOf(wallet2.address)).to.equal(1000);
        })

        // Call whitelistedTokens on the Bank contract
        // to check whether CARD tokens are available for deposits and withdrawals.
        it('should whitelist CARD token on the contract', async function () {
        expect(
            await bank.whitelistedTokens(CARD_TOKEN)
            ).to.equal(token.address);
        })
    })

From here, we will discuss each block beginning with describe as a unit.

Think of each describe block as a separate group of tests.

The tests use setup plus describe blocks, so the blocks do not share the resulting state.

Suppose there are three describe blocks, named describe1, describe2, and describe3.

First, the setup runs before describe1 executes.

Then describe2 runs without carrying over the state produced by describe1.

Likewise, describe3 does not carry over the state produced by describe2.

This describe block checks that wallet1, wallet2, and the Bank contract have the expected CARD token balances and registration.

Depositing CARD tokens

javascript
    describe('depositTokens', function () {
        it('should deposit CARD token', async function () {
            // Deposit 100 CARD tokens from wallet1.
            await bank.connect(wallet1).depositTokens(
                500,
                CARD_TOKEN,
            );

            // Deposit 50 CARD tokens from wallet2.
            await bank.connect(wallet2).depositTokens(
                300,
                CARD_TOKEN,
            );

            // Check the token balances of wallet1 and wallet2.
            expect(await token.balanceOf(wallet1.address)).to.equal(1500);
            expect(await token.balanceOf(wallet2.address)).to.equal(700);

            // Check that the Bank contract recorded the deposits.
            expect(
                await bank.accountBalances(wallet1.address, CARD_TOKEN)
            ).to.equal(500);
            expect(
                await bank.accountBalances(wallet2.address, CARD_TOKEN)
            ).to.equal(300);
        });
    })

This section tests whether CARD tokens can be deposited.

It deposits 500 CARD units from wallet1 and 300 CARD units from wallet2, then checks their balances.

It then checks that the Bank contract records the deposited CARD tokens.

Withdrawing CARD tokens

javascript
    describe('withdraw', function () {
        it('should withdraw CARD token from the contract', async function () {
            // Deposit another 600 CARD tokens from wallet1.
            await bank.connect(wallet1).depositTokens(
                1000,
                CARD_TOKEN,
            );
            // Withdraw 100 CARD tokens.
            await bank.connect(wallet1).withdrawTokens(
                500,
                CARD_TOKEN,
            );

            // After depositing 600 CARD tokens and withdrawing 100 CARD tokens,
            // wallet1 should hold 4500 CARD tokens. Check the balance.
            expect(await token.balanceOf(wallet1.address)).to.equal(1500);

            // Check how many CARD tokens wallet1 has deposited in the Bank contract.
            expect(
                await bank.accountBalances(wallet1.address, CARD_TOKEN)
            ).to.equal(500);
            })

            // Check that withdrawing more CARD tokens than deposited causes an error.
            it('should not allow withdrawing more than has been deposited', async function () {
                await expect(
                    bank.connect(wallet1).withdrawTokens(1000, CARD_TOKEN)
                ).to.be.revertedWith("Insufficent funds")
            }
        )
    })
})

Finally, let's examine this block.

Here, wallet1 deposits 1000 CARD units into the Bank contract and withdraws 500 CARD units.

The test then checks the CARD token amounts held by wallet1 and recorded by the Bank contract.

The final test checks that attempting to withdraw more CARD tokens than were deposited causes an error.

Running the tests

Now run the tests.

Run the following command in your terminal.

bash
$ npx hardhat test 

The original article shows the following output as an example of a successful test run. This output has not been reproduced for this translation.

bash

  Bank
    deployment
      ✔ should mint tokens to wallet 1
      ✔ should transfer tokens to wallet 2
      ✔ should whitelist CARD token on the contract
    depositTokens
      ✔ should deposit CARD token (75ms)
    withdraw
      ✔ should withdraw CARD token from the contract (47ms)
      ✔ should not allow withdrawing more than has been deposited

  Lock
    Deployment
      ✔ Should set the right unlockTime (59ms)
      ✔ Should set the right owner
      ✔ Should receive and store the funds to lock
      ✔ Should fail if the unlockTime is not in the future
    Withdrawals
      Validations
        ✔ Should revert with the right error if called too soon
        ✔ Should revert with the right error if called from another account
        ✔ Shouldn't fail if the unlockTime has arrived and the owner calls it
      Events
        ✔ Should emit an event on withdrawals
      Transfers
        ✔ Should transfer the funds to the owner

  15 passing (2s)

Source code

Source code

Refer to the following code.

The individual files are available at the following links.

Bank.sol

Token.sol

Bank.js

https://github.com/cardene777/smart-contract-test/blob/main/ERC20/test/Bank.js

Conclusion

Conclusion

This article explained ERC-20 deposits and withdrawals.

How did it go?

If you are an engineer with some understanding of ERC-20, you should now have a clearer idea of how to use it.

If you found the tutorial difficult, review the fundamentals of Solidity.

Contract inheritance in particular can be challenging, so spend some time studying that topic.

If you are still unsure about ERC-20, the article introduced at the beginning of this tutorial is a useful reference.

/articles/aeefe2d89dd5332c9f43

If you have any questions, feel free to ask me on Twitter or through other channels.

You can also contact me through Twitter if you have questions.

I regularly share information about Solidity, blockchain, and Web3.

I share interesting articles on Twitter, so feel free to follow me.