中文 / English
This basic task is to show how to interact with ERC20 contract, so the developer can understand the basic interface of ERC20 contract.
-
IERC20 totalSupply: Get the total amount of ERC20 token in the contract balanceOf: Get the amount of ERC20 token of specific account in the contract transfer: Transfer ERC20 token to specific account allowance: Get the amount of ERC20 tokens of the source account that the target account can use approve: Authorize the target account to transfer the specified amount of ERC20 Tokens transferFrom: (Third party call) Transfer a specific amount of ERC20 token from the source account to target account
-
IERC20Metadata name: Get the name of the Token symbol: Get the symbol of the Token decimals: Get the decimals of the Token
- Install dependencies:
npm install
- Copy the configuration file:
cp .env.example .env
- Edit the configuration file:
vim .env
, copy your project ID and private key to the.env
file.PRIVATE_KEY=YOUR_PRIVATE_KEY INFURA_ID=YOUR_PROJECT_ID
- Run the
index.js
file:node index.js
You can't use .sol
files directly, you need to compile it to binary file firstly.
- Load the smart contract file
SimpleToken.sol
intosource
variable.
// Load contract
const source = fs.readFileSync('SimpleToken.sol', 'utf8');
- Compile the smart contract file
// compile solidity
const input = {
language: 'Solidity',
sources: {
'SimpleToken.sol': {
content: source,
},
},
settings: {
outputSelection: {
'*': {
'*': ['*'],
},
},
},
};
const tempFile = JSON.parse(solc.compile(JSON.stringify(input)));
| Note: The version of solidity in this task is 0.8.0
, different versions may have different compile ways.
- Get the Contract Binary Object
The solidity object that was successfully compiled in the previous step contains many properties/values, and what we only need is the contract object, so we can get the SimpleToken
contract object by accessing the object properties.
const contractFile = tempFile.contracts['SimpleToken.sol']['SimpleToken'];
- Export
contractFile
Object If you want to use thecontractFile
object in otherjs
files, you can export it.
module.exports = contractFile;
- Load the
SimpleToken
smart contract fromcompile
file
const contractFile = require('./compile');
- Load private key
For security’s sake, the private key is not hard-coded, but it can be read as environment variables. When run this task, the dotenv
plugin will automatically read the configurations in the .env
file and load them as environment variables, and then you can use the private key and other environment variables via process.env
.
require('dotenv').config();
const privatekey = process.env.PRIVATE_KEY;
- Create a
receiver
account for testing
const receiver = '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266';
- Build the
web3
object
const web3 = new Web3(new Web3.providers.HttpProvider('https://kovan.infura.io/v3/' + process.env.INFURA_ID));
| Note: The INFURA_ID
is the PROJECT ID
of the Infura
project you created in last task
- Get the
account
address
On blockchain, each user has a address
, which is unique for others, and you can get the address
by the private key. In this task, you can use the we3.eth.accounts.privateKeyToAccount
API to get your account
address by passing the private key as a parameter.
const account = web3.eth.accounts.privateKeyToAccount(privatekey);
const account_from = {
privateKey: account.privateKey,
accountaddress: account.address,
};
- Get the
abi
andbin
When deploying the smart contract, we need two important parameters which are thebytecode
andabi
of the smart contract. In previous step 1, we loaded the compiledSimpleToken
object, so we can get thebytecode
andabi
from it.
const bytecode = contractFile.evm.bytecode.object;
const abi = contractFile.abi;
- Get contract instance
In the last step, you got the
bin
andabi
, so we can create the contract instance by theabi
.
const deployContract = new web3.eth.Contract(abi);
- Create the transaction of the
deployContract
const deployTx = deployContract.deploy({
data: bytecode,
arguments: ['DAPPLEARNING', 'DAPP', 0, 10000000],
});
| So far, this transaction has not been deployed into the blockchain.
- Sign the transaction Use your private key to sign the transaction.
const deployTransaction = await web3.eth.accounts.signTransaction(
{
data: deployTx.encodeABI(),
gas: '8000000',
},
account_from.privateKey
);
- Deploy the contract
Send your signed
deployTransaction
transaction to the blockchain. You will receive a receipt, and get this contract address from it.
const deployReceipt = await web3.eth.sendSignedTransaction(deployTransaction.rawTransaction);
console.log(`Contract deployed at address: ${deployReceipt.contractAddress}`);
- Create a transfer transaction
We created a transfer transaction for ERC20
token, the receiver is receiver
account, and the amount is 100000
token.
const transferTx = erc20Contract.methods.transfer(receiver, 100000).encodeABI();
- Sign and send the transaction
const transferReceipt = await web3.eth.sendSignedTransaction(transferTransaction.rawTransaction);
- Check the balance of the
receiver
account
After the transaction is sent, you can log the balance of the receiver
and make sure the balance is correct.
erc20Contract.methods
.balanceOf(receiver)
.call()
.then((result) => {
console.log(`The balance of receiver is ${result}`);
});
infura
doesn't supportsendTransaction
, only supportsendRawTransaction
infura
doesn't invokeeth_sendTransaction
, so you need to an unlocked account on theethereum
node. More details, please refer to this