0
0
BlockchainHow-ToBeginner ยท 4 min read

How to Connect Frontend to Smart Contract in Solidity

To connect a frontend to a smart contract, use a JavaScript library like Web3.js or Ethers.js to interact with the blockchain. Load the contract's ABI and address in your frontend, then call contract methods through the library connected to a provider like MetaMask.
๐Ÿ“

Syntax

Connecting a frontend to a smart contract involves these parts:

  • Provider: Connects your app to the blockchain (e.g., MetaMask).
  • ABI (Application Binary Interface): Describes the contract's functions and events.
  • Contract Address: The deployed contract's location on the blockchain.
  • Library Instance: Using Web3.js or Ethers.js to create a contract object.
javascript
import { ethers } from 'ethers';

const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
const contractAddress = '0xYourContractAddress';
const contractABI = [ /* ABI array here */ ];

const contract = new ethers.Contract(contractAddress, contractABI, signer);
๐Ÿ’ป

Example

This example shows how to connect a frontend to a smart contract using Ethers.js, request user permission with MetaMask, and call a simple contract method.

javascript
import { ethers } from 'ethers';

async function connectContract() {
  if (!window.ethereum) {
    alert('MetaMask is required to connect');
    return;
  }

  await window.ethereum.request({ method: 'eth_requestAccounts' });
  const provider = new ethers.providers.Web3Provider(window.ethereum);
  const signer = provider.getSigner();

  const contractAddress = '0x1234567890abcdef1234567890abcdef12345678';
  const contractABI = [
    "function getValue() view returns (uint256)",
    "function setValue(uint256 newValue)"
  ];

  const contract = new ethers.Contract(contractAddress, contractABI, signer);

  // Call a read-only function
  const value = await contract.getValue();
  console.log('Current value:', value.toString());

  // Call a state-changing function
  const tx = await contract.setValue(42);
  await tx.wait();
  console.log('Value updated to 42');
}

connectContract();
Output
Current value: 0 Value updated to 42
โš ๏ธ

Common Pitfalls

  • Not requesting user accounts: Forgetting eth_requestAccounts causes no access to wallet.
  • Wrong contract address or ABI: Leads to errors or no interaction.
  • Not handling asynchronous calls: Contract calls return promises; use await.
  • Not waiting for transactions: State changes need confirmation with tx.wait().
javascript
/* Wrong way: Missing account request */
const provider = new ethers.providers.Web3Provider(window.ethereum);
await window.ethereum.request({ method: 'eth_requestAccounts' });
const signer = provider.getSigner();
const contract = new ethers.Contract(address, abi, signer);
// This may fail if user did not approve access

/* Right way: Request accounts first */
await window.ethereum.request({ method: 'eth_requestAccounts' });
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
const contract = new ethers.Contract(address, abi, signer);
๐Ÿ“Š

Quick Reference

  • Provider: Connects frontend to blockchain (MetaMask, Infura).
  • ABI: Contract interface needed to call functions.
  • Contract Address: Unique location of deployed contract.
  • Signer: Represents user wallet to sign transactions.
  • Read-only calls: Use call or direct function calls.
  • State-changing calls: Send transactions and wait for confirmation.
โœ…

Key Takeaways

Use a provider like MetaMask to connect your frontend to the blockchain.
Load the contract's ABI and address to create a contract instance with Web3.js or Ethers.js.
Always request user permission to access their wallet before interacting.
Handle asynchronous calls with await and wait for transaction confirmations.
Verify contract address and ABI to avoid connection errors.