My Image
CoursesQuizzesProblemsContestsSmartBooks
Contest!

No results found

LOGINREGISTER
My ProgressCoursesQuizzesProblemsContestsSmartbooks
Published on 27 Jun 2021
Interact solidity contract functions in javascript
Call solidity contract functions in simple vanilla JS
img
Ganesh Deshpande
0
Like
1254

Creating project

Create a basic nodeJS project. We will be using index.html file to interact with smart contract functions.

 

Get web3js for client side operations

We will need web3js to create instance of our contract and interact with the functions , if you are setting up web3 at backend , i.e nodeJS you can directly install it throught npm package otherwise include it as cdn for client side inteaction purpose from here.

 

 

Connecting browser to metamask

We need rpc provider in order to ineract with solidity contract function , so for client side metamask fullfills the requirement for that, if you are working in backend you can user popular providers like infura.

connecting browser o metamask is simple thing we will just check if ethereum is available in our js window object.

create script tag in index.html file or you can create new js file and import it in index.html and check for window.ethereum like this :

window.onload = async function () {
            if (window.ethereum) {
                console.log("This is DAppp Environment");
                var accounts = await ethereum.request({ method: 'eth_requestAccounts' });
                var currentaddress = accounts[0];
            } else {
                console.log("Please connect with metamask");
            }
        }

In the if statement we check for ethereum and then access accounts connected to our DApp. with ethereum.request method. Thus now we have connected with metamask. you can log the account address which is stores in variable currentaddress to check proper working.

 

Getting contract instance in our project

Declaring ABI and contract Address

If you have already deployed your contract then you can skip this step.

Head over to the remix. And create new contract file. Follow this article to deploy contract on testnet and how to get ABI and contract adderss. If you still want to deploy on truffle but using remix you can check it here.

Once you got the abi and contract address declare it as global variables in our JS and in window.ethereum if statement create a instance of web3 like show below.

window.onload = async function () {
            if (window.ethereum) {
                console.log("This is DAppp Environment");
                var accounts = await ethereum.request({ method: 'eth_requestAccounts' });
                var currentaddress = accounts[0];

                web3 = new Web3(window.ethereum);
                mycontract = new web3.eth.Contract(abi, address); // add your alreay defined abi and address in Contract(abi, address)
                console.log(mycontract);

            } else {
                console.log("Please connect with metamask");
            }
        }

note that web3 and mycontract are defined as global varibles , you can customize it according to your need. Now we have our contract instance in mycontract variable.

 

How to call function ?

 mycontract.methods.retrieve().call().then((res) => {
                    alert(res);
                }).catch((err) => {
                    alert(err);
                })

here retrieve is the function defined in smart contract and returns uint256 value, thus in callback funtion we can get result or catch error.

 

How to Send function ?

mycontract.methods.store(55).send({ from: currentaddress }).then(() => {
                    alert("stored success!");
                }).catch((err) => {
                    console.log(err);
                })

here store is the function defined in smart contract and takes uint256 as argument, for multiple arguments you should pass the same in store(arg1, arg2, arg3, ...etc). then in send we have defined from address that is already declared. 

 

How to pass value to contract ?

If you want to send ethere to contract you just have to add value: eth in send method. this is taken in wei by defualt. Also if you are sending ether to contract the function should be payable declared in smart contract.

mycontract.methods.deposite().send({ from: currentaddress, value: 10 * 10 ** 18 }).then(() => {
                    alert("deposite success!");
                }).catch((err) => {
                    console.log(err);
                })

here deposite is function declared as payable in smart contract and we are sending 10 etheres to the contract in wei format.

thats it this is all easy..

Enjoyed the SmartBook?
Like
logo
contact@dapp-world.com
Katraj, Pune, Maharashtra, India - 411048

Follow Us

linkedintwitteryoutubediscordinstagram

Products

  • SmartBooks
  • Courses
  • Quizzes
  • Assessments

Support

  • Contact Us
  • FAQ
  • Privacy Policy
  • T&C

Backed By

ah! ventures

Copyright 2023 - All Rights Reserved.

Recommended from DAppWorld
img
1 May 2021
How to connect Ganache with Metamask and deploy Smart contracts on remix without
Set up your development environment with (Metamask + Ganache + Remix) and skip truffle :)
3 min read
11494
5
img
8 Jul 2021
How to interact with smart contarct from backend node js
call and send functions from backend server side using nodejs
3 min read
8068
2
img
18 Aug 2021
Send transaction with web3 using python
Introduction to web3.py and sending transaction on testnet
3 min read
6215
5
img
5 Aug 2021
Deploy Smart Contract on Polygon POS using Hardhat
how to deploy smart contracts on polygon pos chain using hardhat both mainnet and testnet ?
3 min read
5533
3