What is Ethers.js?

Ethers.js is a JavaScript library that enables developers to interact with the Ethereum blockchain. It provides a simple and intuitive interface for tasks such as sending transactions, interacting with smart contracts, and managing wallets.

Setting Up Your Project

Follow these steps to set up a basic Ethers.js project:

1. Create a New Project Directory

First, create a new directory for your project and navigate into it. You can use the command line for this:

mkdir ethers-project
cd ethers-project

2. Initialize a New Node.js Project

Next, initialize a new Node.js project by running the following command. This will create a package.json file:

npm init -y

3. Install Ethers.js

Now, install Ethers.js using npm with the following command:

npm install ethers

4. Create an HTML File

Create an index.html file in your project directory. This file will serve as the entry point for your application. You can use the following code as a starting point:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ethers.js Basic Project</title>
<script src="https://cdn.jsdelivr.net/npm/ethers@5.7.0/dist/ethers.umd.min.js"></script>
</head>
<body>
<h1>Welcome to Ethers.js</h1>
<button id="connectButton">Connect Wallet</button>
<script>
document.getElementById('connectButton').onclick = async () => {
if (typeof window.ethereum !== 'undefined') {
const provider = new ethers.providers.Web3Provider(window.ethereum);
await window.ethereum.request({ method: 'eth_requestAccounts' });
const signer = provider.getSigner();
const address = await signer.getAddress();
console.log('Connected:', address);
alert('Connected: ' + address);
} else {
alert('Please install MetaMask!');
}
};
</script>
</body>
</html>

5. Run a Local Server

To view your project in a browser, you’ll need to serve it over a local server. You can use a simple server like http-server. First, install it globally if you haven't already:

npm install -g http-server

Then, run the server in your project directory:

http-server

Open your web browser and navigate to http://localhost:8080 (or the port displayed in your terminal).

Conclusion

You have now set up a basic Ethers.js project! This project allows you to connect to an Ethereum wallet using MetaMask and retrieve the connected wallet address. From here, you can expand your project by adding more functionalities such as sending transactions, interacting with smart contracts, and more.