Examples Using the Alchemy SDK

Real-world examples on how to query information from the blockchain using the most powerful Web3 SDK.

If you’re looking to start using the Alchemy SDK, but want some plug-and-play examples on how to get started with common use cases, here’s the place to start! We’ll walk you through setting up the Alchemy SDK and a variety of basic tasks you can do.

Setting up the Alchemy SDK

This guide assumes you already have an Alchemy account and access to our Dashboard.

1. Create an Alchemy Key

To access Alchemy’s free node infrastructure, you need an API key to authenticate your requests.

You can create API keys from the dashboard. Check out this video on how to create an app:

Or follow the written steps below:

First, navigate to the “create app” button in the “Apps” tab.

3584

Fill in the details under “Create App” to get your new key. You can also see apps you previously made and those made by your team here. Pull existing keys by clicking on “View Key” for any app.

You can also pull existing API keys by hovering over “Apps” and selecting one. You can “View Key” here, as well as “Edit App” to whitelist specific domains, see several developer tools, and view analytics.

2. Install and set up the Alchemy SDK

To install the Alchemy SDK, you want to create a project, and then navigate to your project directory to run the installation. Let’s go ahead and do that! Once we’re in our home directory, let’s execute the following:

With NPM:

NPM
$mkdir your-project-name
>cd your-project-name
>npm init # (or npm init --yes)
>npm install alchemy-sdk

Next, create a file named index.js and add the following contents:

You should ultimately replace demo with your Alchemy HTTP API key.

index.js
1// Setup: npm install alchemy-sdk
2const { Network, Alchemy } = require("alchemy-sdk");
3
4// Optional Config object, but defaults to demo api-key and eth-mainnet.
5const settings = {
6 apiKey: "demo", // Replace with your Alchemy API Key.
7 network: Network.ETH_MAINNET, // Replace with your network.
8};
9
10const alchemy = new Alchemy(settings);
11
12async function main() {
13 const latestBlock = await alchemy.core.getBlockNumber();
14 console.log("The latest block number is", latestBlock);
15}
16
17main();

Unfamiliar with the async stuff? Check out this Medium post.

3. Run your dApp using Node

shell
$node index.js

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

shell
$The latest block number is 11043912

4. Import SDK Utils (Optional)

Optionally, you can import SDK utils to perform certain operations, such as parsing ETH to Wei as shown in the example below:

javascript
1const { Network, Alchemy, Utils } = require("alchemy-sdk");
2
3const settings = {
4 apiKey: "demo", // Replace with your API key
5 network: Network.ETH_MAINNET, // Replace with your Network
6};
7
8const alchemy = new Alchemy(settings);
9
10async function main() {
11 const gasEstimate = await alchemy.core.estimateGas({
12 to: "vitalik.eth",
13 // parsing 1 ETH to wei using Utils
14 value: Utils.parseEther("1.0"),
15 });
16 console.log(gasEstimate);
17}
18
19main();

Below, we’ll list a number of examples on how to make common requests on Ethereum or EVM blockchains.

SDK Core Endpoint Examples

How to Get the Latest Block Number on Ethereum

A block is generated on Ethereum approximately every 15 seconds. If you’re looking for the latest block, you can plug in the following:

typescript
1async function main() {
2 const latestBlock = await alchemy.core.getBlockNumber();
3 console.log("The latest block number is", latestBlock);
4}
5
6main();

How to Get a Block By Its Block Hash on Ethereum

Every block on Ethereum correspond to a specific hash. If you’d like to look up a block by its hash, you can plug in the following code:

typescript
1async function main() {
2 const block = await alchemy.core.getBlock(
3 "0x92fc42b9642023f2ee2e88094df80ce87e15d91afa812fef383e6e5cd96e2ed3"
4 );
5 console.log(block);
6}
7
8main();

How to Get a Block By Its Block Number on Ethereum

Every block on Ethereum correspond to a specific number. If you’d like to look up a block by its number, you can plug in the following code:

typescript
1async function main() {
2 const block = await alchemy.core.getBlock(15221026);
3 console.log(block);
4}
5
6main();

How to Get Logs for an Ethereum Transaction

Logs are essentially a published list of user-defined events that have happened on the blockchain during an Ethereum transaction. You can learn more about them in Understanding Logs: Deep Dive into eth_getLogs.

Here’s an example on how to write a getLogs query on Ethereum:

typescript
1async function main() {
2 const getLogs = await alchemy.core.getLogs({
3 address: "0xdAC17F958D2ee523a2206206994597C13D831ec7",
4 topics: [
5 "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",
6 ],
7 blockHash:
8 "0x49664d1de6b3915d7e6fa297ff4b3d1c5328b8ecf2ff0eefb912a4dc5f6ad4a0",
9 });
10 console.log(getLogs);
11}
12
13main();

How to Make an Eth_Call on Ethereum

An eth_call in Ethereum is essentially a way to execute a message call immediately without creating a transaction on the block chain. It can be used to query internal contract state, to execute validations coded into a contract or even to test what the effect of a transaction would be without running it live.

Here’s an example on how to write a call query on Ethereum:

typescript
1async function main() {
2 const call = await alchemy.core.call({
3 to: "0x4976fb03C32e5B8cfe2b6cCB31c09Ba78EBaBa41",
4 gas: "0x76c0",
5 gasPrice: "0x9184e72a000",
6 data: "0x3b3b57debf074faa138b72c65adbdcfb329847e4f2c04bde7f7dd7fcad5a52d2f395a558",
7 });
8 console.log(call);
9}
10
11main();

How to Get a Transaction by Its Hash on Ethereum

Every transaction on Ethereum correspond to a specific hash. If you’d like to look up a transaction by its hash, you can plug in the following code:

typescript
1async function main() {
2 const tx = await alchemy.core.getTransaction(
3 "0x88df016429689c079f3b2f6ad39fa052532c56795b733da78a91ebe6a713944b"
4 );
5 console.log(tx);
6}
7
8main();

How to Get a Transaction Receipt on Ethereum

Every transaction on Ethereum has an associated receipt with metadata about the transaction, such as the gas used and logs printed during the transaction. If you’d like to look up a transaction’s receipt, you can plug in the following code:

typescript
1async function main() {
2 const txReceipt = await alchemy.core.getTransactionReceipt(
3 "0x88df016429689c079f3b2f6ad39fa052532c56795b733da78a91ebe6a713944b"
4 );
5 console.log(txReceipt);
6}
7
8main();

How to get a User’s Transaction Count on Ethereum

The number of transactions a user has sent is particularly important when it comes to calculating the nonce for sending new transactions on Ethereum. Without it, you’ll be unable to send new transactions because your nonce won’t be set correctly.

typescript
1async function main() {
2 const txCount = await alchemy.core.getTransactionCount(
3 "0x4976fb03C32e5B8cfe2b6cCB31c09Ba78EBaBa41"
4 );
5 console.log(txCount);
6}
7
8main();

How to Fetch Historical Transactions on Ethereum

Oftentimes, you’ll want to look up a set of transactions on Ethereum between a set of blocks, corresponding to a set of token types such as ERC20 or ERC721, or with certain attributes. Alchemy’s proprietary Transfers API allows you to do so in milliseconds, rather than searching every block on the blockchain.

typescript
1async function main() {
2 const getTransfers = alchemy.core.getAssetTransfers({
3 fromBlock: "0x0",
4 toBlock: "latest",
5 toAddress: ["vitalik.eth"],
6 excludeZeroValue: true,
7 category: ["erc721"],
8 });
9 console.log(getTransfers);
10}
11
12main();

How to Estimate the Gas of a Transaction on Ethereum

Oftentimes, you’ll need to calculate how much gas a particular transaction will use on the blockchain to understand the maximum amount that you’ll pay on that transaction. This example will return the gas used by the specified transaction:

typescript
1async function main() {
2 const gasEstimate = await alchemy.core.estimateGas({
3 // ETH address
4 to: "vitalik.eth",
5 // 1 ether
6 value: Utils.parseEther("1.0"),
7 });
8 console.log(gasEstimate);
9}
10
11main();

How to Get the Current Gas Price in Ethereum

You can retrieve the current gas price in wei using this method:

typescript
1async function main() {
2 const gasPrice = await alchemy.core.getGasPrice();
3 console.log(gasPrice);
4}
5
6main();

SDK Websocket Examples

How to Subscribe to New Blocks on Ethereum

If you’d like to open a WebSocket subscription to send you a JSON object whenever a new block is published to the blockchain, you can set one up using the following syntax.

typescript
1// Subscription for new blocks on Eth Mainnet.
2alchemy.ws.on("block", (blockNumber) =>
3 console.log("The latest block number is", blockNumber)
4);

How to Subscribe to Pending Transactions on Ethereum

Alchemy exposes a proprietary WebSockets endpoint pendingTransactions that allows you to receive a JSON object whenever a pending transaction matching a set of requirements is submitted or confirmed on the blockchain.

In the following example, you can receive a JSON object whenever a pending transaction is submitted with the recipient as Vitalik Buterin’s contract address.

typescript
1// Subscription for Alchemy's pendingTransactions Enhanced API
2alchemy.ws.on(
3 {
4 method: "alchemy_pendingTransactions",
5 toAddress: "vitalik.eth",
6 },
7 (tx) => console.log(tx)
8);

SDK NFT API Examples

How to Check the Owner of an NFT

If you’d like to identify which contract address currently owns a specific NFT, you can use Alchemy’s proprietary NFT API to search the blockchain. See the example below:

typescript
1async function main() {
2 // TIMEPieces contract address
3 const address = "0xDd69da9a83ceDc730bc4d3C56E96D29Acc05eCDE";
4
5 // Safe Haven Token ID
6 const tokenId = 4254;
7
8 // Get owner of NFT
9 const owner = await alchemy.nft.getOwnersForNft(address, tokenId);
10 console.log(owner);
11}
12
13main();

How to get All NFTs in a Collection

If you’d like to print the metadata of all the NFTs in a specific collection, you can use Alchemy’s proprietary NFT API to search the blockchain. See the example below:

typescript
1async function main() {
2 // Contract address
3 const address = "0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D";
4
5 // Flag to omit metadata
6 const omitMetadata = false;
7
8 // Get all NFTs
9 const { nfts } = await alchemy.nft.getNftsForContract(address, {
10 omitMetadata: omitMetadata,
11 });
12
13 let i = 1;
14
15 for (let nft of nfts) {
16 console.log(`${i}. ${nft.rawMetadata.image}`);
17 i++;
18 }
19}
20
21main();

How to Get All NFTs Owned by an Address

If you’d like to retrieve all the NFTs owned by a specific user address, you can use Alchemy’s proprietary NFT API to search the blockchain. See these example below:

typescript
1async function main() {
2 // Get all NFTs
3 const nfts = await alchemy.nft.getNftsForOwner("elanhalpern.eth");
4 // Print NFTs
5 console.log(nfts);
6}
7
8main();

SDK Transact Examples

How to Send a Transaction to the Blockchain

One of the most common requests is sending a transaction to be mined onto the blockchain. Here’s some example code showing you how to make a transaction from scratch, sign it, and send it to be confirmed.

typescript
1import { Network, Alchemy, Wallet, Utils } from "alchemy-sdk";
2import dotenv from "dotenv";
3dotenv.config();
4
5const { API_KEY, PRIVATE_KEY } = process.env;
6
7const settings = {
8 apiKey: API_KEY,
9 network: Network.ETH_GOERLI, // Replace with your network.
10};
11
12const alchemy = new Alchemy(settings);
13const wallet = new Wallet(PRIVATE_KEY);
14
15const transaction = {
16 to: "0xa238b6008Bc2FBd9E386A5d4784511980cE504Cd",
17 value: Utils.parseEther("0.001"),
18 gasLimit: "21000",
19 maxPriorityFeePerGas: Utils.parseUnits("5", "gwei"),
20 maxFeePerGas: Utils.parseUnits("20", "gwei"),
21 nonce: await alchemy.core.getTransactionCount(wallet.getAddress()),
22 type: 2,
23 chainId: 5, // Corresponds to ETH_GOERLI
24};
25
26const rawTransaction = await wallet.signTransaction(transaction);
27await alchemy.transact.sendTransaction(rawTransaction);

How to Send a Private Transaction to the Blockchain

If you’re worried about your transactions being front-run on Ethereum, Flashbots has created a tool to allow you to submit transactions without exposing them to the entire blockchain! It provides greater privacy while maintaining all the features of sendTransaction.

typescript
1import { Network, Alchemy, Wallet, Utils } from "alchemy-sdk";
2import dotenv from "dotenv";
3dotenv.config();
4
5const { API_KEY, PRIVATE_KEY } = process.env;
6
7const settings = {
8 apiKey: API_KEY,
9 network: Network.ETH_MAINNET, // Replace with your network.
10};
11
12const alchemy = new Alchemy(settings);
13const wallet = new Wallet(PRIVATE_KEY);
14
15const transaction = {
16 to: "0xa238b6008Bc2FBd9E386A5d4784511980cE504Cd",
17 value: Utils.parseEther("0.001"),
18 gasLimit: "21000",
19 maxPriorityFeePerGas: Utils.parseUnits("5", "gwei"),
20 maxFeePerGas: Utils.parseUnits("20", "gwei"),
21 nonce: await alchemy.core.getTransactionCount(wallet.getAddress()),
22 type: 2,
23 chainId: 1, // Corresponds to ETH_MAINNET
24};
25
26const rawTransaction = await wallet.signTransaction(transaction);
27alchemy.transact.sendPrivateTransaction(rawTransaction).then(console.log);

SDK Notify Examples

How to Create an Alchemy Notify Webhook

If you’d like to set up a Webhook to alert you when a pending transaction is submitted, mined, or when activity happens on an NFT address, we have a simple CRUD API that lets you create, update, and delete our Notify Webhooks programmatically.

typescript
1// Setup: npm install alchemy-sdk
2// Github: https://github.com/alchemyplatform/alchemy-sdk-js
3import { Alchemy, Network, WebhookType } from "alchemy-sdk";
4
5// authToken is required to use Notify APIs. Found on the top right corner of
6// https://dashboard.alchemy.com/notify.
7const settings = {
8 authToken: "your-notify-auth-token",
9 network: Network.ETH_MAINNET, // Replace with your network.
10};
11
12const alchemy = new Alchemy(settings);
13
14const minedTxWebhook = await alchemy.notify.createWebhook(
15 "https://webhook.site/your-webhook-url",
16 WebhookType.MINED_TRANSACTION,
17 { appId: "wq9fgv022aff81pg" }
18);
19
20const droppedTxWebhook = await alchemy.notify.createWebhook(
21 "https://webhook.site/your-webhook-url",
22 WebhookType.DROPPED_TRANSACTION,
23 { appId: "wq9fgv022aff81pg" }
24);
25
26const addressActivityWebhook = await alchemy.notify.createWebhook(
27 "https://webhook.site/your-webhook-url",
28 WebhookType.ADDRESS_ACTIVITY,
29 {
30 addresses: ["0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96010"],
31 network: Network.ETH_MAINNET,
32 }
33);
34
35const nftActivityWebhook = await alchemy.notify.createWebhook(
36 "https://webhook.site/your-webhook-url",
37 WebhookType.NFT_ACTIVITY,
38 {
39 filters: [
40 {
41 contractAddress: "0x88b48f654c30e99bc2e4a1559b4dcf1ad93fa656",
42 tokenId: "234",
43 },
44 ],
45 network: Network.ETH_MAINNET,
46 }
47);