What is Ethers.js?

Ethers.js is a library that allows developers to interact with the Ethereum blockchain and its ecosystem. It provides a simple and complete API for working with Ethereum, including smart contracts, wallets, and transactions.

Why Use TypeScript with Ethers.js?

TypeScript is a superset of JavaScript that adds static typing. Using TypeScript with Ethers.js offers several benefits:

  • Improved code quality through type checking.
  • Better developer experience with autocompletion and documentation.
  • Enhanced maintainability of codebases.

Setting Up Your Project

To use Ethers.js with TypeScript, follow these steps:

  1. Initialize a new Node.js project:
  2. npm init -y
  3. Install TypeScript and Ethers.js:
  4. npm install typescript ethers
  5. Initialize TypeScript configuration:
  6. npx tsc --init

Sample Code to Use Ethers.js with TypeScript

Below is an example demonstrating how to use Ethers.js in a TypeScript file:

import { ethers } from "ethers";

// Connect to the Ethereum network (default to mainnet)
const provider = new ethers.providers.getDefaultProvider();

async function getBlockNumber() {
try {
const blockNumber = await provider.getBlockNumber();
console.log("Current Block Number:", blockNumber);
} catch (error) {
console.error("Error:", error);
}
}

// Call the function
getBlockNumber();

Integrating with HTML

To integrate this TypeScript code into an HTML document, you can compile the TypeScript code to JavaScript and include it in your HTML file:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ethers.js with TypeScript Example</title>
<script src="https://cdn.jsdelivr.net/npm/ethers@5.7.0/dist/ethers.umd.min.js"></script>
<script src="path/to/your/compiled.js"></script>
</head>
<body>
<h1>Ethers.js with TypeScript</h1>
<button id="getBlockNumberButton">Get Current Block Number</button>
<pre id="blockNumberOutput"></pre>

<script>
document.getElementById('getBlockNumberButton').onclick = async function() {
await getBlockNumber(); // Call the function from your TypeScript code
};
</script>
</body>
</html>

Conclusion

Using Ethers.js with TypeScript enhances your development experience by providing type safety and better tooling. By following the steps outlined above, you can easily set up your project and start interacting with the Ethereum blockchain.