Manage ERC20 tokens in Java with Web3j
In this article, we learn how to manage ERC20 (Fungible) tokens in Java with the Web3j library.
ERC20 is an Ethereum Smart Contract standard for implementing tokens in a compliant way, so it is easy to interact and integrate tokens with any application (dapps, wallets, exchanges, etc.).
For more details about ERC20, see the article ERC-20 Token Standard.
Prerequisites
To follow this tutorial, you need the following software installed on your computer:
- Java programming language (> 8)
- A package and dependency manager, for example Maven or Gradle
- An IDE (Integrated development environment), for this tutorial, we use Eclipse
- Truffle: a development framework to develop, test and deploy Ethereum smart contract
- Ganache-cli: your local personal blockchain for Ethereum development.
Start ganache by running the command:
1 | ganache-cli |
Contract deployment
Before starting, we need an ERC20 token contract deployed on the Ethereum blockchain (Ganache in our case). There are many ways to do this (Read Develop your ERC-20 Tokens explained and OpenZeppelin Part 3: Token Standards). For the sake of this tutorial, we use the simplest solution using OpenZeppelin reusable contracts, Truffle and Ganache.
1. First create a project folder for our ERC20 called JVM and initialize a Truffle project
1 | mkdir JVM |
2. Then we install the Open-Zeppelin Solidity library which contains a lot of high-quality, fully tested and audited reusable smart contracts
Import the OpenZeppelin smart contracts using npm packages.
1 | npm init -y |
3. Create a contract file ./contracts/JavaToken.sol
The smart contract inherits all the functionality and rules from the reusable OpenZeppelin contract ERC20Mintable
. We only need to configure the following constant variables as below:
1 | // JavaToken.sol |
4. Deploy the smart contract on our local Ganache network
We need to first complete the migration script. Create a file called ./migrations/2_deploy_contract.js
, and add the code below to the file:
1 | // 2_deploy_contract.js |
The migration script deploys the contract, mints and distributes 100 JVM tokens to the deployer account (the Ganache first account).
The next step is to configure a connection to the Ganache network in order to deploy a smart contract. Change the file ./truffle-config.js
to the code below:
1 | // truffle-config.js |
To deploy the smart contracts on the Ganache network, run the command below (do not forget to start ganache-cli beforehand):
1 | truffle migrate --network development |
Note the contract address after the command completes.
If you wish to learn more about this step, I recommend reading the following articles about Truffle and Ganache for deploying smart contracts: Truffle: Smart Contract Compilation & Deployment and Truffle 101 - Development Tools for Smart Contracts
Load the contract with Web3j
Now we have deployed an ERC20 smart contract on our Ganache local blockchain, and we can start interacting with it in Java using the Web3j ERC20 utility class.
1. Create a new project and import the Web3j dependency
Create a new Maven project in your favorite IDE and import Web3j dependencies (core
and contracts
for EIP support):
1 | <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> |
2. Create a new class to load an ERC20 Smart Contract wrapper
ERC20 is a standard, so there is no need to manually generate a Smart Contract wrapper, Web3j includes it by default.
However, you do need to connect Web3j to an Ethereum blockchain and configure a wallet to sign transactions.
In this article, we connect to a local Ganache blockchain (exposed by default on http://localhost:8545
) and use the first Ganache test account (read the Ganache startup logs to find this information) which received 100 JVM tokens during deployment.
1 | // Connect Web3j to the Blockchain |
For more complex scenarios, you can load the contract with a specific TransactionManager
and Gas parameters using ERC20.load(contractAddress, web3j, transactionManager, gasPrice, gasLimit)
3. Get token information
Once we have loaded our ERC20 token contract, we can start requesting information stored on this contract such as the number of decimal or the balance of an account in JVM tokens.
The following code retrieves the information we configured in our contract earlier.
1 | String symbol = javaToken.symbol().send(); |
More importantly, we can retrieve the token balance of an account.
1 | BigInteger balance1 = javaToken.balanceOf("0x1583c05d6304b6651a7d9d723a5c32830f53a12f").send(); |
The account 0x1583c05d6304b6651a7d9d723a5c32830f53a12f
is Ganache’s first account, the one that deployed the contract and received 100 tokens during deployment. While 0x0db6b797e64666d4b36b13e5dc6fcd4661893ac8
represents Ganache’s second account that didn’t receive any token.
Transfer tokens
To interact with the token, the ERC20
class offers all the functionalities needed like transfer
, transferFrom
and approve
.
For example, we can transfer 25 JVM tokens to 0x0db6b797e64666d4b36b13e5dc6fcd4661893ac8
by signing and sending a transaction from our account configured as Credentials (0x1583c05d6304b6651a7d9d723a5c32830f53a12f
).
1 | TransactionReceipt receipt = javaToken.transfer("0x0db6b797e64666d4b36b13e5dc6fcd4661893ac8", new BigInteger("25")).send(); |
Get notified of transfer events
Finally, we cover how to subscribe to specific events generated by the ERC20 contract so we can react to any activity from it.
You can retrieve specific events for a given transaction via the method getTransferEvents
:
1 | List<ERC20.TransferEventResponse> events = javaToken.getTransferEvents(receipt); |
We can also add RxJava as a dependency to subscribe continuously to any new events via transferEventFlowable
.
1 | javaToken.transferEventFlowable(DefaultBlockParameterName.EARLIEST, DefaultBlockParameterName.LATEST) |
For more information about subscribing to events with Web3j, I highly recommend reading this article: Interacting with an Ethereum Smart Contract in Java