What is Ethers.js?

Ethers.js is a JavaScript library that allows 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.

Creating a New Wallet

You can create a new wallet using Ethers.js by generating a random mnemonic phrase or by directly creating a wallet with a private key. Here, we will focus on creating a wallet using a mnemonic phrase, which is a more user-friendly approach.

1. Set Up Your Project

If you haven't set up an Ethers.js project yet, you can follow these steps:

mkdir ethers-wallet-project
cd ethers-wallet-project
npm init -y
npm install ethers

2. Create an HTML File

Create an index.html file in your project directory. 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>Create Wallet with Ethers.js</title>
<script src="https://cdn.jsdelivr.net/npm/ethers@5.7.0/dist/ethers.umd.min.js"></script>
</head>
<body>
<h1>Create a New Wallet</h1>
<button id="createWalletButton">Create Wallet</button>
<pre id="walletInfo"></pre>
<script>
document.getElementById('createWalletButton').onclick = async () => {
// Generate a random wallet
const wallet = ethers.Wallet.createRandom();

// Display the wallet address and mnemonic
document.getElementById('walletInfo').innerText =
'Address: ' + wallet.address + '\\n' +
'Mnemonic: ' + wallet.mnemonic.phrase;
};
</script>
</body>
</html>

3. 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).

How It Works

In the provided code, when you click the "Create Wallet" button, the following happens:

  • A new wallet is generated using ethers.Wallet.createRandom().
  • The wallet's address and mnemonic phrase are displayed on the page.
  • The mnemonic phrase is crucial for recovering the wallet, so make sure to store it securely.

Conclusion

You have successfully created a new wallet using Ethers.js! This wallet can be used to send and receive Ethereum, as well as interact with smart contracts. Remember to keep your mnemonic phrase safe, as it is the key to accessing your wallet.