Create a simple web3 app to connect and sign with your wallet in 7 minutes
Tags: web3, javascript, tutorial, ethereum
Published: 2023-04-05 09:54:39

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](https://zhljt9.csb.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](https://codesandbox.io/) 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zfvj2bypixezd742krho.png)

## Step 2: Modify the HTML file
In the CodeSandbox editor, open the `index.html` file and replace its contents with the following code:

```html
<!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>
```

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:

```javascript
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);
```

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/talarkk0wi95o0841mug.png)

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
* [Final CodeSandbox project](https://codesandbox.io/s/simple-web3-connect-and-sign-project-zhljt9)
* [Live demo](https://zhljt9.csb.app/)
* [web3js's docs](https://web3js.readthedocs.io/en/v1.8.2/getting-started.html)

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 😎