My Image
CoursesQuizzesProblemsContestsSmartBooks
Contest!

No results found

LOGINREGISTER
My ProgressCoursesQuizzesProblemsContestsSmartbooks
Published on 4 Jul 2021
Connect Solidity Smart Contracts to Frontend and interact with it
The Copy Paste Template method to boost your Dapp building process
img
Rajendra Bisoi
0
Like
2430

Here, in this tutorial we will be looking at building your 1st Blockchain App.

Assuming you know all the basics of Smart Contract ABI, Adresses, Use of Metamask Test Networks in Remix-IDE using Injected Web3 option

Let's get started

So as of now you have a Solidity Smart Contract having two types of functionality

  • One method which takes User Input and shows Output (Say 'methodOne( userInputArgument )' )
  • Another one which only shows output (Say 'methodTwo( )')

To connect with frontend 1st you run the following command in your project folder in command prompt

npm init

Basically this will create the required JSON files in your folder and will add necessary NPM modules

If you have a frontend HTML page for your Solidity contract to interact then you copy paste the following web3.js, jquery scripts

<!-- jquery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>

<!-- web3 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/web3/1.4.0/web3.min.js"></script>  

 

Then copy paste the following code to connect your Frontend with Meta Mask

Don't forget to copy paste your ABI inside var ABI & copy paste your smart contract adress inside var Address

 <script type="text/javascript">
    async function loadweb3(){
        if(window.ethereum){
            window.web3=new Web3(window.ethereum);
            window.ethereum.enable(); 
        } 
    }        
       
     async function loadContract(){
          //ABI & address of owner who deployed it on metamask network in RemixIDE
        var ABI = ///Copy paste your Smart Contract ABI
        var Addresss = ///Copy paste your Smart Contract Address inside '  '
          return await new window.web3.eth.Contract( ABI, Address); 
      } 
      
        
      async function load(){
            await loadweb3();
         window.contract = await loadContract();
        }
         
      
    load();  
      
</script>

Boom! you are ready to go with Meta Mask connected to your smart contract....

 

Now let's interact with smart contract functions 

let's say we have buttons to interact with smart contract functions methodOne(userInputArgument) & methodTwo( ) as defined earlier



///////////////////////// Interact with smart contract methods which takes user input and shows output /////////////////////

<input type="text" id="userInputArgument" >                                                 //Here we take user input & stored it in id ="userInputArgument"
<button type="button"  onclick="callMethodOne( );"> mOne </button>       //Here on clicking button mOne a javascript function callMethodOne( ) will be called
<script>
     async function callMethodOne( )
{
          var amtA = 0;

          //We stored the valued captured by input field through id ="userInputArgument" inside a variable "amtA"
          amtA = $('#userInputArgument').val( );    
                                             
          web3.eth.getAccounts().then(function(accountsA){
              var accA = accountsA[0];

              //Here we call the smart contract method that we defined earlier methodOne(userInputArgument)
              return contract.methods.methodOne(amtA).send({from:accA});                                         

                            
          })
 } 


</script>
///////////////////////// Interact with smart contract methods which only shows output without taking any input /////////////////////

<button type="button"  onclick="callMethodTwo( );"> mTwo </button>     //Here on clicking button "mTwo" a javascript function callMethodTwo( ) will be called

<script>
 async function callMethodTwo( ){

           //Here we call the smart contract method that we defined earlier methodTwo( )
          const amtB = await window.contract.methods.methodTwo( ).call();                   
         
      }

</script>

and that's all......

You are now good to go on your journey of building smart contracts......

 

For many more exciting tutorials keep following my username @BlockTalks_Raj

 

 

!!!!!HAPPY LEARNING!!!!!

 

 

 

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
11508
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
8103
2
img
18 Aug 2021
Send transaction with web3 using python
Introduction to web3.py and sending transaction on testnet
3 min read
6229
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
5540
3