UNPKG

@covalenthq/client-sdk

Version:

<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>

357 lines (269 loc) 17.6 kB
<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> <br/> <p align="center"> <a href="https://www.npmjs.com/package/@covalenthq/client-sdk"> <img src="https://img.shields.io/npm/v/@covalenthq/client-sdk" alt="NPM"> </a> <a href="https://www.npmjs.com/package/@covalenthq/client-sdk"> <img src="https://img.shields.io/npm/dm/@covalenthq/client-sdk" alt="NPM downloads"> </a> <img src="https://img.shields.io/github/license/covalenthq/covalent-api-sdk-ts" alt="Apache-2.0"> </p> # 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](https://www.covalenthq.com/docs/networks/) including Mainnets and Testnets. > Use with [`NodeJS v18`](https://nodejs.org/en) or above for best results. > The GoldRush API is required. You can register for a free key on [GoldRush's website](https://goldrush.dev/platform/apikey) ## Using the SDK > You can also follow the [video tutorial](https://www.youtube.com/watch?v=XSpPJP2w62E&ab_channel=Covalent) 1. Install the dependencies ```bash npm install @covalenthq/client-sdk ``` 2. Create a client using the `GoldRushClient` ```ts 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: ```ts const resp = await client.BalanceService.getTokenBalancesForWalletAddress( "eth-mainnet", "demo.eth", { quoteCurrency: "CAD", nft: true, } ); ``` ### 3. Exported Types All the `interface`s 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 ```ts 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: ```ts 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. ```ts 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 ```ts bigIntParser("-123"); // -123n ``` You can explore more examples [here](./test/unit/bigint-parser.test.ts) 2. **calculatePrettyBalance**: Formats large and raw numbers and bigints to human friendly format. For example ```ts calculatePrettyBalance(1.5, 3, true, 4); // "0.0015" ``` You can explore more examples [here](./test/unit/calculate-pretty-balance.test.ts) 3. **isValidApiKey**: Checks for the input as a valid GoldRush API Key. For example ```ts isValidApiKey(cqt_wF123); // false ``` You can explore more examples [here](./test/unit/is-valid-api-key.test.ts) 4. **prettifyCurrency**: Formats large and raw numbers and bigints to human friendly currency format. For example ```ts prettifyCurrency(89.0, 2, "CAD"); // "CA$89.00" ``` You can explore more examples [here](./test/unit/is-valid-api-key.test.ts) 5. **timestampParser**: Convert ISO timestamps to various human-readable formats ```ts timestampParser("2024-10-16T12:39:23.000Z", "descriptive"); // "October 16 2024 at 18:09:23" ``` You can explore more examples [here](./test/unit/timestamp-parser.test.ts) ### 8. Standardized (Error) Responses All the responses are of the same standardized format ```ts ❴ "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: <details> <summary> 1. <strong>All Chains Service</strong>: Access to the data across multiple chains and addresses. </summary> - `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) </details> <details> <summary> 2. <strong>Security Service</strong>: Access to the token approvals API endpoints </summary> - `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. </details> <details> <summary> 3. <strong>Balance Service</strong>: Access to the balances endpoints </summary> - `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. </details> <details> <summary> 4. <strong>Base Service</strong>: Access to the address activity, log events, chain status, and block retrieval endpoints </summary> - `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. </details> <details> <summary> 5. <strong>Bitcoin Service</strong>: Access to the Bitcoin wallet endpoints </summary> - `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. </details> <details> <summary> 6. <strong>NFT Service</strong>: Access to the NFT endpoints </summary> - `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. - `getHistoricalFloorPricesForCollection()`: Commonly used to render a price floor chart for an NFT collection. - `getHistoricalVolumeForCollection()`: Commonly used to build a time-series chart of the transaction volume of an NFT collection. - `getHistoricalSalesCountForCollection()`: Commonly used to build a time-series chart of the sales count of an NFT collection. - `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. </details> <details> <summary> 7. <strong>Pricing Service</strong>: Access to the historical token prices endpoint </summary> - `getTokenPrices()`: Get historic prices of a token between date ranges. Supports native tokens. </details> <details> <summary> 8. <strong>Transaction Service</strong>: Access to the transactions endpoints </summary> - `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. </details> ## Contributing Contributions, issues and feature requests are welcome! Feel free to check [issues](https://github.com/covalenthq/covalent-api-sdk-ts/issues) page. ## Show your support Give a ⭐️ if this project helped you! ## License This project is [Apache-2.0](./LICENSE) licensed.