Working with smart contract on the Frontend
Published: 2023-07-04 09:00:00


## Table of Contents

1.  [Working with smart conrtacts on the Frontend](#org1bbf0bf)
2.  [Connecting to a wallet](#orga2c5443)
3.  [Better UX for mobile users](#orgf2ca362)
4.  [Connecting to the smart contract](#org8efa526)
5.  [Exporting all the logic into a hook](#org0d154c2)
6.  [Caveats](#org64adb7e)
7.  [Thank you for reading](#org14c2822)

<a id="org1bbf0bf"></a>

## Working with smart conrtacts on the Frontend

Hello fellow web3 enthusiasts, in this article, we'll explore how to integrate smart contracts on the frontend using `ethers` [a library for interacting with Ethereum and its ecosystem](https://docs.ethers.org/v6/). Its often used to connect your decentralized app(dapp) to MetaMask wallet, and interact with Smart Contracts on Ethereum blockchain.

<a id="orga2c5443"></a>

## Connecting to a wallet

ethers provides an extremely simple API to connect to a wallet


```
if (window.ethereum) {
  const accounts = await window.ethereum.request({
    method: "eth_requestAccounts",
  });
  const account = accounts[0];

  setIsWalletConnected(true);
  setCurrentAccount(account);

  console.log("Connected Wallet:", account);
} else {
  alert("Connect your Ethereum Wallet");
}
```


If you are using TypeScript you'll get an error that property `ethereum` doesn't exist on `window`. To fix it create a `react-app-env.d.ts` in your root directory and paste the following

```
*/* <reference types="react-scripts" />

interface Window {
    ethereum: any
}
```

The only caveat is that it won't work on mobile browsers, since there's no way to install the [Metamask extension](https://metamask.io/) on there. You'll need to use the browser inside metamask app on mobile. 

![Metamask in app browser](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kn3yhub791y80addh4x2.jpeg)

<a id="orgf2ca362"></a>

## Better UX for mobile users

Some mobile users might be confused if they'll open your open outside metamask. Thankfully, MetaMask has a [deeplink generator](https://metamask.github.io/metamask-deeplinks/) which you can use to redirect mobile users to the app. Before the user open a page which requires MetaMask, you can check whether he's on mobile and redirect him if needed 

```
<a href={\`${
        !window.ethereum ? `https://metamask.app.link/dapp/${process.env.NEXT_PUBLIC_APP_URL}\` : ''
}pagesWith/metamask\`}>Go to page</a>
```

<a id="org8efa526"></a>

## Connecting to the smart contract

You'll need your smart contract's ABI stored somewhere on the FE, along with the contract address and the amount you want to send.

```
import { BrowserProvider, Contract, parseEther } from 'ethers';

const provider = new BrowserProvider(window.ethereum);
const signer = await provider.getSigner();
const smartContract = new Contract(
  contractAddress,
  contractABI,
  signer
);

if (isWalletConnected) {
  const valueToSend = parseEther(amount); */ Value to send in Ether
  const methodName = 'publicSale'; /* Replace with your payable method name

  const transaction = await smartContract.connect(signer)[methodName]({
  value: valueToSend
});

  const receipt = await transaction.wait();
  console.log('Transaction hash:', transaction.hash);
  console.log(receipt);
  return transaction;
} else {
  alert("Connect your wallet first to request PAC tokens.");
}
```

The code also checks if your wallet is connected first, before making the transaction. One of the cool features is ethers picks up the chain you are using automatically, so there's no need for additional config.

<a id="org0d154c2"></a>

## Exporting all the logic into a hook

Now, let's make our code a bit more suitable for React. All those separate functions are great, but using them in a React component can be a hassle. So let's encalpsulate everything into a hook.

```
import {
    useEffect,
    useState
} from "react";
import {
    abi
} from '@/mock/abi';
import {
    BrowserProvider,
    Contract,
    parseEther
} from 'ethers';

export default function useMetamaskSdk() {
    const [isWalletConnected, setIsWalletConnected] = useState(false);
    const [currentAccount, setCurrentAccount] = useState(null);

    const contractAddress: string = process.env.NEXT_PUBLIC_CONTRACT_ADDRESS // It 's better to store sensetive data like that in .env
    const contractABI = abi.abi; // Your abi, make sure to point to the Abi object itself.

    const checkIfWalletIsConnected = async () => {
        try {
            if (window.ethereum) {
                const accounts = await window.ethereum.request({
                    method: "eth<sub>requestAccounts</sub>",
                });
                const account = accounts[0];

                setIsWalletConnected(true);
                setCurrentAccount(account);

                console.log("Connected Wallet:", account);
            } else {
                alert("Connect your Ethereum Wallet");
            }
        } catch (error) {
            console.log(error);
        }
    };

    // Amount - Ether value e.g 0.003
    const requestToken = async (amount: string) => {
        try {
            const provider = new BrowserProvider(window.ethereum);
            const signer = await provider.getSigner();
            const smartContract = new Contract(
                contractAddress,
                contractABI,
                signer
            );

            if (isWalletConnected) {
                const valueToSend = parseEther(amount);*/
                Value to send in Ether
                const methodName = 'publicSale'; // Replace with your payable method name

                const transaction = await smartContract.connect(signer).[methodName]({
                    value: valueToSend
                });

                const receipt = await transaction.wait();
                console.log('Transaction hash:', transaction.hash);
                console.log(receipt);
                return transaction;
            } else {
                alert("Connect your wallet first to request PAC tokens.");
            }
        } catch (error) {
            console.log(error);
        }
    };

    // Connecting the wallet on the first render
    useEffect(() => {
        checkIfWalletIsConnected();
    }, []);

    return {
        requestToken,
        checkIfWalletIsConnected,
        isWalletConnected,
        currentAccount
    }
}
```

<a id="org64adb7e"></a>

## Caveats

There's a couple of downsides to using ethers instead of [Moralis](https://docs.moralis.io/)

-   Mobile experience suffers a bit, since users have to go through MetaMask browser instead of their preferred one. With Moralis, you can [use WalletConnect](https://docs.moralis.io/authentication-api/evm/how-to-sign-in-with-walletconnect) which recently started supporting MetaMask, so you can do it all in your browser.
-   Poor wallet support. When using WalletConnect instead of ethers, you have a much wider choice of wallets. Even thought MetaMask is used by 80-90% of users, you can grow your user base by offering more wallet options.

Moralis isn't the silver bullet as well, since compared to ethers its API isn't that powerful. So you need to weigh the upsides and downsides of both. We'll cover using Moralis in our next article, so you could compare it with ethers and decide easily.  

<a id="org14c2822"></a>

## Thank you for reading

If you have any questions or suggestions, feel free to leave them in the comments!

---

At MiKi we help businesses make stunning websites with a blazing-fast and cost-efficient cloud backend.
Interested?
Feel free to give us a call at +447588739366, book a meeting at https://lnkd.in/gGmfJu8z or feel out the contact form at our website https://www.miki.digital/contact