中文 / 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.envfile.PRIVATE_KEY=YOUR_PRIVATE_KEY INFURA_ID=YOUR_PROJECT_ID - Run the
index.jsfile: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.solintosourcevariable.
// 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
contractFileObject If you want to use thecontractFileobject in otherjsfiles, you can export it.
module.exports = contractFile;- Load the
SimpleTokensmart contract fromcompilefile
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
receiveraccount for testing
const receiver = '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266';- Build the
web3object
const web3 = new Web3(new Web3.providers.HttpProvider('https://goerli.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
accountaddress
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
abiandbinWhen deploying the smart contract, we need two important parameters which are thebytecodeandabiof the smart contract. In previous step 1, we loaded the compiledSimpleTokenobject, so we can get thebytecodeandabifrom it.
const bytecode = contractFile.evm.bytecode.object;
const abi = contractFile.abi;- Get contract instance
In the last step, you got the
binandabi, 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
deployTransactiontransaction 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
receiveraccount
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}`);
});infuradoesn't supportsendTransaction, only supportsendRawTransactioninfuradoesn't invokeeth_sendTransaction, so you need to an unlocked account on theethereumnode. More details, please refer to this