Metadata-Version: 2.1
Name: covalent-api-sdk
Version: 0.0.3
Summary: covalent-api-sdk-py
Home-page: https://github.com/covalenthq/covalent-api-sdk-py/
Author: Covalenthq
License: MIT
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Requires-Python: >=3.7
Description-Content-Type: text/markdown

# covalent-api-sdk-py

The Covalent API SDK supported for Python. Make sure to use Python 3.7 and above!

The Covalent Python SDK supports all chains across Mainnets and Testnets. List of supported Networks can be found on our [Supported Networks page](https://www.covalenthq.com/docs/networks/)

> **Name Resolution**
>
> The Covalent Python 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

```
pip3 install covalent-api-sdk
```

After installing the app, you can then import and use the SDK:

```py
from covalent import Client
```
```py
def main():
    c = Client("YOUR_KEY")
    b = c.balance_service.get_token_balances_for_wallet_address("eth-mainnet", "demo.eth")
    if not b.error:
        print(b.data.chain_name)
    else:
        print(b.error_message)
```

> **Creating a unique Covalent API Key**
>
> To create your own API key, **[sign up for an Covalent account here](https://www.covalenthq.com/platform/auth/register/)** and use the key created under the [API Keys](https://www.covalenthq.com/platform/apikey/) tab.


## How to use the Covalent Python SDK

The Covalent Python 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:

- `security_service`: Access to the Covalent's getApprovals endpoint
- `balance_service`: Access to the Covalent's balances endpoints
- `base_services`: Access to the Covalent's log events, chain, and block endpoints
- `nft_service`: Access to the Covalent's NFT endpoints
- `pricing_service`: Access to the Covalent's get historical token prices endpoint
- `transaction_service`: Access to the Covalent's transactions endpoints (with pagination)
- `xyk_service`: Access to the Covalent's Xy=k endpoints

### security_service

The `security_service` class contains the get_approvals() endpoint, refer to the [get_approvals endpoint on our API docs](https://www.covalenthq.com/docs/api/security/get-token-approvals-for-address/).

- `get_approvals()`: Get a list of approvals across all token contracts categorized by spenders for a wallet’s assets.

### balance_service

The `balance_service` 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.

- `get_token_balances_for_wallet_address()`: Fetch the native, fungible (ERC20), and non-fungible (ERC721 & ERC1155) tokens held by an address. Response includes spot prices and other metadata.
- `get_historical_token_balances_for_wallet_address()`: 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.
- `get_historical_portfolio_for_wallet_address()`: Render a daily portfolio balance for an address broken down by the token. The timeframe is user-configurable, defaults to 30 days.
- `get_erc20_transfers_for_wallet_address()`: Render the transfer-in and transfer-out of a token along with historical prices from an address.
- `get_token_holders_v2_for_token_address()`: 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.

### base_services

The `base_services` 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.

- `get_block()`: Fetch and render a single block for a block explorer.
- `get_logs()`: Get all the event logs of the latest block, or for a range of blocks. Includes sender contract metadata as well as decoded logs.
- `get_resolved_address()`: Used to resolve ENS, RNS and Unstoppable Domains addresses.
- `get_block_heights()`: Get all the block heights within a particular date range. Useful for rendering a display where you sort blocks by day.
- `get_log_events_by_address()`: Get all the event logs emitted from a particular contract address. Useful for building dashboards that examine on-chain interactions.
- `get_log_events_by_topic_hash()`: 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.
- `get_all_chains()`: Used to build internal dashboards for all supported chains on Covalent.
- `get_all_chain_status()`: Used to build internal status dashboards of all supported chains.

### nft_service

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.

- `get_chain_collections()`: Used to fetch the list of NFT collections with downloaded and cached off chain data like token metadata and asset files.
- `get_nfts_for_address()`: Used to render the NFTs (including ERC721 and ERC1155) held by an address.
- `get_token_ids_for_contract_with_metadata()`: Get NFT token IDs with metadata from a collection. Useful for building NFT card displays.
- `get_nft_metadata_for_given_token_id_for_contract()`: Get a single NFT metadata by token ID from a collection. Useful for building NFT card displays.
- `get_nft_transactions_for_contract_token_id()`: Get all transactions of an NFT token. Useful for building a transaction history table or price chart.
- `get_traits_for_collection()`: Used to fetch and render the traits of a collection as seen in rarity calculators.
- `get_attributes_for_trait_in_collection()`: Used to get the count of unique values for traits within an NFT collection.
- `get_collection_traits_summary()`: Used to calculate rarity scores for a collection based on its traits.
- `check_ownership_in_nft()`: Used to verify ownership of NFTs (including ERC-721 and ERC-1155) within a collection.
- `check_ownership_in_nft_for_specific_token_id()`: Used to verify ownership of a specific token (ERC-721 or ERC-1155) within a collection.
- `get_nft_external_metadata_for_contract()`: Get a single NFT with metadata by token ID from a collection. Useful for building NFT card displays.

### pricing_service

The `pricing_service` class contains the get_token_prices() endpoint. Refer to the [get_token_prices endpoint on our API docs](https://www.covalenthq.com/docs/api/pricing/get-historical-token-prices/).

- `get_token_prices()`: Get historic prices of a token between date ranges. Supports native tokens.

### transaction_service

The `transaction_service` 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.

- `get_all_transactions_for_address()`: Fetch and render the most recent transactions involving an address. Frequently seen in wallet applications.
- `get_transaction()`: Fetch and render a single transaction including its decoded log events. Additionally return semantically decoded information for DEX trades, lending and NFT sales.
- `get_transactions_for_block()`: Fetch all transactions including their decoded log events in a block and further flag interesting wallets or transactions.
- `get_transaction_summary()`: 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.

### xyk_service

The `xyk_service` 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.

- `get_pools()`: 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).
- `get_pool_by_address()`: 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.
- `get_address_exchange_balances()`: Return balance of a wallet/contract address on a specific DEX.
- `get_network_exchange_tokens()`: Get the balance of a wallet address in a DEX. Useful for finding out user balances locked up in DEX pools.
- `get_supported_dexes()`: Get all the supported DEXs available for the xy=k endpoints, along with the swap fees and factory addresses.
- `get_single_network_exchange_token()`: Get historical daily swap count for a single network exchange token.
- `get_transactions_for_account_address()`: Get all the DEX transactions of a wallet. Useful for building tables of DEX activity segmented by wallet.
- `get_transactions_for_token_address()`: Get all the transactions of a token within a particular DEX. Useful for getting a per-token view of DEX activity.
- `get_transactions_for_exchange()`: Get all the transactions of a particular DEX liquidity pool. Useful for building a transactions history table for an individual pool.
- `get_ecosystem_chart_data()`: Get a 7d and 30d time-series chart of DEX activity. Includes volume and swap count.
- `get_health_data()`: Ping the health of xy=k endpoints to get the synced block height per chain.

### How pagination works

The Covalent `get_all_transactions_for_address()` 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:

```py
from covalent import Client
import asyncio

async def main():
    c = Client("YOUR_KEY")
    async for res in c.transaction_service.get_all_transactions_for_address("eth-mainnet", "demo.eth"):
        print(res)

asyncio.run(main())
```
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 `get_all_transactions_for_address()` 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.
```py
❴ 
    "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

Ensure you are at the root directory before running any tests

install `pytest-env` first if you do not have it already

```
pip install pytest-env
```
then go to the `pytest.ini` file in the root director and enter your covalent api key in the `COVALENT_API_KEY` field
then to run all tests, run
```
pytest
```
OR run individual tests

```
pytest tests/test_security_service.py
```

## Documentation

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

