One of the most common ways is to copy the ABI using the ABI button under compile tab of
Ethereum REMIX IDE after the smart contract has complied.
Another way is compiling and generating ABI using
solc, which provides JavaScript bindings for
Solidity Compiler. To install solc, we need to have npm, which comes with
node.js. Check if node.js is installed on your system or not.
If not installed, you can download the LTS version of NodeJS from the
official website.
Now let’s install solc
$ npm install solc
$ npm install solc
We’ll compile and generate ABI for the following contract, test.sol which is a contract to increment the value of a variable:
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
contract test {
uint256 private count = 0;
function increment() public {
count += 1;
}
function getCount() public view returns (uint256) {
return count;
}
}
Explanation of the code above
Line 1: Specifying
SPDX license type, which is an addition after Solidity ^0.6.8; whenever the source code of a smart contract is made available to the public, these licenses can help resolve/avoid copyright issues. If you do not wish to specify any license type, you can use a special value UNLICENSED or simply skip the whole comment (it won’t result in an error, just a warning).
Line 2: Declaring the Solidity version.
Line 4: Starting our contract name test.
Line 6: Declaring a private variable named count of type unsigned integer and assigning value zero to it.
Line 8-10: Declaring a public function increment, which increases the value of count by one when called.
Line 12-14: Declaring a public function getCount which will return the value of count in unsigned integer form.
Now, let’s get the ABI for the above contract.
$ solcjs test.sol --abi
$ solcjs test.sol --abi
A file named test_sol_test.abi will be created in the same directory; it will have the ABI in the JSON format something like this:
[
{
"inputs": [],
"name": "getCount",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "increment",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
}
]
[
{
"inputs": [],
"name": "getCount",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "increment",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
}
]
[
{
"inputs": [],
"name": "getCount",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "increment",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
}
]