Smart Contracts – How to Interact with Smart Contract Using Web3.js?

contract-deploymentweb3js

I have deployed a contract in rinkeby network. Now I have the address of the contract and ABI of the contract.

    var contract = new web3.eth.Contract(ContractABI, 'ContractAddress')

But now how to call the functions and how to pass the arguments and console.log the return values.

Best Answer

First, you need a provider which connects you to the Rinkeby network. It can be MetaMask or infura I have a separate file called 'web3.js' which has this code:

import Web3 from 'web3';


let web3;
if (typeof window !== 'undefined' && typeof window.web3 !== 'undefined') {
  // we check if metamask is running
  web3 = new Web3(window.web3.currentProvider);
} else {
  // set up provider through infura
  const provider = new Web3.providers.HttpProvider(
    // pass url of remote node
    'rinkeby infura link that you receive after signing up'
  );
  web3 = new Web3(provider);

}

export default web3;

Now comes the trick: Create another file such as contractName.js

import web3 from './web3';

const address = 'your contract addess';  // use quotes! 

const abi = [contractAbi]; 
// contract abi doesn't have quotes an will be something like [{a lot of code}, {a lot of code}, … ];  REMEMBER to add ; or it won't work 
export default new web3.eth.Contract(abi, address);

Now in normal files just call web3 from the file web3.js and you'll be able to call functions from your contract. For example, if your contract has a 'helloWorld()' you will have to use something like

contractName.methods.helloWorld().call(); 

Check web3 documentation for more information

Related Topic