Testing vue + web3 and smart contract on localhost: Part2

Seobs
4 min readApr 13, 2022

In part 1, we deployed Smart Contract in the localhost.

In part 2, we will use the Smart Contract by Vue.

Vue

I used vue-cli and created a project using vue create.

Vue & MetaMask

Checking whether MetaMask is installed and connecting is possible with window.ethereum without a separate package.

This is part of the code I wrote.

const { ethereum } = window;...let accounts = await ethereum.request({ method: "eth_accounts" }); // connection checkif (accounts.length === 0) {
accounts = await ethereum.request({method: "eth_requestAccounts"}); // connection try
}

Vue & Smart Contract

To connect with smart contracts, I used ethers package.

In order to connect to the smart contract using the package, you need the address of the wallet and the ABI file.

All can be obtained from the Remix IDE.

First, the address can be obtained from the bottom of the distribution screen.

ABI file is under the compilation screen.
The copied ABI information must be saved as a file.

This is part of the code I wrote.

import SimpleStorage from "../utils/SimpleStorage.json"; ... const {ethereum} = window; 
const provider = new ethers.providers.Web3Provider(ethereum);
const signer = provider.getSigner();
const connectedContract = new ethers.Contract(
"ADDRESS",
SimpleStorage,
signer
);

Next, try using the GET function of Smart Contract.

If you set 200 in Remix IDE, you can see that 200 is displayed as the result.

let getNumber = await connectedContract.get(); console.log(getNumber.toString(10));

Let’s try using SET function.
If you use set, you will be asked for gas to open your wallet.

console.log(await connectedContract.set(100));

Add Ganache Account to MetaMask

I’m currently rejecting it because I don’t have enough ETH.
And I will add a new account with ETH.

Open MetaMask and click the Profile button in the upper right corner.

Then click Get Account.

The private key string we’ll be using here comes from ganache.

If you look at the account tab of ganache, there are many accounts.

To the right of every row is a key icon.

Click on anything and the SECRET KEY will appear.

Copy that KEY, enter it into MetaMask and import button.

And run the SET function again.

If you run GET function in Remix IDE, you can see that it is changed to 100.

--

--