1. Home
  2. Docs
  3. APIs
  4. How to call an ERC-20 smart contract?

How to call an ERC-20 smart contract?

To call an Ethereum smart contract, you typically need to use the ABI (Application Binary Interface) and the address of the Ethereum smart contract. You also use an Ethereum client library like web3.js or ethers.js to construct and send transactions. Below is an example JavaScript code using the web3.js library to call a method on a simple Ethereum smart contract.
Below is an example JavaScript code using the web3.js library to call a method of a simple Ethereum smart contract:

First, make sure you have the web3.js library installed. If not, you can install it with the following command:
npm install web3
Next, use the following example code to call a smart contract method:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
const Web3 = require('web3');

// Connect to an Ethereum node
const web3 = new Web3('https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID'); // Replace with your Infura project ID

// Contract ABI (Application Binary Interface)
const contractABI = [...]; // Replace with your smart contract ABI

// Contract address
const contractAddress = '0xYourContractAddress'; // Replace with your smart contract address

// Create a contract instance
const contract = new web3.eth.Contract(contractABI, contractAddress);

// Sender's Ethereum address
const senderAddress = '0xYourSenderAddress'; // Replace with your Ethereum address

// Private key (used to sign the transaction)
const privateKey = '0xYourPrivateKey'; // Replace with your private key

// Method name and parameters you want to call
const methodName = 'yourMethodName'; // Replace with your contract's method name
const methodParams = [...]; // Replace with your method parameters

// Build a transaction object
const transactionObject = {
from: senderAddress,
to: contractAddress,
gas: 200000, // Replace with an appropriate gas limit
data: contract.methods[methodName](...methodParams).encodeABI(),
};

// Sign the transaction with the private key
web3.eth.accounts.signTransaction(transactionObject, privateKey)
.then(signedTx => {
// Send the transaction
web3.eth.sendSignedTransaction(signedTx.rawTransaction)
.on('transactionHash', (hash) => {
console.log(Transaction Hash: ${hash});
})
.on('confirmation', (confirmationNumber, receipt) => {
console.log(Confirmation Number: ${confirmationNumber});
if (confirmationNumber === 1) {
console.log(Transaction Receipt:, receipt);
}
})
.on('error', (error) => {
console.error(Error:, error);
});
})
.catch(error => {
console.error(Error signing transaction:, error);
});
Please note that the code above is a basic framework, and you’ll need to customize it to match your smart contract’s ABI, address, methods, and parameters. Also, ensure that you use the appropriate private key, gas limit, and Ethereum network in practice.
Tags