π Don't have an API Key? Start here before setting up your project!
Viem is a set of modules, which you can use in JavaScript or Typescript, helping you interface with Ethereum or Ethereum Virtual Machine (EVM) chains.
You will use it in this guide, configuring it with your Alchemy API URL, so you can read and write to the blockchain of your choice.
If you're new to viem, check out our 60 minute video diving into it and the viem docs are a great place to start as well!
Let's get started!
-
Node.js
- Required to run JavaScript/TypeScript outside the browser.
- Install Node.js 18 or later (viem requires modern Node features).
- Download from: https://nodejs.org/
-
npm (comes with Node.js)
- Default package manager bundled with Node.
- Automatically installed when you install Node.js.
From your command line, create a new project directory and install Viem:
# Create and enter project directory
mkdir project && cd project
# Initialize a new Node.js project
npm init -y
# Install viem
npm install viemCreate a file named index.js and add the following contents, replacing demo with your Alchemy API Key:
import { createPublicClient, http } from "viem";
import { mainnet } from "viem/chains";
const client = createPublicClient({
chain: mainnet,
transport: http("https://eth-mainnet.g.alchemy.com/v2/demo"),
});
async function getLatestBlockNumber() {
const blockNumber = await client.getBlockNumber();
console.log("Latest block number:", blockNumber);
}
getLatestBlockNumber();You can find the documentation of viem's getBlockNumber which is configured to call out to eth_blockNumber on the Alchemy API.
node index.jsThis should return the latest block number in your console:
The latest block number is 11043912Woo! Congrats! You just wrote your first web3 script using Alchemy and sent your first request to your Alchemy API endpoint π
You can visit your request logs to see the full details of the request come through the API!
So, what's next for you?
- Want to build an application using the latest and greatest web3 login experience? Check out getting started with our wallets.
- Need the industry best APIs to access blockchain data (tokens, transfers, nfts, prices and more)? Jump on over to our data APIs.
- Want to find all the methods available to you on our node API? Check out the documentation here.
- Need to learn more about crypto? We've got you covered at Alchemy University.