npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@covalenthq/client-sdk

v2.2.2

Published

<div align="center"> <a href="https://goldrush.dev/products/goldrush/" target="_blank" rel="noopener noreferrer"> <img alt="GoldRush TS SDK Logo" src="./repo-static/ts-sdk-banner.png" style="max-width: 100%;"/> </a> </div>

Downloads

12,486

Readme

GoldRush SDK for TypeScript

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

Use with NodeJS v18 or above for best results.

The GoldRush API is required. You can register for a free key on GoldRush's website

Using the SDK

You can also follow the video tutorial

  1. Install the dependencies

    npm install @covalenthq/client-sdk
  2. Create a client using the GoldRushClient

    import { GoldRushClient, Chains } from "@covalenthq/client-sdk";
    
    const client = new GoldRushClient("<YOUR_API_KEY>");
    
    const ApiServices = async () => {
      try {
        const balanceResp =
          await client.BalanceService.getTokenBalancesForWalletAddress(
            "eth-mainnet",
            "demo.eth"
          );
    
        if (balanceResp.error) {
          throw balanceResp;
        }
    
        console.log(balanceResp.data);
      } catch (error) {
        console.error(error);
      }
    };

    The GoldRushClient can be configured with a second object argument, settings. The settings offered are

    1. debug: A boolean that enables server logs of the API calls, enhanced with the request URL, response time and code, and other settings. It is set as false by default.
    2. threadCount: A number that sets the number of concurrent requests allowed. It is set as 2 by default.
    3. enableRetry: A boolean that enables retrying the API endpoint in case of a 429 - rate limit error. It is set as true by default.
    4. maxRetries: A number that sets the number of retries to be made in case of 429 - rate limit error. To be in effect, it requires enableRetry to be enabled. It is set as 2 by default.
    5. retryDelay: A number that sets the delay in ms for retrying the API endpoint in case of 429 - rate limit error. To be in effect, it requires enableRetry to be enabled. It is set as 2 by default.
    6. source: A string that defines the source of the request of better analytics.

Features

1. Name Resolution

The GoldRush SDK natively resolves the underlying wallet address for the following

  1. ENS Domains (e.g. demo.eth)
  2. Lens Handles (e.g. demo.lens)
  3. Unstoppable Domains (e.g. demo.x)
  4. RNS Domains (e.g. demo.ron)

2. Query Parameters

All the API call arguments have an option to pass typed objects as Query parameters.

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",
  "demo.eth",
  {
    quoteCurrency: "CAD",
    nft: true,
  }
);

3. Exported Types

All the interfaces used, for arguments, query parameters and responses are also exported from the package which can be used for custom usage.

For example, explicitly typecasting the response

import {
  GoldRushClient,
  type BalancesResponse,
  type BalanceItem,
} from "@covalenthq/client-sdk";

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

const data: BalancesResponse = resp.data;
const items: BalanceItem[] = resp.data.items;

4. Multiple Chain input formats

The SDK supports the following formats for the chain input:

  1. Chain Name (e.g. eth-mainnet)
  2. Chain ID (e.g. 1)
  3. Chain Name Enum (e.g. ChainName.ETH_MAINNET)
  4. Chain ID Enum (e.g. ChainID.ETH_MAINNET)

5. Additional Non-Paginated methods

For paginated responses, the GoldRush API can at max support 100 items 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 { GoldRushClient } from "@covalenthq/client-sdk";

const ApiServices = async () => {
  const client = new GoldRushClient("<YOUR_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);
  }
};

6. Executable pagination functions

Paginated methods 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 { GoldRushClient } from "@covalenthq/client-sdk";

const client = new GoldRushClient("<YOUR_API_KEY>");
const resp = await client.TransactionService.getAllTransactionsForAddressByPage(
  "eth-mainnet",
  "demo.eth"
); // 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);
}

7. Utility Functions

  1. bigIntParser: Formats input as a bigint value. For example

    bigIntParser("-123"); // -123n

    You can explore more examples here

  2. calculatePrettyBalance: Formats large and raw numbers and bigints to human friendly format. For example

    calculatePrettyBalance(1.5, 3, true, 4); // "0.0015"

    You can explore more examples here

  3. isValidApiKey: Checks for the input as a valid GoldRush API Key. For example

    isValidApiKey(cqt_wF123); // false

    You can explore more examples here

  4. prettifyCurrency: Formats large and raw numbers and bigints to human friendly currency format. For example

    prettifyCurrency(89.0, 2, "CAD"); // "CA$89.00"

    You can explore more examples here

  5. timestampParser: Convert ISO timestamps to various human-readable formats

    timestampParser("2024-10-16T12:39:23.000Z", "descriptive"); // "October 16 2024 at 18:09:23"

    You can explore more examples here

8. Standardized (Error) Responses

All the responses are of the same standardized format

❴
    "data": <object>,
    "error": <boolean>,
    "error_message": <string>,
    "error_code": <number>
❵

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:

  • getAddressActivity(): Locate chains where an address is active on with a single API call.
  • getMultiChainMultiAddressTransactions(): Fetch and render the transactions across multiple chains and addresses
  • getMultiChainBalances(): Fetch the token balances of an address for multiple chains. (limited to 10 chains at a time)
  • 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.
  • 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.
  • 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.
  • getGasPrices(): Get real-time gas estimates for different transaction speeds on a specific network, enabling users to optimize transaction costs and confirmation times.
  • getBitcoinHdWalletBalances(): Fetch balances for each active child address derived from a Bitcoin HD wallet.
  • getTokenBalancesForWalletAddress(): Fetch the native, fungible (ERC20), and non-fungible (ERC721 & ERC1155) tokens held by an address. Response includes spot prices and other metadata.
  • getTransactionsForBtcAddress(): Used to fetch the full transaction history of a Bitcoin wallet. Only supports non-HD bitcoin addresses.
  • 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.
  • getTokenPrices(): Get historic prices of a token between date ranges. Supports native tokens.
  • 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.

Contributing

Contributions, issues and feature requests are welcome! Feel free to check issues page.

Show your support

Give a ⭐️ if this project helped you!

License

This project is Apache-2.0 licensed.