Interact with deployed smart contracts
You can get started with the Developer Quickstart to rapidly generate local blockchain networks.
This tutorial shows you how to interact with smart contracts that have been deployed to a network.
Prerequisites
- A network with a deployed smart contract as in the deploying smart contracts tutorial
Interact with public contracts
This tutorial uses the SimpleStorage.sol
contract:
pragma solidity ^0.7.0;
contract SimpleStorage {
uint public storedData;
constructor(uint initVal) public {
storedData = initVal;
}
function set(uint x) public {
storedData = x;
}
function get() view public returns (uint retVal) {
return storedData;
}
}
Once the contract is deployed, you can perform a read operation using the get
function call and a write operation using the set
function call. This tutorial uses the web3js library to interact with the contract. A full example of these calls can be found in the Developer Quickstart.
1. Perform a read operation
To perform a read operation, you need the address that the contract was deployed to and the contract's ABI. The contract's ABI can be obtained from compiling the contract; see the deploying smart contracts tutorial for an example.
Use the web3.eth.Contract
object to create a new instance of the smart contract, then make the get
function call from the contract's list of methods, which will return the value stored:
async function getValueAtAddress(
host,
deployedContractAbi,
deployedContractAddress,
) {
const web3 = new Web3(host);
const contractInstance = new web3.eth.Contract(
deployedContractAbi,
deployedContractAddress,
);
const res = await contractInstance.methods.get().call();
console.log("Obtained value at deployed contract is: " + res);
return res;
}