Alchemy SDK Surface Overview

An in-depth look at the APIs available in the Alchemy SDK and how it differs from Ethers.js.

📘

Alchemy SDK Quickstart

If you'd like to start writing code immediately with the SDK, go here!

The Alchemy SDK is the most comprehensive, stable, and powerful Javascript SDK available today to interact with the blockchain.

It supports the exact same syntax and functionality of the Ethers.js AlchemyProvider and WebSocketProvider, making it a 1:1 mapping for anyone using the Ethers.js Provider. However, it adds a significant amount of improved functionality on top of Ethers, such as easy access to Alchemy’s Enhanced and NFT APIs, robust WebSockets, and quality-of life improvements such as automated retries.

The SDK currently supports the following chains:

  • Ethereum: Mainnet, Goerli
  • Polygon: Mainnet, Mumbai
  • Optimism: Mainnet, Goerli
  • Arbitrum: Mainnet, Goerli
  • Astar: Mainnet

API Surface

The Alchemy SDK currently supports five different namespaces, including:

  • core: All commonly-used Ethers.js Provider methods and Alchemy Enhanced API methods
  • nft: All Alchemy NFT API methods
  • ws: All WebSockets methods
  • transact: All Alchemy Transaction API methods
  • notify: CRUD endpoints for modifying Alchemy Notify Webhooks

If you are already using Ethers.js, you should be simply able to replace the Ethers.js Provider object with alchemy.core and it should just work.

The Alchemy SDK also supports a number of Ethers.js objects that streamline the development process:

  • Utils: Equivalent to ethers.utils, this provides a number of common Ethers.js utility methods for developers.
    • Interface: Found in Utils.Interface, this class abstracts the encoding and decoding required to interact with contracts on the Ethereum network.
  • Contract: An abstraction for smart contract code deployed to the blockchain.
  • ContractFactory: Allows developers to build a Contract object.
  • Wallet: An implementation of Signer that can sign transactions and messages using a private key as a standard Externally Owned Account.

Alchemy Settings

An AlchemySettings object can be passed on instantiation to the Alchemy object, with the following optional parameters:

  • apiKey: API key that can be found in the Alchemy dashboard. Defaults to demo: a rate-limited public key.
  • network: Name of the network. Defaults to Network.ETH_MAINNET
  • maxRetries: The maximum number of retries to attempt if a request fails. Defaults to 5.
  • url: Optional URL endpoint to use for all requests. Setting this field will override the URL generated by the network andapiKey fields.
  • authToken: Alchemy auth token required to use the Notify API. This token can be found in the Alchemy Dashboard on the Notify tab.
  • batchRequests: Optional setting that automatically batches and sends json-rpc requests for higher throughput and reduced network IO. Defaults to false.

📘

ENS Resolution

The Alchemy SDK now supports ENS names (e.g. vitalik.eth) for every parameter where you can pass in an Externally Owned Address, or user address (e.g. 0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045)

Alchemy Core

The core package contains all commonly-used Ethers.js Provider methods. If you are already using Ethers.js, you should be simply able to replace the Ethers.js Provider object with alchemy.core and it should just work.

It also includes the majority of Alchemy Enhanced APIs, including:

  • getTokenMetadata(): Get the metadata for a token contract address.
  • getTokenBalances(): Gets the token balances for an owner given a list of contracts.
  • getAssetTransfers(): Get transactions for specific addresses.
  • getTransactionReceipts(): Gets all transaction receipts for a given block.

Accessing the full Ethers.js Provider

To keep the package clean, we don't support certain uncommonly-used Ethers.js Provider methods as top-level methods the Alchemy object - for example, provider.formatter. If you'd like to access these methods, simply use the alchemy.config.getProvider() function to configure the Ethers.js AlchemyProvider and return it.

import { Alchemy } from 'alchemy-sdk';
const alchemy = new Alchemy();

async function runAlchemy() {
  const ethersProvider = await alchemy.config.getProvider();
  console.log(ethersProvider.formatter);
}
runAlchemy();

Alchemy WebSockets

In addition to the built-in Ethers.js listeners, the Alchemy SDK includes support for Alchemy's Subscription API . This allows you to subscribe to events and receive updates as they occur.

The alchemy.ws instance can be used can be used like the standard Ethers.js WebSocketProvider to add listeners for Alchemy events:

import { Alchemy } from 'alchemy-sdk';

const alchemy = new Alchemy();

// Listen to all new pending transactions.
alchemy.ws.on(
  {
    method: 'alchemy_pendingTransactions'
  },
  res => console.log(res)
);

// Listen to only the next transaction on the USDC contract.
alchemy.ws.once(
  {
    method: 'alchemy_pendingTransactions',
    toAddress: 'vitalik.eth'
  },
  res => console.log(res)
);

// Remove all listeners.
alchemy.ws.removeAllListeners();

The SDK brings multiple improvements to ensure correct WebSocket behavior in cases of temporary network failure or dropped connections. As with any network connection, you should not assume that a WebSocket will remain open forever without interruption, but correctly handling dropped connections and reconnection by hand can be challenging to get right. alchemy-sdk automatically handles these failures with no configuration necessary.

The main benefits are:

  • Resilient event delivery: Unlike standard Web3.js or Ethers.js, you will not permanently miss events which arrive while the backing WebSocket is temporarily down. Instead, you will receive these events as soon as the connection is reopened. Note that if the connection is down for more than 120 blocks (approximately 20 minutes), you may still miss some events that were not part of the most recent 120 blocks.
  • Lowered rate of failure: Compared to standard Web3.js or Ethers.js, there are fewer failures when sending requests over the WebSocket while the connection is down. Alchemy Web3 will attempt to send the requests once the connection is reopened. Note that it is still possible, with a lower likelihood, for outgoing requests to be lost, so you should still have error handling as with any network request.

Alchemy Transact

The transact namespace contains methods used for sending transactions. The unique methods to the transact namespace are:

  • sendPrivateTransaction(): Send a private transaction through Flashbots.
  • cancelPrivateTransaction(): Cancel a private transaction sent with Flashbots.

The transact namespace also aliases over several commonly used methods from the core namespace for convenience:

  • getTransaction(): Returns the transaction for the given transaction hash.
  • sendTransaction(): Sends a standard transaction to the network to be mined.
  • waitForTransaction(): Waits for a transaction to be mined and returns the transaction receipt.

Alchemy NFT API

The SDK currently supports the following NFT API endpoints under the alchemy.nft namespace:

  • getNftMetadata(): Get the NFT metadata for a contract address and tokenId.
  • getNftMetadataBatch(): Get the NFT metadata for multiple NFT contract addresses/token id pairs.
  • getContractMetadata(): Get the metadata associated with an NFT contract
  • getNftsForOwner(): Get NFTs for an owner address.
  • getNftsForOwnerIterator(): Get NFTs for an owner address as an async iterator (handles paging automatically).
  • getNftsForContract(): Get all NFTs for a contract address.
  • getNftForContractIterator(): Get all NFTs for a contract address as an async iterator (handles paging
    automatically).
  • getOwnersForNft(): Get all the owners for a given NFT contract address and a particular token ID.
  • getOwnersForContract(): Get all the owners for a given NFT contract address.
  • checkNftOwnership(): Check that the provided owner address owns one or more of the provided NFT contract addresses.
  • isSpamContract(): Check whether the given NFT contract address is a spam contract as defined by Alchemy (see the NFT API FAQ)
  • getSpamContracts(): Returns a list of all spam contracts marked by Alchemy.
  • findContractDeployer(): Find the contract deployer and block number for a given NFT contract address.
  • refreshNftMetadata(): Refresh the cached NFT metadata for a contract address and a single tokenId.
  • refreshContract(): Enqueues the specified contract address to have all token ids' metadata refreshed.
  • getFloorPrice(): Return the floor prices of a NFT contract by marketplace.
  • computeRarity(): Get the rarity of each attribute of an NFT.
  • getNftSales(): Returns NFT sales that have happened through on-chain marketplaces.
  • summarizeNftAttributes(): Get the summary of attribute prevalence for all NFTs in a contract.
  • searchContractMetadata(): Search for a keyword across metadata of all ERC-721 and ERC-1155 smart contracts.

Pagination

The Alchemy NFT endpoints return 100 results per page. To get the next page, you can pass in the pageKey returned by the previous call. To simplify paginating through all results, the SDK provides the getNftsIterator() and getNftsForCollectionIterator() functions that automatically paginate through all NFTs and yields them via an AsyncIterable.

Here's an example of how to paginate through all the NFTs in Vitalik's ENS address:

import { Alchemy } from 'alchemy-sdk';

const alchemy = new Alchemy();

async function main() {
  const ownerAddress = 'vitalik.eth';
  for await (const nft of alchemy.nft.getNftsForOwnerIterator(ownerAddress)) {
    console.log('ownedNft:', nft);
  }
}

main();

SDK vs NFT API Differences

The NFT API in the SDK standardizes response types to reduce developer friction, but note this results in some differences compared to the Alchemy REST endpoints:

  • Methods referencing Collection have been renamed to use the name Contract for greater accuracy: e.g. getNftsForContract.
  • Some methods have different naming that the REST API counterparts in order to provide a consistent API interface (
    e.g. getNftsForOwner() is alchemy_getNfts, getOwnersForNft() is alchemy_getOwnersForToken).
  • SDK standardizes to omitMetadata parameter (vs. withMetadata).
  • Standardization to pageKey parameter for pagination (vs. nextToken/startToken)
  • Empty TokenUri fields are omitted.
  • Token ID is always normalized to an integer string on BaseNft and Nft.
  • Some fields omitted in the REST response are included in the SDK response in order to return an Nft object.
  • Some fields in the SDK's Nft object are named differently than the REST response.

Alchemy Notify

The Alchemy Notify API helps developers set up webhooks in their apps. The namespace provides methods to programmatically create, read, update, and delete your webhooks along with typings for the different webhooks. To learn more about Webhooks, please refer to the Alchemy documentation.

Methods on the NotifyNamespace can be accessed via alchemy.notify. To use the methods, you must include your team's auth token in the authToken field of AlchemySettings when instantiating the SDK. The auth token can be found on the Alchemy Dashboard in the Notify Tab.

Methods include:

  • getAllWebhooks(): Get all webhooks on your team.
  • getAddresses(): Get all addresses tracked for the provided Address Activity Webhook.
  • getNftFilters(): Get all NFT filters tracked for the provided NFT Activity Webhook.
  • createWebhook(): Create a new webhook.
  • updateWebhook(): Update an existing webhook's active status or tracked addresses and NFT filters.
  • deleteWebhook(): Delete the provided webhook.

Utils Object

Alchemy provides a consolidated Utils object that supports a number of the most commonly used utils from Ethers. These should be able to be used as a drop-in replacement for ethers.utils.

  • dnsEncode
  • hashMessage
  • id
  • isValidName
  • namehash
  • arrayify
  • concat
  • hexConcat
  • hexDataSlice
  • hexDataLength
  • hexlify
  • hexStripZeros
  • hexValue
  • hexZeroPad
  • isBytes
  • isBytesLike
  • isHexString
  • joinSignature
  • zeroPad
  • splitSignature
  • stripZeros
  • formatEther
  • parseEther
  • parseUnits
  • formatUnits

Documentation

The SDK is documented via tsdoc comments in the source code. The generated types and documentation are included when using an IDE. To browse the documentation separately, you can view the generated API interfaces in the GitHub repository.

Questions and Feedback

👍

Feature Requests

We'd love your thoughts on what would improve your web3 dev process the most! If you have 5 minutes, tell us what you want at our Feature Request feedback form and we'd love to build it for you:

https://alchemyapi.typeform.com/sdk-feedback

If you have any questions, issues, or feedback, please file an issue on GitHub, or drop us a message on our Discord channel for the SDK.