covalent-api-sdk-ts
The Covalent API SDK supported for Typescript.
The Covalent SDK supports all chains across Mainnets and Testnets. List of supported Networks can be found on our Supported Networks page
Name Resolution
The Covalent SDK supports address resolution natively allowing an ENS, RNS, Lens Handle or Unstoppable Domains address to be passed in directly for all our endpoints.
Getting started
npm install @covalenthq/client-sdk
or
yarn add @covalenthq/client-sdk
After installing the app, you can then import and use the SDK:
import { Client } from "@covalenthq/client-sdk";
const ApiServices = async () => {
const client = new Client("YOUR_API_KEY");
const resp = await client.BalanceService.getTokenBalancesForWalletAddress("eth-mainnet", "WALLET_ADDRESS");
console.log(resp.data);
}
Creating a unique Covalent API Key
To create your own API key, sign up for an Covalent account here and use the key created under the API Keys tab.
How to use the Covalent SDK
The Covalent SDK provides comprehensive support for all Class A, Class B, and Pricing endpoints grouped under various Services, offering a wide range of functionalities and capabilities:
SecurityService
: Access to the Covalent's getApprovals endpointBalanceService
: Access to the Covalent's balances endpointsBaseServices
: Access to the Covalent's log events, chain, and block endpointsNftService
: Access to the Covalent's NFT endpointsPricingService
: Access to the Covalent's get historical token prices endpointTransactionService
: Access to the Covalent's transactions endpoints (with pagination)XykService
: Access to the Covalent's Xy=k endpoints
SecurityService
The SecurityService
class contains the getApprovals() endpoint, refer to the getApprovals endpoint on our API docs.
getApprovals()
: Get a list of approvals across all token contracts categorized by spenders for a wallet’s assets.
BalanceService
The BalanceService
class contains the balances endpoints. Listed below are the supported endpoints, also refer to our api docs under the Balances section in our class A 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.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.
BaseServices
The BaseServices
class contains the log events, chain, and block endpoints. Listed below are the supported endpoints, also refer to our api docs under the Base section in our class A 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.getLogEventsByAddress()
: Get all the event logs emitted from a particular contract address. Useful for building dashboards that examine on-chain interactions.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.getAllChains()
: Used to build internal dashboards for all supported chains on Covalent.getAllChainStatus()
: Used to build internal status dashboards of all supported chains.
NftService
The NftService
class contains the NFT endpoints. Listed below are the supported endpoints, also refer to our api docs under the NFT section in our class A endpoints.
getChainCollections()
: Used to fetch the list of NFT collections with downloaded and cached off chain data like token metadata and asset files.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.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.getNftExternalMetadataForContract()
: Get a single NFT with metadata by token ID from a collection. Useful for building NFT card displays.
PricingService
The PricingService
class contains the getTokenPrices() endpoint. Refer to the getTokenPrices endpoint on our API docs.
getTokenPrices()
: Get historic prices of a token between date ranges. Supports native tokens.
TransactionService
The TransactionService
class contains the transactions endpoint. Listed below are the supported endpoints, also refer to our api docs under the Transactions section in our class A endpoints.
getAllTransactionsForAddress()
: 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.
XykService
The XykService
class contains the Xy=k endpoints. Listed below are the supported endpoints, also refer to our api docs under the XY=K section in our class B 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.getAddressExchangeBalances()
: Return balance of a wallet/contract address on a specific DEX.getNetworkExchangeTokens()
: Get the balance of a wallet address in a DEX. Useful for finding out user balances locked up in DEX pools.getSupportedDEXes()
: Get all the supported DEXs available for the xy=k endpoints, along with the swap fees and factory addresses.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.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.
The Covalent getAllTransactionsForAddress()
endpoint is currently the only endpoint that supports pagination which return 100 results per page. To get the next page, it uses a link url that is grabbed from the previous call. Here's an example of how to paginate through all recent transactions on the ethereum blockchain for the demo's ENS address:
import { Client } from "@covalenthq/client-sdk";
const ApiServices = async () => {
const client = new Client("YOUR_API_KEY");
for await (const tx of client.TransactionService.getAllTransactionsForAddress("eth-mainnet", "demo.eth")) {
console.log("tx", tx);
}
}
This endpoint exclusively returns transaction items without the response wrapper, enabling developers to access the list seamlessly, ensuring efficient and straightforward transaction item retrieval.
Retry Mechanism
Each endpoint is equipped with an exponential backoff algorithm that exponentially extends the wait time between retries, making up to a maximum of 5
retry attempts only.
Error Handling
The getAllTransactionsForAddress()
endpoint will throw an error message in this format: An error occurred {error_code}: {error_message}
, when an error occurs. The developer would need to make sure to catch those errors if any. This endpoint does not follow our default response format unlike our other endpoints, shown below.
❴
"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.