Read/Write Contract using ABIs
​ABIs (Application Binary Interface) can be thought of as a restaurant menu
🍽
, they describe the possible functions that can be called to interact with a smart contract.
By knowing the functions available to a contract, we can programmatically use them β€” in situations where the project websites are down or when you need to automate certain transactions.
You will need Node.js
installed, a valid Etherscan API Key and access to an Ethereum node, such as from Infura or Alchemy.

1. Setting up a Node.js project

In a new folder, initiate a new Node.js project with the command npm init -y to accept all default project parameters.
A package.json file will be created for you, which contains all your packages and project information.

2. Obtaining a contract's ABI

Create a new file named script.js.
In JavaScript, we'll be writing our code to make a request to the endpoint "Get Contract ABI for Verified Contract Source Codes", which you will need to specify your verified contract address.
1
https://api-ropsten.etherscan.io/api?module=contract&action=getabi&address=0xC1dcBB3E385Ef67f2173A375F63f5F4361C4d2f9&apikey=YourApiKeyToken
Copied!
For this example, we'll be borrowing a default contract available from Remix, which has been deployed on the Ropsten Testnet.​
1
const fetch = require('node-fetch');
2
​
3
async function main() {
4
​
5
// make an API call to the ABIs endpoint
6
const response = await fetch('https://api-ropsten.etherscan.io/api?module=contract&action=getabi&address=0xC1dcBB3E385Ef67f2173A375F63f5F4361C4d2f9&apikey=YourApiKeyToken');
7
const data = await response.json();
8
​
9
// print the JSON response
10
let abi = data.result;
11
console.log(abi);
12
}
13
​
14
main();
Copied!

3. Connecting to a node

To interact with smart contracts, we will need a connection to an Ethereum node such as Infura, Alchemy or even running one of your own.
We're using Infura in this case, make sure to set your endpoint to the Ropsten Testnet and copy the WebSockets (WSS) endpoint.

4. Integrating Ethers.js

We'll need to integrate a JavaScript library, known as Ether.js that will be used to interact with the Ethereum blockchain.
To do so, run the command npm i ethers from a terminal within this project directory to install it.
Ether.js provides several classes such as a Provider, which represents the state of the Ethereum blockchain. We can create a new Provider using the syntax below, and pass in our node URL to initiate a connection to the Ethereum network.
1
const fetch = require('node-fetch');
2
const ethers = require("ethers");
3
​
4
async function main() {
5
const response = await fetch('https://api-ropsten.etherscan.io/api?module=contract&action=getabi&address=0xC1dcBB3E385Ef67f2173A375F63f5F4361C4d2f9&apikey=YourApiKeyToken');
6
const data = await response.json();
7
​
8
let abi = data.result;
9
console.log(abi);
10
​
11
// creating a new Provider, and passing in our node URL
12
const node = "wss://ropsten.infura.io/ws/v3/733a7efe57364ffd9210b582d7cd0cb3";
13
const provider = new ethers.providers.WebSocketProvider(node);
14
}
15
​
16
main();
Copied!

5. Initiating an Ethereum wallet

Another class that Ether.js allows us to create is a Wallet, which will allow us to specify a private key and use an Ethereum address.
Performing write operations will incur gas costs, as such you may get some testnet ETH from a faucet to pay for transaction fees.
1
const fetch = require('node-fetch');
2
const ethers = require("ethers");
3
​
4
async function main() {
5
const response = await fetch('https://api-ropsten.etherscan.io/api?module=contract&action=getabi&address=0xC1dcBB3E385Ef67f2173A375F63f5F4361C4d2f9&apikey=YourApiKeyToken');
6
const data = await response.json();
7
​
8
let abi = data.result;
9
console.log(abi);
10
​
11
const node = "wss://ropsten.infura.io/ws/v3/733a7efe57364ffd9210b582d7cd0cb3";
12
const provider = new ethers.providers.WebSocketProvider(node);
13
​
14
// initiating a new Wallet, passing in our private key to sign transactions
15
let privatekey = "fdfb72ce9754e3cbc1e79e44a8e20804cebd3c4a347605c6a3462a8de05b8784";
16
let wallet = new ethers.Wallet(privatekey, provider);
17
​
18
// print the wallet address
19
console.log("Using wallet address " + wallet.address);
20
}
21
​
22
main();
Copied!

6. Reading a contract

Finally, to interact with a smart contract we'll need to create a new Contract class.
The Contract class accepts an input of a contract address, an ABI (which we retrieved from the API earlier), and a wallet address to pay gas for any contract interactions.
1
const fetch = require('node-fetch');
2
const ethers = require("ethers");
3
​
4
async function main() {
5
const response = await fetch('https://api-ropsten.etherscan.io/api?module=contract&action=getabi&address=0xC1dcBB3E385Ef67f2173A375F63f5F4361C4d2f9&apikey=YourApiKeyToken');
6
const data = await response.json();
7
​
8
let abi = data.result;
9
console.log(abi);
10
​
11
const node = "wss://ropsten.infura.io/ws/v3/733a7efe57364ffd9210b582d7cd0cb3";
12
const provider = new ethers.providers.WebSocketProvider(node);
13
​
14
let privatekey = "fdfb72ce9754e3cbc1e79e44a8e20804cebd3c4a347605c6a3462a8de05b8784";
15
let wallet = new ethers.Wallet(privatekey, provider);
16
​
17
console.log("Using wallet address " + wallet.address);
18
​
19
// specifying the deployed contract address
20
let contractaddress = "0xC1dcBB3E385Ef67f2173A375F63f5F4361C4d2f9";
21
22
// initiating a new Contract
23
let contract = new ethers.Contract(contractaddress, abi, wallet);
24
}
25
​
26
main();
Copied!
Having a closer look at the ABI we retrieved in Step 2, we can see that the contract has a function named retrieve, that doesn't accept an input however does return a uint256 number as an output.
1
[
2
{
3
"inputs":[
4
// no input required
5
],
6
"name":"retrieve", // function name retrieve
7
"outputs":[
8
{
9
"internalType":"uint256",
10
"name":"",
11
"type":"uint256" // returns a uint256 output
12
}
13
],
14
"stateMutability":"view",
15
"type":"function"
16
},
17
{
18
"inputs":[
19
{
20
"internalType":"uint256",
21
"name":"num",
22
"type":"uint256"
23
}
24
],
25
"name":"store",
26
"outputs":[
27
28
],
29
"stateMutability":"nonpayable",
30
"type":"function"
31
}
32
]
Copied!
We can therefore call that function of the contract, read the value stored and print it out.
You may run this code from your console using the command node script.js.
Reading data stored in a contract incurs no gas cost, as it does not change the state of the Ethereum blockchain.
1
const fetch = require('node-fetch');
2
const ethers = require("ethers");
3
​
4
async function main() {
5
const response = await fetch('https://api-ropsten.etherscan.io/api?module=contract&action=getabi&address=0xC1dcBB3E385Ef67f2173A375F63f5F4361C4d2f9&apikey=YourApiKeyToken');
6
const data = await response.json();
7
​
8
let abi = data.result;
9
console.log(abi);
10
​
11
const node = "wss://ropsten.infura.io/ws/v3/733a7efe57364ffd9210b582d7cd0cb3";
12
const provider = new ethers.providers.WebSocketProvider(node);
13
​
14
let privatekey = "fdfb72ce9754e3cbc1e79e44a8e20804cebd3c4a347605c6a3462a8de05b8784";
15
let wallet = new ethers.Wallet(privatekey, provider);
16
​
17
console.log("Using wallet address " + wallet.address);
18
​
19
let contractaddress = "0xC1dcBB3E385Ef67f2173A375F63f5F4361C4d2f9";
20
let contract = new ethers.Contract(contractaddress, abi, wallet);
21
​
22
// calling the "retrieve" function to read the stored value
23
let read = await contract.retrieve();
24
console.log("Value stored in contract is " + read.toString());
25
}
26
​
27
main();
Copied!

7. Writing a contract

Referring to the ABI once again, we can see that the contract has another method store, which accepts a uint256 number as an input and does not return any output.
1
[
2
{
3
"inputs":[
4
5
],
6
"name":"retrieve",
7
"outputs":[
8
{
9
"internalType":"uint256",
10
"name":"",
11
"type":"uint256"
12
}
13
],
14
"stateMutability":"view",
15
"type":"function"
16
},
17
{
18
"inputs":[
19
{
20
"internalType":"uint256", // requires a uint256 input
21
"name":"num",
22
"type":"uint256"
23
}
24
],
25
"name":"store", // function name store
26
"outputs":[
27
// no output returned
28
],
29
"stateMutability":"nonpayable",
30
"type":"function"
31
}
32
]
Copied!
We can call that function and pass in any number as a parameter. To check that its updated, we'll wait for a 2 block confirmation, and read the contract again to confirm that the number has been updated.
You may run this code from your console using the command node script.js.
Writing new data to a contract will incur gas costs, as it requires fees to be paid to miners to process your transaction. Make sure your wallet has been funded with some testnet ETH
​
1
const fetch = require('node-fetch');
2
const ethers = require("ethers");
3
​
4
async function main() {
5
const response = await fetch('https://api-ropsten.etherscan.io/api?module=contract&action=getabi&address=0xC1dcBB3E385Ef67f2173A375F63f5F4361C4d2f9&apikey=YourApiKeyToken');
6
const data = await response.json();
7
​
8
let abi = data.result;
9
console.log(abi);
10
​
11
const node = "wss://ropsten.infura.io/ws/v3/733a7efe57364ffd9210b582d7cd0cb3";
12
const provider = new ethers.providers.WebSocketProvider(node);
13
​
14
let privatekey = "fdfb72ce9754e3cbc1e79e44a8e20804cebd3c4a347605c6a3462a8de05b8784";
15
let wallet = new ethers.Wallet(privatekey, provider);
16
​
17
console.log("Using wallet address " + wallet.address);
18
​
19
let contractaddress = "0xC1dcBB3E385Ef67f2173A375F63f5F4361C4d2f9";
20
let contract = new ethers.Contract(contractaddress, abi, wallet);
21
​
22
let read = await contract.retrieve();
23
console.log("Value stored in contract is " + read.toString());
24
​
25
// call the "store" function to update the value to 420
26
let write = await contract.store(420);
27
28
// wait for 2 blocks of confirmation
29
write.wait(2)
30
.then(async () => {
31
// read the contract again, similar to above
32
let read = await contract.retrieve();
33
console.log("Updated value stored in contract is " + read.toString());
34
});
35
}
36
​
37
main();
Copied!

Beyond the testing grounds

You've now mastered how to programmatically interact with smart contracts
✨
, using ABIs retrieved from the Etherscan APIs.
Possible use cases from this include minting NFTs right on the dot
🎯
, performing trades on Decentralised Exchanges (DEXs)
πŸ’°
and automating token transfers at certain time intervals
⏰
.
The full sample code is on Github, feel free to experiment and use it ( with caution ) on real world contracts out there.
Last modified 7d ago