@covalenthq/client-sdk
TypeScript icon, indicating that this package has built-in type declarations

1.0.2 • Public • Published

NPM npm downloads

Covalent SDK for TypeScript

The Covalent SDK is the fastest way to integrate the Covalent Unified API for working with blockchain data. The SDK works with all supported chains including Mainnets and Testnets.

Note - Require Node v18 and above for best results.

Sign up for an API Key

To get your own Covalent API key, sign up here and create your key from the API Keys tab.

Getting started

npm install @covalenthq/client-sdk

or

yarn add @covalenthq/client-sdk

How to use the Covalent SDK

Video Tutorial: https://www.youtube.com/watch?v=XSpPJP2w62E&ab_channel=Covalent

After installing, you can import and use the SDK with:

import { CovalentClient, Chains } from "@covalenthq/client-sdk";

const ApiServices = async () => {
    const client = new CovalentClient("YOUR_API_KEY"); // Replace with your Covalent API key.

    const balanceResp = await client.BalanceService.getTokenBalancesForWalletAddress("eth-mainnet", "WALLET_ADDRESS");
    if (!balanceResp.error) {
        console.log(balanceResp.data);
    } else {
        console.log(balanceResp.error_message);
    }
}

Name Resolution

The Covalent SDK natively supports ENS domains (e.g. demo.eth), Lens Handles (e.g. @demo.lens) and Unstoppable Domains (e.g. demo.x) which automatically resolve to the underlying user address (e.g. 0xfC43f5F9dd45258b3AFf31Bdbe6561D97e8B71de)

ℹ️ BREAKING CHANGE

If you have been importing with Client:

import { Client } from "@covalenthq/client-sdk";

Please change to CovalentClient:

import { CovalentClient } from "@covalenthq/client-sdk";

How to apply supported query parameters to endpoints

Query parameters are handled using typed objects. To pass in query parameters, developers can define an object that follows the type listed in the provided tsdocs under src/util/types/. Additionally, developers can reference the tsdocs for autocomplete suggestions for the supported parameters. These supported parameters can be passed in any order.

For example, the following sets the quoteCurrency query parameter to CAD and the parameter nft to true for fetching all the token balances, including NFTs, for a wallet address:

const resp = await client.BalanceService.getTokenBalancesForWalletAddress("eth-mainnet", "WALLET_ADDRESS", {quoteCurrency: "CAD", nft: true});

Assign Types

You can import types for each endpoint, found here src/util/types/. Here is an example:

import { CovalentClient, BalancesResponse,  BalanceItem } from "@covalenthq/client-sdk";
const resp = await client.BalanceService.getTokenBalancesForWalletAddress("eth-mainnet", "WALLET_ADDRESS", {quoteCurrency: "CAD", nft: true});
const data: BalancesResponse = resp.data; // `resp.data` in this case is of type `BalancesResponse`
const items: BalanceItem[] = resp.data.items; // `resp.data.items` is of type `BalanceItem[]`

Different ways to input chains in chain fields

We offer users three options for specifying a chain in the designated field:

  1. String literal - directly inputting the chain name, such as eth-mainnet, with auto-completion functionality as the user types.
  2. Chain Enum - utilizing the Chain enum Chains.ETH_MAINNET, which provides auto-suggestions as the user types in the chain field.
  3. Chain Id - entering the ChainId as a numerical value.

Example with string literal

// Example call with string literal  ("eth-mainnet")
const respWithStringLiteral = await client.BalanceService.getTokenBalancesForWalletAddress("eth-mainnet", "WALLET_ADDRESS");

Example with Chain Enum

// Example call with enum  (Chains.ETH_MAINNET)
const respWithEnum = await client.BalanceService.getTokenBalancesForWalletAddress(Chains.ETH_MAINNET, "WALLET_ADDRESS");

Example with Chain Id

// Example call with chain Id  (1)
const respWithChainId = await client.BalanceService.getTokenBalancesForWalletAddress(1, "WALLET_ADDRESS");

Supported Endpoints

The Covalent SDK provides comprehensive support for all Class A, Class B, and Pricing endpoints that are grouped under the following Service namespaces:

SecurityService

The SecurityService class refers to the token approvals API endpoints:

  • getApprovals(): Get a list of approvals across all ERC20 token contracts categorized by spenders for a wallet’s assets.
  • getNftApprovals(): Get a list of approvals across all NFT contracts categorized by spenders for a wallet’s assets.

BalanceService

The BalanceService class refers to the balances API endpoints:

  • getTokenBalancesForWalletAddress(): Fetch the native, fungible (ERC20), and non-fungible (ERC721 & ERC1155) tokens held by an address. Response includes spot prices and other metadata.
  • getHistoricalTokenBalancesForWalletAddress(): Fetch the historical native, fungible (ERC20), and non-fungible (ERC721 & ERC1155) tokens held by an address at a given block height or date. Response includes daily prices and other metadata.
  • getHistoricalPortfolioForWalletAddress(): Render a daily portfolio balance for an address broken down by the token. The timeframe is user-configurable, defaults to 30 days.
  • getErc20TransfersForWalletAddress(): Render the transfer-in and transfer-out of a token along with historical prices from an address. (Paginated)
  • getErc20TransfersForWalletAddressByPage(): Render the transfer-in and transfer-out of a token along with historical prices from an address. (NonPaginated)
  • getTokenHoldersV2ForTokenAddress(): Get a list of all the token holders for a specified ERC20 or ERC721 token. Returns historic token holders when block-height is set (defaults to latest). Useful for building pie charts of token holders. (Paginated)
  • getTokenHoldersV2ForTokenAddressByPage(): Get a list of all the token holders for a specified ERC20 or ERC721 token. Returns historic token holders when block-height is set (defaults to latest). Useful for building pie charts of token holders. (Nonpaginated)
  • getNativeTokenBalance(): Get the native token balance for an address. This endpoint is required because native tokens are usually not ERC20 tokens and sometimes you want something lightweight.

BaseService

The BaseService class refers to the address activity, log events, chain status and block retrieval API endpoints:

  • getBlock(): Fetch and render a single block for a block explorer.
  • getLogs(): Get all the event logs of the latest block, or for a range of blocks. Includes sender contract metadata as well as decoded logs.
  • getResolvedAddress(): Used to resolve ENS, RNS and Unstoppable Domains addresses.
  • getBlockHeights(): Get all the block heights within a particular date range. Useful for rendering a display where you sort blocks by day. (Paginated)
  • getBlockHeightsByPage(): Get all the block heights within a particular date range. Useful for rendering a display where you sort blocks by day. (Nonpaginated)
  • getLogEventsByAddress(): Get all the event logs emitted from a particular contract address. Useful for building dashboards that examine on-chain interactions. (Paginated)
  • getLogEventsByAddressByPage(): Get all the event logs emitted from a particular contract address. Useful for building dashboards that examine on-chain interactions. (Nonpaginated)
  • getLogEventsByTopicHash(): Get all event logs of the same topic hash across all contracts within a particular chain. Useful for cross-sectional analysis of event logs that are emitted on-chain. (Paginated)
  • getLogEventsByTopicHashByPage(): Get all event logs of the same topic hash across all contracts within a particular chain. Useful for cross-sectional analysis of event logs that are emitted on-chain. (Nonpaginated)
  • getAllChains(): Used to build internal dashboards for all supported chains on Covalent.
  • getAllChainStatus(): Used to build internal status dashboards of all supported chains.
  • getAddressActivity(): Locate chains where an address is active on with a single API call.
  • getGasPrices(): Get real-time gas estimates for different transaction speeds on a specific network, enabling users to optimize transaction costs and confirmation times.

NftService

The NftService class refers to the NFT API endpoints:

  • getChainCollections(): Used to fetch the list of NFT collections with downloaded and cached off chain data like token metadata and asset files. (Paginated)
  • getChainCollectionsByPage(): Used to fetch the list of NFT collections with downloaded and cached off chain data like token metadata and asset files. (Nonpaginated)
  • getNftsForAddress(): Used to render the NFTs (including ERC721 and ERC1155) held by an address.
  • getTokenIdsForContractWithMetadata(): Get NFT token IDs with metadata from a collection. Useful for building NFT card displays. (Paginated)
  • getTokenIdsForContractWithMetadataByPage(): Get NFT token IDs with metadata from a collection. Useful for building NFT card displays. (Nonpaginated)
  • getNftMetadataForGivenTokenIDForContract(): Get a single NFT metadata by token ID from a collection. Useful for building NFT card displays.
  • getNftTransactionsForContractTokenId(): Get all transactions of an NFT token. Useful for building a transaction history table or price chart.
  • getTraitsForCollection(): Used to fetch and render the traits of a collection as seen in rarity calculators.
  • getAttributesForTraitInCollection(): Used to get the count of unique values for traits within an NFT collection.
  • getCollectionTraitsSummary(): Used to calculate rarity scores for a collection based on its traits.
  • checkOwnershipInNft(): Used to verify ownership of NFTs (including ERC-721 and ERC-1155) within a collection.
  • checkOwnershipInNftForSpecificTokenId(): Used to verify ownership of a specific token (ERC-721 or ERC-1155) within a collection.
  • getNftMarketSaleCount(): Used to build a time-series chart of the sales count of an NFT collection.
  • getNftMarketVolume(): Used to build a time-series chart of the transaction volume of an NFT collection.
  • getNftMarketFloorPrice(): Used to render a price floor chart for an NFT collection.

PricingService

The PricingService class refers to the historical token prices API endpoint:

  • getTokenPrices(): Get historic prices of a token between date ranges. Supports native tokens.

TransactionService

The TransactionService class refers to the transactions API endpoints:

  • getAllTransactionsForAddress(): Fetch and render the most recent transactions involving an address. Frequently seen in wallet applications. (Paginated)
  • getAllTransactionsForAddressByPage(): Fetch and render the most recent transactions involving an address. Frequently seen in wallet applications. (Nonpaginated)
  • getTransactionsForAddressV3(): Fetch and render the most recent transactions involving an address. Frequently seen in wallet applications.
  • getTransaction(): Fetch and render a single transaction including its decoded log events. Additionally return semantically decoded information for DEX trades, lending and NFT sales.
  • getTransactionsForBlock(): Fetch all transactions including their decoded log events in a block and further flag interesting wallets or transactions.
  • getTransactionSummary(): Fetch the earliest and latest transactions, and the transaction count for a wallet. Calculate the age of the wallet and the time it has been idle and quickly gain insights into their engagement with web3.
  • getTimeBucketTransactionsForAddress(): Fetch all transactions including their decoded log events in a 15-minute time bucket interval.
  • getTransactionsForBlockHashByPage(): Fetch all transactions including their decoded log events in a block and further flag interesting wallets or transactions.
  • getTransactionsForBlockHash(): Fetch all transactions including their decoded log events in a block and further flag interesting wallets or transactions.

The functions getAllTransactionsForAddressByPage(), getTransactionsForAddressV3(), and getTimeBucketTransactionsForAddress() have been enhanced with the introduction of next() and prev() support functions. These functions facilitate a smoother transition for developers navigating through our links object, which includes prev and next fields. Instead of requiring developers to manually extract values from these fields and create JavaScript API fetch calls for the URL values, the new next() and prev() functions provide a streamlined approach, allowing developers to simulate this behavior more efficiently.

import { CovalentClient } from "@covalenthq/client-sdk";

const client = new CovalentClient("YOUR_API_KEY"); // Replace with your Covalent API key.
const resp = await client.TransactionService.getAllTransactionsForAddressByPage("eth-mainnet", "WALLET_ADDRESS");
// assuming resp.data.current_page is 10
if (resp.data !== null) {
    const prevPage = await resp.data.prev() // will retrieve page 9
    console.log(prevPage.data)
}

XykService

The XykService refers to the Xy=k API endpoints:

  • getPools(): Get all the pools of a particular DEX. Supports most common DEXs (Uniswap, SushiSwap, etc), and returns detailed trading data (volume, liquidity, swap counts, fees, LP token prices).
  • getPoolByAddress(): Get the 7 day and 30 day time-series data (volume, liquidity, price) of a particular liquidity pool in a DEX. Useful for building time-series charts on DEX trading activity.
  • getPoolsForTokenAddress(): Get all pools and the supported DEX for a token. Useful for building a table of top pairs across all supported DEXes that the token is trading on.
  • getPoolsForWalletAddress(): Get all pools and supported DEX for a wallet. Useful for building a personal DEX UI showcasing pairs and supported DEXes associated to the wallet.
  • getAddressExchangeBalances(): Return balance of a wallet/contract address on a specific DEX.
  • getNetworkExchangeTokens(): Retrieve all network exchange tokens for a specific DEX. Useful for building a top tokens table by total liquidity within a particular DEX.
  • getLpTokenView(): Get a detailed view for a single liquidity pool token. Includes time series data.
  • getSupportedDEXes(): Get all the supported DEXs available for the xy=k endpoints, along with the swap fees and factory addresses.
  • getDexForPoolAddress(): Get the supported DEX given a pool address, along with the swap fees, DEX's logo url, and factory addresses. Useful to identifying the specific DEX to which a pair address is associated.
  • getSingleNetworkExchangeToken(): Get historical daily swap count for a single network exchange token.
  • getTransactionsForAccountAddress(): Get all the DEX transactions of a wallet. Useful for building tables of DEX activity segmented by wallet.
  • getTransactionsForTokenAddress(): Get all the transactions of a token within a particular DEX. Useful for getting a per-token view of DEX activity.
  • getTransactionsForExchange(): Get all the transactions of a particular DEX liquidity pool. Useful for building a transactions history table for an individual pool.
  • getTransactionsForDex(): Get all the the transactions for a given DEX. Useful for building DEX activity views.
  • getEcosystemChartData(): Get a 7d and 30d time-series chart of DEX activity. Includes volume and swap count.
  • getHealthData(): Ping the health of xy=k endpoints to get the synced block height per chain.

Additional Helper Functions

calculatePrettyBalance

The calculatePrettyBalance function is designed to take up to 4 inputs: the balance field obtained from the tokenBalance endpoint and the contract_decimals. The function also includes two optional fields, roundOff and precision, to allow developers to round the unscaled balance to a certain decimal precision. The primary purpose of this function is to convert the scaled token balance (the balance parameter) into its unscaled, human-readable form. The scaled balance needs to be divided by 10^(contractDecimals) to remove the scaling factor.

import { CovalentClient, calculatePrettyBalance } from "@covalenthq/client-sdk";

const client = new CovalentClient("YOUR_API_KEY"); // Replace with your Covalent API key.
const resp = await client.BalanceService.getTokenBalancesForWalletAddress("eth-mainnet", "WALLET_ADDRESS");
const prettyBalance = calculatePrettyBalance(resp.data.items[0].balance, resp.data.items[0].contract_decimals);

prettifyCurrency

The prettifyCurrency function refines the presentation of a monetary value, accepting a numerical amount and a fiat currency code as parameters (with USD as the default currency). It simplifies currency formatting for developers, ensuring visually polished representations of financial information in user interfaces for an enhanced user experience.

import { CovalentClient, prettifyCurrency } from "@covalenthq/client-sdk";

const client = new CovalentClient("YOUR_API_KEY"); // Replace with your Covalent API key.
const resp = await client.BalanceService.getTokenBalancesForWalletAddress("eth-mainnet", "WALLET_ADDRESS");
const prettyCurrency = prettifyCurrency(resp.data.items[0].quote_rate);

Built-in SDK Features

Explaining Pagination Mechanism Within the SDK

The following endpoints support pagination:

  • getErc20TransfersForWalletAddress()
  • getTokenHoldersV2ForTokenAddress()
  • getBlockHeights()
  • getLogEventsByAddress()
  • getLogEventsByTopicHash()
  • getChainCollections()
  • getTokenIdsForContractWithMetadata()
  • getAllTransactionsForAddress()

Using the Covalent API, paginated supported endpoints return only 100 items, such as transactions or log events, per page. However, the Covalent SDK leverages generators to seamlessly fetch all items without the user having to deal with pagination.

For example, the following fetches ALL transactions for demo.eth on Ethereum:

import { CovalentClient } from "@covalenthq/client-sdk";

const ApiServices = async () => {
    const client = new CovalentClient("YOUR_API_KEY"); // Replace with your Covalent API key.
    try {
        for await (const tx of client.TransactionService.getAllTransactionsForAddress("eth-mainnet", "demo.eth")) {
            console.log("tx", tx);
        }
    } catch (error) {
        console.log(error.message);
    }
}

Concurrency Mechanism

Developers have the flexibility to specify the desired number of concurrent API calls they wish to execute using the threadCount settings parameter, with a default value of 3. For example:

import { CovalentClient, CovalentClientSettings } from "@covalenthq/client-sdk";

const settings: CovalentClientSettings = {
    threadCount: 5
}

const ApiServices = async () => {
    const client = new CovalentClient("YOUR_API_KEY", settings); // Replace with your Covalent API key and add set debugger
    const resp = await client.BalanceService.getTokenBalancesForWalletAddress("eth-mainnet", "WALLET_ADDRESS");
    if (!resp.error) {
        console.log(resp.data);
    } else {
        console.log(resp.error_message);
    }
}

Debugger Mode

Developers have the option to enable a debugger mode that provides response times, the URLs of called endpoints, and the HTTP statuses of those endpoints. This feature helps users identify which endpoints may have encountered failures. The default is debug = false if no input is provided.

import { CovalentClient, CovalentClientSettings } from "@covalenthq/client-sdk";

const settings: CovalentClientSettings = {
    debug: true
}

const ApiServices = async () => {
    const client = new CovalentClient("YOUR_API_KEY", settings); // Replace with your Covalent API key and add set debugger
    const resp = await client.BalanceService.getTokenBalancesForWalletAddress("eth-mainnet", "WALLET_ADDRESS");
    if (!resp.error) {
        console.log(resp.data);
    } else {
        console.log(resp.error_message);
    }
}

example result image

Retry Mechanism

Each endpoint is equipped with an exponential backoff algorithm that exponentially extends the wait time between retries, up to a maximum of 5 retry attempts.

Users have the ability to control the retry feature through the enableRetry configuration setting. By default, this feature is enabled true. However, users can deactivate it by setting enableRetry to false.

import { CovalentClient, CovalentClientSettings } from "@covalenthq/client-sdk";

const settings: CovalentClientSettings = {
    enableRetry: false
}

Error Handling

The paginated endpoints throw an error message in this format: An error occurred {error_code}: {error_message}. The developer will need to catch these errors. Note - these endpoints do not follow the default response format which is:

 
    "data": ...,
    "error": false,
    "error_message": null,
    "error_code": null

Error codes

Covalent uses standard HTTP response codes to indicate the success or failure of an API request. In general: codes in the 2xx range indicate success. Codes in the 4xx range indicate an error that failed given the information provided (e.g., a required parameter was omitted, etc.). Codes in the 5xx range indicate an error with Covalent's servers (these are rare).

Code Description
200 OK Everything worked as expected.
400 Bad Request The request could not be accepted, usually due to a missing required parameter.
401 Unauthorized No valid API key was provided.
404 Not Found The request path does not exist.
429 Too Many Requests You are being rate-limited. Please see the rate limiting section for more information.
500, 502, 503 Server Errors Something went wrong on Covalent's servers. These are rare.

Tests

to run all tests, you need to input your api key first shown below

COVALENT_API_KEY=YOUR_KEY npm test

OR

you can run individual tests for each service, for example

COVALENT_API_KEY=YOUR_KEY npm test -- security-service.test.ts

Documentation

The Covalent API SDK documentation is integrated within the source code through tsdoc comments. When utilizing an Integrated Development Environment (IDE), the SDK provides generated types and accompanying documentation for seamless reference and usage.

Readme

Keywords

none

Package Sidebar

Install

npm i @covalenthq/client-sdk

Weekly Downloads

3,124

Version

1.0.2

License

MIT

Unpacked Size

5.91 MB

Total Files

146

Last publish

Collaborators

  • jagnani73
  • jaypozo_covalent
  • daviddzhang
  • harishraisinghani
  • covalenthq_devops