Getting Started with the Alchemy SDK

Getting Started with the Alchemy SDK

This is a beginner's guide to interacting with the blockchain using the Alchemy SDK. A Web3 developer most times you do not get to write smart contracts. They tend to focus on the layer above smart contracts which is interacting and parsing data from the blockchain to the front end of your Dapp. At this point is where we bring in the Alchemy SDK.

Before we dive into learning about the Alchemy SDK, let us first look at what the Alchemy Platform is all about.

What is alchemy?

Alchemy is the leading blockchain development platform, powering millions of users in 197 countries worldwide. The Alchemy platform provides developers with the fundamental building blocks they need to create the future of technology.

What is Alchemy SDK

The Alchemy SDK is a comprehensive, stable, and powerful Javascript SDK used to interact with the blockchain. It gives you up-to-date information about the current state of the blockchain. A single download that bundles all of Alchemy’s hardened node infrastructure and API into a single Javascript package. This guarantee bests node reliability, scalability, and data correctness.

The Alchemy SDK uses the same syntax and functionality as Ethers.js, AlchemyProvider, and WebSocketProvider. It adds some improved functionality on top of Ethersjs, such as;

  • Easy access to Alchemy’s Enhanced and NFT APIs,
  • A robust WebSockets, and
  • Implements automated retries.

Querying Blockchain Data

Blockchain run as a network of individual nodes. Each node stores the entire state of the blockchain as a series of blocks chained together. A single block contains a hash and a list of transactions performed on that block.

Frame 3.png

Querying data from the Blockchain can be easy in some situations and difficult in other cases. For example, getting the latest block number from the blockchain is an easy query, here you are just looking for the end of the block list.

Querying exact information from the blockchain that involves filtering over a list of transactions to get specific information is difficult to achieve. This sort of query will cause you to spend some time manually doing these operations on the client side after reading information from the blockchain.

An example of this is getting a list of transactions carried out by a particular address. This query can be very difficult to achieve due to the nature and structure of a blockchain. The transactions from a particular address do not live in the same block, and there is no built-in mechanism to identify, categorize, or query for that particular data.

This is where the Alchemy SDK becomes a powerful help to make the developer's life easy.

Prerequisites

  • Install nodejs on your PC
  • Choose and install a package manager npm or yarn
  • Install your preferred IDE for this tutorial I will be using VSCode
  • Login or Create an Alchemy Account

Setting up the Alchemy SDK

Set up your project directory

npm

  • We opened up our terminal
  • We created a new project directory.
  • Navigate into our project directory
    mkdir alchemy-nft-api
    cd alchemy-nft-api
    
  • Initialize the directory as an npm project.

    npm init --yes
    

    yarn

    Here we initialized the repository as a yarn project

    mkdir alchemy-nft-api
    cd alchemy-nft-api
    yarn init --yes
    
  • In your package.json file add 'type': 'module'. This is because we would be using the ES6 import syntax

    {
    ...
    "type": "module"
    }
    

Installing the Alchemy SDK

Run the following command to install alchemy-SDK with npm or yarn

npm install alchemy-sdk
yarn add alchemy-sdk
  • Now in our project directory, we create a new file called alchemy.js Interacting with the blockchain.
  • In our alchemy.js file add the code snippet below
import { Network, Alchemy } from 'alchemy-sdk';

const settings = {
  apiKey: 'ALCHEMY _API_KEY', 
  network: Network.ETH_MAINNET, 
};

const alchemy = new Alchemy(settings);

Explanation

  • Line1: We imported the alchemy SDK
  • Line3: We created a config object - This step is optional
  • Line4: In the config object, we added our Alchemy API Key
  • Line5: We added the network we are deploying to.
  • Line8: Created a state variable that initializes the Alchemy settings

After these few lines of code, we can start executing codes to start interacting with the blockchain. A good example is getting NFTs owned by a particular address.

In our alchemy.js file, we can add the code snippet below to get NFTs owned by an address.

import {
  NftExcludeFilters,
  Alchemy
} from 'alchemy-sdk';

const alchemy = new Alchemy();

// Get how many NFTs an address owns.
alchemy.nft.getNftsForOwner('vitalik.eth').then(nfts => {
  console.log(nfts.totalCount);
});

// Get all the image urls for all the NFTs an address owns.
async function main() {
  for await (const nft of alchemy.nft.getNftsForOwnerIterator('vitalik.eth')) {
    console.log(nft.media);
  }
}

main();

// Filter out spam NFTs.
alchemy.nft.getNftsForOwner('vitalik.eth', {
  excludeFilters: [NftExcludeFilters.SPAM]
}).then(console.log);

Supported Chains

Currently, the Alchemy SDK supports the following chain

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

As a Developer, Why should I use the Alchemy SDK?

The Alchemy SDK contains a lot of APIs that help ease the project development process.

Access to Alchemy’s Enhanced NFT APIs

The Alchemy SDK gives you easy access to the Alchemy NFT API. It allows you to fetch and display NFTs for your users, which makes it easy to build all kinds of NFT projects.

Robust Web Socket

A WebSocket does not remain open forever without interruption. Correctly handling dropped connections and reconnection by hand can be very challenging. There are lots of improvements done on the Alchemy SDK that ensures correct WebSocket behavior in cases of temporary network failure or dropped connections.

Resilient event delivery

Compared to Web3.js or Ethers.js, using the Alchemy SDK you will not permanently miss events that occurred while WebSocket is temporarily down. You will receive these events as soon as the connection is back. Note: If the connection is down for more than 20 minutes, you may still miss some events that were not part of the most recent 20 minutes mark.

Automated Retries

There are fewer failures when sending requests over the WebSocket while the connection is down. The Alchemy SDK will attempt to send the requests once the connection is reopened. Note: You should have an error handling code as some of the requests might be lost during this drop in connection.