OpenReplay
Navigate back to the homepage
BLOG
Browse Repo
Back

Creating a Blockchain Decentralized App with Vue and Tezos

Melvin Kosisochukwu
May 30th, 2022 · 5 min read

Many organizations/individuals have adopted blockchain technology and development in recent years. Blockchain technology is gaining so much traction due to the decentralization and security provided by storing data on the blockchain. Decentralization here means that control and decision-making aren’t handled by an individual or a centralized entity but by a distributed network. You can say that a blockchain by its users. Ultimately blockchain provides a very secure network that is impossible to hack. This security increases as more blocks are included in the chain.

Tezos is a blockchain built to adjust, adapt, and add features and functionality through its proven on-chain upgrade mechanism. It is a notable skill to learn and understand how to connect a Vuejs application to smart contracts built on the Tezos blockchain. Holding Tezos tokens (“tez”) allows one to interact with the Tezos blockchain. You can store tez in digital wallets supported by Tezos. You can find additional information on the Tezos blockchain here.

This article will walk you through interacting with a smart contract for a memo application deployed on the Tezos blockchain from a Vue application. To continue with this article, you need a fundamental knowledge of Vue and Vuex; you can find the complete code for the project here.

Creating our app

To start with our Vue application, we will create a Vue app and add Vuex from the CLI.

1vue create tez_memo && vue add vuex

Setting up

Select your configuration option and continue with the app setup. For this article, we will select the “Default ([Vue 3] babel, eslint)” configuration. After creating the app, you will need to install all the required dependencies for the project.

1yarn add @airgap/beacon-sdk @taquito/beacon-wallet @taquito/taquito bignumber.js buffer path-browserify stream-browserify

Additionally, we will need to configure webpack to resolve polyfill errors due to webpack 5 in the vue.config.js file we will include.

1const { defineConfig } = require("@vue/cli-service");
2var webpack = require('webpack');
3
4module.exports = defineConfig({
5//…
6configureWebpack: {
7 resolve: {
8 fallback: {
9 path: require.resolve("path-browserify"),
10 stream: require.resolve("stream-browserify"),
11 buffer: require.resolve("buffer"),
12 crypto: false,
13 },
14 },
15 plugins: [
16 new webpack.ProvidePlugin({
17 Buffer: ["buffer", "Buffer"],
18 }),
19 ],
20},
21//…
22});

Setting Up Store and RPC Provider

The next step will be to set up the state and actions. We will create the following files in the store folder.

1📂store
2┣ 📜actions.js
3┣ 📜getters.js
4┣ 📜index.js
5┗ 📜mutations.js

I will be focusing on setting up the Tezos connection, so I will move to the actions file. You can preview the content of the other files in store here.

In actions.js, we will be setting up the Tezos RPC connection to the ithacanet, a testnet on the Tezos blockchain. The smart contract we will be working with is deployed on ithacanet. To connect to ithacanet, we will have the following code.

1import { TezosToolkit } from "@taquito/taquito";
2import { BeaconWallet } from "@taquito/beacon-wallet";
3import { ColorMode, NetworkType } from "@airgap/beacon-sdk";
4import { CONTRACT_ADDRESS } from "@/utils";
5import BigNumber from "bignumber.js";
6// Set the network
7const network = { type: NetworkType.ITHACANET };
8// initialize the SDK
9const Tezos = new TezosToolkit("https://ithacanet.ecadinfra.com");
10const wallet = new BeaconWallet({
11 name: "Tez-memo",
12 preferredNetwork: network.type,
13}); // Takes the same arguments as the DAppClient constructor
14Tezos.setWalletProvider(wallet);
15// setting the color mode for beacon wallet
16wallet.client.setColorMode(ColorMode.DARK);
17const getContract = async () => await Tezos.wallet.at(CONTRACT_ADDRESS);

On line 9, I set up a new TezosToolkit with the RPC link to the ithacanet test network; check here for links to other RPC nodes. On line 10, we set up a connection to Beacon; this allows our decentralized app (“dApp”) to interact with the wallet. For additional information on Beacon, you can look at their official documentation.

The next step will be to pass the wallet in the setWalletProvider method on Tezos. On line 17, we have a function that connects to the smart contract. The at method accepts the contract address (a unique identifier for smart contracts deployed on the Tezos blockchain) as a parameter; the wallet to sign contract calls for this use case. Alternatively, you can set up other formats for signing contract calls via TezBridge or inMemory (using the account private key). You can read more on the other formats of signing contract calls here.

Wallet Connection

The next act will be to set up a wallet connection on our dApp; to achieve this, you must request permission to connect to a wallet. In the actions.js file, I have a function connectWallet; it requests permission to connect to a wallet.

1...
2 async connectWallet({ dispatch }) {
3 try {
4 await wallet.requestPermissions({
5 network: network,
6 });
7 dispatch("checkWalletConnection");
8 } catch (error) {
9 console.log(error);
10 }
11 },
12...

On line 4, the request to connect to a wallet is initiated with the requestPermissions method; this function is passed to the connect wallet button in the vue application. When the “Connect Wallet” button is clicked, a modal will pop up with different wallet options.

Image 1: Wallet selection modal

For this article, I will be using the temple wallet, a browser extension wallet. You can download the extension here. Once the connection request has been approved, the connectWallet action will dispatch checkWalletConnection.

1...
2 async checkWalletConnection({ commit }) {
3 try {
4 const activeAccount = await wallet.client.getActiveAccount();
5 let pkh;
6 if (activeAccount) {
7 // If defined, the user is connected to a wallet.
8 pkh = activeAccount.address;
9 commit("updatePkh", pkh);
10 commit("updateConnected", true);
11 } else {
12 commit("updatePkh", "");
13 commit("updateConnected", false);
14 }
15 } catch (error) {
16 console.log(error);
17 }
18 },
19...

This action checks if an account with active permission is on the wallet on line 4. If an active account exists, the pkh (Public Key Hash)/account address is assigned to the pkh state, and the connected state is true. When no active account exists, connected is false, and pkh is an empty string. There is also a need to disconnect wallet permission, and this can be achieved by calling the clearActiveAccount method on the wallet:

1...
2 async disconnectWallet({ dispatch }) {
3 await wallet.clearActiveAccount();
4 dispatch("checkWalletConnection");
5 },
6...

Open Source Session Replay

OpenReplay is an open-source, session replay suite that lets you see what users do on your web app, helping you troubleshoot issues faster. OpenReplay is self-hosted for full control over your data.

replayer.png

Start enjoying your debugging experience - start using OpenReplay for free.

Smart Contract Interaction

After setting up a wallet connection for the application, the next step will be to set up smart contract interaction and access to contract storage. You can preview smart contract storage and methods on a smart contract through network explorers. An example of a network explorer for Tezos is Better Call Dev. To preview the contract, you will need to enter the contract address and search on the platform. To find the smart contract for this project on the explorer here

Image 2: Contract storage on the explorer

The image shows the storage structure. We have a key for setting the id for a new memo, a map with an id and account address pair as key and memo object as value, and a user map that uses an account address as a key and a set of memo ids tied to the account address.

Image 3: Contract methods on the explorer

In this image you can see that the smart contract has four methods: addMemo, deleteMemo, toggleMemoStatus and updateMemo.

Accessing Contract Storage

The next action will be to access the contract storage and display memos existing on storage. I will be doing this in the getMemoList function in the actions file.

1...
2async getMemoList({ state, commit }) {
3 commit("updateLoading", true);
4 try {
5 let active_memo = [];
6 let done_memo = [];
7 if (state.connected) {
8 const contract = await getContract();
9 const storage = await contract.storage();
10 const storage_user_memos = await storage.users.get(state.pkh);
11 const user_memos = storage_user_memos.map((val) => new BigNumber(val).toNumber());
12 console.log(user_memos);
13 for (let index = 0; index < user_memos.length; index++) {
14 const memo = await storage.memos.get({
15 owner: state.pkh,
16 id: user_memos[index].toString(),
17 });
18 const formated_memo = { ...memo, id: new BigNumber(memo.id).toString() };
19 if (!memo.done) {
20 active_memo.push(formated_memo);
21 } else {
22 done_memo.push(formated_memo);
23 }
24 }
25 }
26 commit("updateActiveMemo", active_memo);
27 commit("updateDoneMemo", done_memo);
28 } catch (error) {
29 console.log(error);
30 } finally {
31 setTimeout(() => {
32 commit("updateLoading", false);
33 }, 1000);
34 } // end try catch
35},
36...

You need to call the storage method on the contract to access contract storage, as seen in line 9. To access the set of memo ids for the currently connected account, call the get method on users and pass in the key for the value to access; in this case, the address connected to the dApp. This will return an array of big numbers. On line 11, we loop through the set to convert the big numbers to numbers. The updated set is looped through to get all memos with the id belonging to the active address on lines 13 through 25. Subsequently, the active_memo and done_memo states are updated with the memos returned from the storage.

Making Smart Contract Calls From The Vue Application

From image 3, we know that the smart contract has four methods that can be interacted with. The addMemo method allows you to create a new memo, accepting the memo string as value.

1...
2async addMemo({ dispatch }, memo) {
3 try {
4 const contract = await getContract();
5 const op = await contract.methods.addMemo(memo).send();
6 await op.confirmation()
7 dispatch("softUpdateMemoList");
8 } catch (error) {
9 console.log(error);
10 }
11},
12...

On line 4, a smart contract is initiated by calling the send() method. Line 5 waits for the transaction to be confirmed on the blockchain, and dispatches the softUpdateMemoList action. The softUpdateMemoList is similar to the getMemoList, with the only difference being that it does not update the loading state.

The following method on the smart contract is the deleteMemo; this deletes an existing memo by the account that created the memo. It accepts the memo id as a parameter. N/B: The memo id should be a string.

1...
2async deleteMemo({ dispatch }, id) {
3 try {
4 const contract = await getContract();
5 const op = await contract.methods.deleteMemo(id).send();
6 await op.confirmation()
7 dispatch("softUpdateMemoList");
8 } catch (error) {
9 console.log(error);
10 }
11},
12...

To toggle a memo, you will call the toggleMemoStatus method on the contract. The deleteMemo also accepts the memo id and needs to be called from the account that created the memo.

1...
2async toggleMemoStatus({ dispatch }, id) {
3 try {
4 const contract = await getContract();
5 const op = await contract.methods.toggleMemoStatus(id).send();
6 await op.confirmation()
7 dispatch("softUpdateMemoList");
8 } catch (error) {
9 console.log(error);
10 }
11},
12...

method vs methodsObject

The updateMemo method accepts an object with properties memo and id as the parameter. Previously I initiated smart contract calls in this format:

1contract.methods.['smart contract method'].send()

The contract call sequence will not work if you need to pass an object as a parameter to the smart contract method. To do this, you will use the methodObject , which is demonstrated in updatedMemo action:

1async updateMemo({ dispatch }, payload) {
2 try {
3 const contract = await getContract();
4 const op = await contract.methodsObject.updateMemo(payload).send();
5 await op.confirmation()
6 dispatch("softUpdateMemoList");
7 } catch (error) {
8 console.log(error);
9 }
10},

on line 4 methodObject is used to replace method.

Conclusion

The decentralized application is complete, with all smart contract methods integrated into the application. You can deploy the application on any platform that supports Vue applications. Suppose you want to take it further and deploy the application on a decentralized hosting platform like Fleek. In that case, you can find documentation on achieving that here.

In this article, we went through the complete process of integrating a smart contract deployed on the Tezos blockchain into a Vue application. If you made it to this point, you should be able to connect to a wallet and make smart contract calls on the Tezos blockchain. If you want to learn how to write a smart contract, look at this documentation. You can also find the complete code for the project here and a live version of the application here. Cheers.

newsletter

More articles from OpenReplay Blog

Building a digital Signature pad and Signature Images with Flutter

Create a Flutter app to draw and export your signature in an easy way

May 28th, 2022 · 5 min read

Building a static website using Iles.js

Use Iles.js to build minimal sized static sites

May 27th, 2022 · 4 min read
© 2022 OpenReplay Blog
Link to $https://twitter.com/OpenReplayHQLink to $https://github.com/openreplay/openreplayLink to $https://www.linkedin.com/company/18257552