Web3.js

How do I use Web3js with a secure wallet


Web3.js is a powerful JavaScript library that allows developers to interact with the Ethereum blockchain. When working with Web3.js, it's crucial to use a secure wallet to protect your private keys and manage your assets. This guide will explain how to use Web3.js with a secure wallet, such as MetaMask, and provide sample code to demonstrate the integration.

1. Prerequisites

  • Basic understanding of JavaScript and Ethereum.
  • Node.js installed on your machine.
  • A browser with MetaMask installed or another secure wallet.

2. Setting Up Your Project

First, create a new directory for your project and initialize it:

mkdir web3-secure-wallet
cd web3-secure-wallet
npm init -y
npm install web3

3. Create an HTML File

Create an index.html file in your project directory. This file will serve as the frontend for interacting with the Ethereum blockchain:

<!doctype html>
<html lang=`en`>
  <head>
    <meta charset=`UTF-8`>
    <meta name=`viewport` content=`width=device-width, initial-scale=1.0`>
    <title>Web3.js with Secure Wallet</title>
    <script src=`https://cdn.jsdelivr.net/npm/web3/dist/web3.min.js`></script>
  </head>
  <body>
    <h1>Connect to Ethereum Wallet</h1>
    <button id=`connect-button`>Connect Wallet</button>
    <div id=`wallet-info`></div>
    <script src=`app.js`></script>
  </body>
</html>

4. Create the JavaScript File

Create an app.js file in your project directory. This file will handle the connection to the Ethereum wallet and interact with Web3.js:

const connectButton = document.getElementById('connect-button');
const walletInfo = document.getElementById('wallet-info');
async function connectWallet() {
    if (typeof window.ethereum !== 'undefined') {
        try {
            // Request account access
            const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
            const account = accounts[0];
            walletInfo.innerHTML = `Connected: ${account}`;
            const web3 = new Web3(window.ethereum);
            // Now you can use web3 to interact with the Ethereum blockchain
            console.log(web3);
        } catch (error) {
            console.error('User  denied account access or error occurred:', error);
        }
    } else {
        walletInfo.innerHTML = 'Please install MetaMask!';
    }
}
connectButton.addEventListener('click', connectWallet);

5. Running the Application

To run your application, you can use a local server. If you have Python installed, you can run:

python -m http.server 8000

Then open your browser and navigate to http://localhost:8000. Click the `Connect Wallet` button to connect to your MetaMask wallet.

6. Interacting with Smart Contracts

Once connected, you can interact with smart contracts. Here’s an example of how to send a transaction:

async function sendTransaction() {
    const web3 = new Web3(window.ethereum);
    const accounts = await web3.eth.getAccounts();
    const tx = {
        from: accounts[0],
        to: '0xRecipientAddress', // Replace with the recipient address
        value: web3.utils.toWei('0.01', 'ether'),
        gas: 2000000,
    };
    try {
        const receipt = await web3.eth.sendTransaction(tx);
        console.log('Transaction receipt:', receipt);
    } catch (error) {
        console.error('Transaction failed:', error);
    }
}

7. Conclusion

Using Web3.js with a secure wallet like MetaMask allows you to interact with the Ethereum blockchain safely. By following the steps outlined in this guide, you can connect to a wallet

Written by Surfside Media

Senior Full Stack Developer specializing in Web Technologies.