πŸ‘·
Simple Web3 Script
Don't know where to start? This guide will walk you through writing a simple web3 script to get the latest block number from the Ethereum mainnet using Alchemy.
This guide assumes you've gone through the getting started steps and have an Alchemy account!​

1. From your command line, create a new project directory and cd into it:

1
mkdir web3-example
2
cd web3-example
Copied!

2. Install the Alchemy Web3 dependency if you have not already:

You can use any web3 library of your choosing, however there are tons of benefits to using Alchemy Web3!
1
npm install @alch/alchemy-web3
Copied!

3. Create a file named index.js and add the following contents:

You should ultimately replace <api-key> with your Alchemy HTTP API key.
1
async function main() {
2
const { createAlchemyWeb3 } = require("@alch/alchemy-web3");
3
const web3 = createAlchemyWeb3("https://eth-mainnet.alchemyapi.io/<api-key>");
4
const blockNumber = await web3.eth.getBlockNumber();
5
console.log("The latest block number is " + blockNumber);
6
}
7
main();
Copied!
Unfamiliar with the async stuff? Check out this Medium post.

4. Run it using node

1
node index.js
Copied!

5. You should now see the latest block number output in your console!

1
The latest block number is 11043912
Copied!
Woo! Congrats! You just wrote your first web3 script using Alchemy
πŸŽ‰
Once you complete this tutorial, let us know how your experience was or if you have any feedback by tagging us on Twitter @alchemyplatform!
Not sure what to do next? Build upon your skills learned in this tutorial by checking out our beginner's tutorial for sending Ethereum transactions using Web3 and Alchemy.
Last modified 1mo ago