Don't have an API key?
Build faster with production-ready APIs, smart wallets and rollup infrastructure across 70+ chains. Create your free Alchemy API key and get started today.
Let's use the viem package to create an Ethereum client connected to Alchemy and fetch the latest block number!
npm install --save viemimport { createPublicClient, http } from "viem";
import { mainnet } from "viem/chains";
const client = createPublicClient({
chain: mainnet,
transport: http("https://polygon-mainnet.g.alchemy.com/v2/YOUR_ALCHEMY_API_KEY"),
});Now that you've created a client connected to Alchemy, you can continue with some basics:
const blockNumber = await client.getBlockNumber();
console.log("Current block number:", blockNumber);const balance = await client.getBalance({ address: "0xab5801a7d398351b8be11c439e05c5b3259aec9b" });
console.log("Balance (ETH):", Number(balance) / 1e18);const block = await client.getBlock({
blockNumber: blockNumber, // from previous example
});
console.log(block);const tx = await client.getTransaction({ hash: "0xYOUR_TX_HASH" });
console.log(tx);const receipt = await client.getTransactionReceipt({
hash: "0xYOUR_TX_HASH"
});
console.log(receipt);Want to build your first Dapp on Polygon and use Polygon APIs?
Check out the following tutorials to learn how to build on Polygon:
For full documentation on Web3 libraries, check out the official documentation:
- Viem Documentation - Modern TypeScript interface for Ethereum
- Ethers.js Documentation - Complete Ethereum wallet implementation