How to interact with the smart contract using web3.js
This article is the sequel to the one below:
Now that we have our smart contract ready, how can we get/send data to it ?
Intro
- When you want to call a function on a smart contract, you need to query one of these nodes and tell it:
- The address of the smart contract
- The function you want to call, and
- The variables you want to pass to that function.
- Ethereum nodes only speak a language called JSON-RPC
Web3 Providers
- Setting up a web3 provider it’s kind of like setting the URL of the remote web server for your API calls in a traditional web app. It tells our code which node we should be talking to handle our reads and writes.
- However, there’s a third-party service so you don’t need to maintain your own Ethereum node in order to provide a DApp for your users — Infura.
Infura
- Infura is a service that maintains a set of Ethereum nodes with a caching layer for fast reads, which you can access for free through their API.
- to check if the user has Metamask installed on the browser, you can use the boilerplate below.
Contract ABI
- ABI stands for Application Binary Interface. Basically it’s a representation of your contracts’ methods in JSON format that tells Web3.js how to format function calls in a way your contract will understand.
- When you compile your contract to deploy to Ethereum, the Solidity compiler will give you the ABI, so you’ll need to copy and save this in addition to the contract address.
Instantiating a Web3.js Contract
- Once you have your contract’s address and ABI, you can instantiate it in Web3 as follows:
Calling Contract Functions
- Web3.js has two methods we will use to call functions on our contract: call and send.
Call
- Call is used for view and pure functions. It only runs on the local node, and won’t create a transaction on the blockchain.
Review: view and pure functions are read-only and don’t change state on the blockchain. They also don’t cost any gas, and the user won’t be prompted to sign a transaction with MetaMask.
Send
- Send will create a transaction and change data on the blockchain. You’ll need to use send for any functions that aren’t view or pure.
What’s a Wei?
- A wei is the smallest sub-unit of Ether — there are 10¹⁸ wei in one ether.
we have reached the end of our article about smart contracts.
It’s Time for you now to write some code…