Signing Transactions with Web3.js Using Metamask: A Step-by-Step Guide
As a developer building blockchain applications, you are probably familiar with the concept of interacting with the blockchain. However, programmatically executing transactions from a web application can be a challenge. In this article, we will walk you through signing transactions with Web3.js and injecting Metamask functionality into your browser to facilitate secure transaction execution.
Prerequisites
Before continuing, make sure that:
- You have basic knowledge of JavaScript, HTML, and CSS.
- You have installed Node.js and npm (a package manager for Node.js) on your system.
- You have set up a blockchain project, including a contract execution and a backend server.
Step 1: Configure Metamask
Metamask is a browser extension that allows users to manage digital assets, including private keys and wallet addresses. To use Metamask with Web3.js, you need to:
- Install the MetaMask browser extension.
- Create an account with MetaMask by providing your email address and creating a password.
- Enable the Web3 extension in your browser settings.
Step 2: Configure Web3.js
Web3.js is a popular JavaScript library for interacting with the Ethereum blockchain. To use it, you need to:
- Install Node.js and npm (as mentioned earlier).
- Create a new Node.js project using
npm init
.
- Initialize your project by running
npm install web3
in your terminal.
- Import the Web3.js file into your application:
const Web3 = require('web3')
.
Step 3: Introduce Metamask functionality into your browser
To implement Metamask functionality into your browser, you need to:
- Create a new file called
index.html
and add the following code:
Metamask Signing Transaction body {
font-family: Arial, sans-serif;
}
Sign the transaction using Metamask in Web3.js
In this code we use the web3.min.js
file from the CDN to import Web3.js.
Step 4: Create a script.js file
Create a new file called script.js
and add the following code:
const Web3 = require('web3');
const web3 = new Web3(window.ethereum);
document.getElementById('web3').addEventListener('input', (e) => {
const privateKey = e.target.value;
web3.eth account.add(privateKey).then((account) => {
document.getElementById('transaction-response').innerHTML = Transaction signed by account: ${account.address}
;
});
});
document.getElementById('sign-transaction').addEventListener('click', async () => {
try {
const signature = wait for web3.eth.signTransaction({
from: '0x...account_address...', // Replace with your account address
data: '', // Data to sign (e.g. txHash, contract methods)
gasPrice: 20, // Gas price for transaction
});
const transactionResponse = wait for web3.eth.sendSignedTransaction(signature.rawTransaction);
document.getElementById('transaction-response').innerHTML = Transaction signed and sent to blockchain!
;
} catch (error) {
console.error(error);
}
});
In this code, we use Web3.js to create a new Ethereum account using the user's private key.