πŸ“³Frontend Integration Guide

πŸ’‘ Integration guide for a user-facing app that involves the users’ interaction with the blockchain using their self-hosted wallet.

This comprehensive guide details integrating a smart contract with a frontend application, particularly focusing on using web3.js in a React-based environment. You'll learn how to facilitate wallet connections, switch networks, and interact with smart contract functions seamlessly.

Prerequisites

  • A modern JavaScript framework, preferably React, set up in your project.

  • Basic knowledge of JavaScript and React.

  • A package manager such as npm or yarn.

Step 1: Installing web3.js

Web3.js is a JavaScript library that allows your application to interact with Ethereum-compatible blockchains. To install, run:

npm install web3

or, if using Yarn:

yarn add web3

Step 2: Building a "Connect Wallet" Button

In your React component, create a button to enable users to connect their wallet (like MetaMask) to your application. Store the connected wallet instance in the component's state for further interactions.

import React, { useState } from 'react';
import Web3 from 'web3';

const WalletConnect = () => {
  const [web3Instance, setWeb3Instance] = useState(null);

  const connectWallet = async () => {
    if (window.ethereum) { // Check if MetaMask is installed
      try {
        await window.ethereum.enable(); // Request wallet connection
        const web3 = new Web3(window.ethereum); // Initialize web3 instance
        setWeb3Instance(web3); // Store the web3 instance in state
        console.log('Wallet connected');
      } catch (error) {
        console.error('User denied account access', error);
      }
    } else {
      console.log('Please install MetaMask to use this feature.');
    }
  };

  return <button onClick={connectWallet}>Connect Wallet</button>;
};

export default WalletConnect;

Explanation:

  • Web3 Instance: A Web3 instance is created upon successful wallet connection, enabling interaction with Ethereum-based blockchain.

  • User Consent: The window.ethereum.enable() call prompts the user for permission to access their wallet.

Step 3: Network Switching

Implement functionality to switch the user's network to the specific blockchain your smart contract is deployed on.

const switchNetwork = async () => {
  try {
    await window.ethereum.request({
      method: 'wallet_switchEthereumChain',
      params: [{ chainId: '0x1' }], // Use the hexadecimal chain ID of your target network
    });
    console.log('Network switched');
  } catch (switchError) {
    if (switchError.code === 4902) {
      console.log('The network is not available in the user’s wallet.');
      // Optionally, suggest user to add the network
    } else {
      console.error('Network switch error:', switchError);
    }
  }
};

Explanation:

  • Network Switch: The wallet_switchEthereumChain method requests the user’s wallet to switch to the specified network.

  • Error Handling: The code 4902 indicates the requested network is not available in the user's wallet.

Step 4: Initializing Smart Contracts

Prepare your smart contract for interaction by initializing it with its ABI (the interface definition of your smart contract) and address.

import contractABI from './path_to_your_ABI.json'; // Import ABI from a local file

const initializeContract = (web3) => {
  const contractAddress = 'YOUR_CONTRACT_ADDRESS';
  const contract = new web3.eth.Contract(contractABI, contractAddress);
  return contract;

const contract = initializeContract();
};

Explanation:

  • Contract Initialization: Utilizes the ABI and contract address to create a contract instance.

  • Web3 Parameter: Pass the initialized web3 instance to interact with the blockchain.

Step 5: Reading from Smart Contract

For each read function of your smart contract, implement a function to query data from your smart contract. Ensure the contract is initialized before calling this function.

const yourFirstReadFunction = async (contract) => {
  try {
    const data = await contract.methods.yourFirstReadFunction().call();
    console.log('Contract Data:', data);
  } catch (error) {
    console.error('Read error:', error);
  }
};

// Analogous process for every READ function

Explanation:

  • Read Operation: Executes a call on the smart contract, which doesn't require gas as it doesn't alter the blockchain state.

Step 6: Writing to Smart Contract

Create functions to write data or trigger state-changing operations in your smart contract. It requires the user's wallet address and can involve gas costs.

const yourFirstWriteFunction = async (contract, userAddress) => {
  try {
    await contract.methods.yourFirstWriteFunction().send({ from: userAddress });
    console.log('Transaction successful');
  } catch (error) {
    console.error('Write error:', error);
  }
};

// Example usage (ensure contract and userAddress are defined)
yourFirstWriteFunction(contract, '0xUserWalletAddress');

// Analogous process for every WRITE function

Explanation:

  • Write Operation: Uses send to execute a transaction that may change the state on the blockchain.

  • User Wallet Address: Necessary to specify which address is executing the transaction.

Conclusion

With this setup, you've created a fully working functionality to interact with your smart contracts from within your app. Remember to test thoroughly before deploying to production. And if you have any questions, please don’t hesitate to reach out to us via developers@onino.io!

Last updated