DEV Community

Cover image for Create a simple web3 app to connect and sign with your wallet in 7 minutes
Alex Kubica ๐Ÿ‡ฎ๐Ÿ‡ฑ
Alex Kubica ๐Ÿ‡ฎ๐Ÿ‡ฑ

Posted on

Create a simple web3 app to connect and sign with your wallet in 7 minutes

Are you ready to learn how to connect to a wallet and sign a message using Web3.js and MetaMask? ๐Ÿคฉ This step-by-step guide will show you how to get started with these powerful tools to create this web3 app.

With just a few lines of code, you'll be able to connect to a wallet and sign a message in no time! ๐Ÿ˜Ž And don't worry if you're new to Web3.js and MetaMask, we've got you covered with detailed explanations and easy-to-follow instructions.

Step 1: Create a new CodeSandbox project

Go to CodeSandbox and create a new project by clicking the "Create Sandbox" button. Choose the "Vanilla" template to create a new sandbox with a basic HTML, CSS, and JavaScript setup.
You should install the web3 dependency which we will use in the next step.

Image description

Step 2: Modify the HTML file

In the CodeSandbox editor, open the index.html file and replace its contents with the following code:



<!DOCTYPE html>
<html>
  <head>
    <title>Wallet Connection Example</title>
    <meta charset="UTF-8">
  </head>
  <body>
    <h1>Wallet Connection Example</h1>
    <button id="connectBtn">Connect Wallet</button>
    <button id="signBtn" disabled>Sign Message</button>
    <div id="confirmation"></div>

    <script src="./src/index.js"></script>
  </body>
</html>


Enter fullscreen mode Exit fullscreen mode

This code defines a basic HTML page with two buttons and a div to display the signed message confirmation. We've also included a script tag to load our JavaScript code, which we'll write in the next step.

Step 3: Modify the JavaScript file

Now Open the src/index.js file and replace its contents with the following code:



import Web3 from 'web3';

const connectBtn = document.getElementById('connectBtn');
const signBtn = document.getElementById('signBtn');
const confirmationDiv = document.getElementById('confirmation');

// Check if MetaMask is installed
if (typeof window.ethereum === 'undefined') {
  connectBtn.innerText = 'Install MetaMask';
  connectBtn.disabled = true;
}

// Connect to the wallet
let web3;
async function connectWallet() {
  try {
    // Prompt user to connect to MetaMask
    await window.ethereum.request({ method: 'eth_requestAccounts' });
    // Get the provider object
    web3 = new Web3(window.ethereum);
    // Update button text
    connectBtn.innerText = 'Logout';
    // Enable sign button
    signBtn.disabled = false;
  } catch (error) {
    console.error(error);
  }
}
connectBtn.addEventListener('click', connectWallet);

// Sign a message
async function signMessage() {
  try {
    // Get the current account
    const accounts = await web3.eth.getAccounts();
    const account = accounts[0];
    // Create a message to sign
    const message = 'Hello, world!';
    // Sign the message
    const signature = await web3.eth.personal.sign(message, account);
    // Display the signature in the confirmation div
    confirmationDiv.innerText = `Signed message: ${signature}`;
  } catch (error) {
    console.error(error);
  }
}
signBtn.addEventListener('click', signMessage);


Enter fullscreen mode Exit fullscreen mode

This code uses the import statement to import the Web3 library from the web3 package. It defines three variables to reference the two buttons and the confirmation div in our HTML code. We also check if MetaMask is installed and display a message if it is not.

The connectWallet function uses the window.ethereum object to prompt the user to connect to MetaMask and authorize the connection. It then initializes the web3 object with the provider returned by MetaMask and updates the button text and disabled status.

The signMessage function gets the current account from MetaMask, creates a message to sign, and uses the web3.eth.personal.sign method to sign the message with the current account. It then displays the signed message confirmation in the div below the Sign Message button.

Finally, we add event listeners to the Connect Wallet and Sign Message buttons to call the connectWallet and signMessage functions, respectively, when they are clicked.

Step 4: Preview the HTML file in the browser

Image description

To test our code, click the "Preview" button at the top of the CodeSandbox editor to open a new tab with the preview of the HTML page. Click the Connect Wallet button to connect to MetaMask and authorize the connection. Once connected, the Sign Message button will be enabled. Click it to sign the "Hello, world!" message and display the signed message confirmation.

Congratulations, you've successfully connected to a wallet and signed a message using Web3.js and MetaMask in CodeSandbox!

Resources

That's a wrap! If you liked this tutorial let me know in the comments and tell me what you'd like to learn next ๐Ÿ˜Ž

Top comments (1)

Collapse
 
idodav profile image
Ido David

Do a threejs tutrial next!