This is a premium alert message you can set from Layout! Get Now!

Integrating Web3 into Vue applications

0

With Web3, it is possible to build decentralized applications on a blockchain network, giving users full ownership of their own data. The blockchain network uses smart contracts to handle all the backend logic of decentralized applications.

As the most popular, programmable blockchain network, Ethereum allows developers to build and manipulate decentralized applications (DApps), decentralized finance (DeFi), smart contracts, and non-fungible tokens (NFTs).

In this article, we’ll cover the basics of using Web3 in Vue applications, including the installation process and interacting with smart contracts. To follow along with this article, you’ll need the following:

  • Understanding of the Vue CLI
  • Basic understanding of Web3
  • Familiarity with Solidity smart contracts and knowledge of how to deploy them

Table of contents

What is Web3?

Web3 is a new generation of the internet that is based on blockchain technology, promoting decentralization and token-based economics. Calling smart contracts and sending transactions make up most of the interactions on a blockchain network.

What are smart contracts?

A smart contract is a self-executing computer software that lives on a blockchain network. The blockchain executes a smart contract as soon as it is deployed. When the contract is executed, it creates interfaces that DApps use to extend their functionality.

Consider the following simple Solidity smart contract:

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.0;

contract Contract {
    string private text;

    function speak() public view returns (string memory) {
        return text;
    }

    function changeText(string memory newText) public {
        text = newText;
    }
}

When you deploy the contract above to the blockchain network, it creates two interface methods, speak, which returns a text string, and changeText, which changes the string that speak returns.

Project setup

If you already have a Vue project ready for integration, you can skip this section. If you don’t, create the project using the following command for npx package manager:

npx vue create web3-project

If you use the Yarn package manager, use the following command instead:

yarn vue create web3-project

In the menu prompts, select either Vue3 or Vue2. It doesn’t matter which one you choose because you can integrate Web3 in both of them the same way. After creating the project, write the following code in your App.vue file:

<template>
  <div>
    <!-- connect-wallet button is visible if the wallet is not connected -->
  <button v-if="!connected">Connect wallet</button>
    <!-- call-contract button is visible if the wallet is connected -->
    <button v-if="connected">Call contract</button>
    
  </div>
</template>

<script>

export default {
  name: 'App',

  data() {
    return {
      connected: false,
      contractResult: '',
    }
  },
}
</script>

In App.vue, we have two buttons; the first is for connecting a wallet, and the second is for calling a smart contract method.

The call contract button is hidden until the user connects their wallet to the web application. Our application uses the connected state variable to save the wallet connection state.

Setting up Web3

In your project directory, run the command below to install the Web3 package using npm:

npm install web3

If you’re using Yarn, run the following command instead:

yarn add web3

After installing the package, we import Web3 into the App.vue file and run the project to test its compatibility:

...
<script>
import Web3 from 'web3'
export default {
  name: 'App',
…

If you don’t receive any error messages besides Web3 is imported but never used, Web3 is compatible with your framework. But, if the framework generates other errors, you have to switch to an older version of Vue. Web3 compatibility problems arise with the Webpack 5 module, which Vue 3 uses.

Connecting our wallet

MetaMask is an application that allows users to store and connect their wallets to Web3 applications. Metamask can be installed in all major browsers. By connecting their wallet to a website, a user can do the following:

  • Buy and sell tokens on a website
  • Manage digital assets on a blockchain network
  • Make transactions to accounts on a website
  • Interact with smart contracts on a blockchain network

When you install the MetaMask extension in your browser, the extension creates a window.ethereum object. Web3 applications use the window.ethereum object to access the user’s wallet and connect to the Ethereum network.

The window.ethereum.request() method prompts the user to connect their MetaMask wallet:

ethereum.request({ method: 'eth_requestAccounts' })

We can use this prompt to register a wallet connect event to our connect wallet button. Add the following code to your App.vue file:

<template>
  <div>
    <!-- "connect" click event is registered -->
>    <button v-if="!connected" @click="connect">Connect wallet</button>
    <button v-if="connected">Call contract</button>
    
  </div>
</template>

<script>
export default {
  name: 'App',

  data() {
    return {
      connected: false,
      contractResult: '',
    }
  },

>  methods: {

>    connect: function () {
>        // this connects to the wallet
>      
>      if (window.ethereum) { // first we check if metamask is installed
>        window.ethereum.request({ method: 'eth_requestAccounts' })
>          .then(() => {
>            this.connected = true; // If users successfully connected their wallet
>          });
>      }
>    }
>  }
}
</script>

When the user clicks the connect wallet button, a MetaMask prompt appears, allowing the user to select the accounts they want to connect. After the user connects their wallet, the connected state variable in the App.vue file becomes true.

Interact with deployed smart contracts

Deployed smart contracts create interfaces that Web3 applications interact with. To access these interfaces, we need to supply Web3 with the ABI, a description of the smart contract’s interface, and the contract address, the location of the contract on the Ethereum network.

Before writing this article, I deployed a smart contract on the Rinkeby test network. I’ll use its ABI and address in the following example, but if you already have a deployed smart contract, you can use that contract’s address and ABI instead of the ones included here.

To interact with deployed contracts, create an instance of Web3 using the window.ethereum object:

let web3 = new Web3(window.ethereum);

Then, create a reference to the deployed contract using its ABI and address:

let contract = new web3.eth.Contract(abi, contractAddress)

After initializing the contract, you can interact with it. If the contract has an interface method called greet, we call it using the code below:

contract.methods.greet().call()

Now, we’ll modify the call contract button to call a contract with the greet method of your deployed contract:

<!-- vue -->
<button v-if="connected" @click="callContract">Call contract</button>

Next, create a callContract method in the Vue object that the call contract button calls:

callContract: function () {
  // method for calling the contract method
  let web3 = new Web3(window.ethereum);
  let contractAddress = '0xC0B2D76aB95B7E31E241ce713ea1C72d0a50588e';

  let abi = JSON.parse(`[{"inputs": [],"stateMutability": "nonpayable","type": "constructor"},{"inputs": [],"name": "greet","outputs": [{"internalType": "string","name": "","type": "string"}],"stateMutability": "view","type": "function"}]`);


  let contract = new web3.eth.Contract(abi, contractAddress);

  contract.methods.greet().call()
    .then(result => this.contractResult = result);
}

The callContract method will be registered as the button’s click event and will call the greet method in the deployed smart contract:

<template>
  <div>
    <button v-if="!connected" @click="connect">Connect wallet</button>

    <!-- "callContract" event handler is added -->
>    <button v-if="connected" @click="callContract">Call contract</button>

    <!-- displays the result of the contract -->
    
  </div>
</template>

<script>
import Web3 from 'web3'

export default {
  name: 'App',

  data() {
    return {
      connected: false,
      contractResult: '',
    }
  },

  methods: {

    connect: function () {
      let ethereum = window.ethereum;
      if (ethereum) {
      ethereum.request({ method: 'eth_requestAccounts' })
       .then(() => {
            this.connected = true;
          });
      }
    },

>    callContract: function () {
>        // method for calling the contract method
>      let web3 = new Web3(window.ethereum);
>      let contractAddress = '0xC0B2D76aB95B7E31E241ce713ea1C72d0a50588e';

>      let abi = JSON.parse(`[{"inputs": [],"stateMutability": "nonpayable","type": "constructor"},{"inputs": [],"name": "greet","outputs": [{"internalType": "string","name": "","type": "string"}],"stateMutability": "view","type": "function"}]`);


>      let contract = new web3.eth.Contract(abi, contractAddress);

>      contract.methods.greet().call()
>        .then(result => this.contractResult = result);
>    }

  }
}
</script>

After the user connects their wallet and calls the contract, the app should look something like the image below:

User Connect Wallet Output

Conclusion

In this article, we learned how to use Vue to create a Web3 app using the Ethereum blockchain network, connect a MetaMask wallet, and interact with smart contracts. As you can see, integrating Web3 into a Vue application is fairly straightforward as long as you’re familiar with Solidity. Web3 offers major benefits for privacy and data ownership, and we explored some of the tools and concepts that make up this process, like smart contracts.

The post Integrating Web3 into Vue applications appeared first on LogRocket Blog.



from LogRocket Blog https://ift.tt/xYm3SBw
via Read more

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment

Search This Blog

To Top