# Introduction

<figure><img src="/files/lMdSITHAaHQnMbexrcb2" alt=""><figcaption></figcaption></figure>

Welcome to the Crypto.com AI Agent SDK and Developer Platform.&#x20;

This guide will help you get started quickly and understand the two main ways you can interact with Crypto.com's developer tools to build on Cronos EVM and Cronos zkEVM.

***

### Overview

Crypto.com sits at the product layer, offering apps, services, and developer tools like the Crypto.com App, Exchange, and DeFi Wallet, all built to support and integrate with the Cronos chains. In partnership with Cronos Labs, Crypto.com delivers seamless access to projects running on Cronos.

At the technology layer, Cronos consists of three public blockchains:

* Cronos zkEVM – a Zero-Knowledge (ZK) Ethereum Layer-2 focused on scalability, security, and innovation.
* Cronos EVM – an Ethereum-compatible Layer-1 built on the Cosmos SDK, optimized for Web3 and decentralized applications.
* Cronos POS – a Proof-of-Stake Layer-0 chain that underpins the security of the Cronos ecosystem.

These chains expose native Explorer APIs and JSON-RPC methods for direct integration. To simplify this, the Crypto.com Developer Platform offers a higher-level Service API built on Ethers.&#x20;

Through its Client SDKs, developers can access tokens, smart contracts, transactions, blocks, and wallets on Cronos EVM and Cronos zkEVM (Cronos POS is not supported), without managing low-level node connections. In addition, the Developer Platform integrates access to the Crypto.com Exchange API and DeFi platforms like VVS and H2, helps developers to interact with trading, liquidity, and DeFi functionality directly from the same unified interface.

<figure><img src="/files/19pcaKDIbuE3xb9gHIRE" alt=""><figcaption></figcaption></figure>

On top of this, the Crypto.com AI Agent SDK adds a natural-language interface powered by LLMs (e.g., OpenAI, Google GenAI). It provides end users with the ability to interact with blockchain functionality, such as checking balances or sending tokens, simply by expressing their intent in plain language, the SDK translates these inputs into API calls and returns the results back in plain language.

### Two Ways to Building on Cronos with Crypto.com Tools

#### 1. Crypto.com AI Agent SDK

Crypto.com AI Agent SDK allows developers to build apps where end users can interact with Cronos EVM and Cronos zkEVM using natural language. The SDK interprets plain-language questions or commands and translates them into blockchain interactions via the Developer Platform Service API, which abstracts chain complexity, normalizes responses, and handles authentication, rate limits, and environment scoping.

The AI Agent SDK provides idiomatic methods for:

* Interacting with tokens, smart contracts, and transaction data
* Querying balances, transaction statuses, and block information
* Managing wallets and CronosID resolution
* Accessing the Crypto.com Exchange API and DeFi platforms such as VVS and H2
* Building user-friendly experiences like chatbots, assistants, and wallets without requiring users to understand blockchain technical details

Check Crypto.com AI Agent SDK documents for more information:

{% content-ref url="/pages/fChgGVDC8BJyXVX3iuMz" %}
[AI Agent SDK](/crypto.com-ai-agent-sdk/quickstart)
{% endcontent-ref %}

#### 2. Crypto.com On-Chain Developer Platform Client SDK

Crypto.com Developer Platform Client SDK allows developers to work with Cronos EVM and Cronos zkEVM through conventional APIs. The SDK is built on the Developer Platform Service API, which abstracts chain complexity, normalizes responses, and handles authentication, rate limits, and environment scoping. It is implemented with Ethers, so your app does not need to call Cronos Explorer APIs or JSON‑RPC directly.&#x20;

The Client SDKs (TypeScript/Python) provide idiomatic methods for:

* Querying balances, transactions, and blocks (Cronos EVM & zkEVM)
* Working with native tokens and ERC‑20/ERC‑721 assets
* Managing wallets and CronosID resolution
* Accessing the Crypto.com Exchange API and DeFi platforms such as VVS and H2
* Wallet utilities and project‑scoped credentials

Check Crypto.com On-Chain Developer Platform Client SDK documents for more information:

{% content-ref url="/pages/62kuYuZaGkYvmeEdexC3" %}
[On-Chain Developer Platform](/crypto.com-developer-platform/on-chain-developer-platform)
{% endcontent-ref %}

### TL;DR

* Crypto.com is the product layer (Developer Platform, AI Agent SDK, Exchange, DeFi wallet, and other dApps).
* Cronos is the technology layer (three chains).
* Cronos chains expose Explorer APIs and JSON‑RPC.
* Developer Platform uses Ethers and skips Explorer APIs/JSON‑RPC in your integration, integrates Crypto.com Exchange API and DeFi platform APIs, giving you a single, production‑ready surface.
* AI Agent SDK adds natural-language access for end users to be able to communicate with Developer Platform in plain language.

### Quick Links

* **Cronos Explorer APIs**\
  Cronos EVM: <https://explorer-api-doc.cronos.org/mainnet/>\
  Cronos zkEVM: <https://explorer-api-doc.zkevm.cronos.org/mainnet/index.html>
* **Cronos JSON‑RPC**\
  Cronos EVM: <https://docs.cronos.com/for-dapp-developers/chain-integration/json-rpc>\
  Cronos zkEVM: <https://docs-zkevm.cronos.com/for-developers/json-rpc-api-overview>
* **Crypto.com Developer Platform**

  Dashboard: <https://ai-agent-sdk-docs.crypto.com/crypto.com-developer-platform/developer-platform-dashboard>

  Client SDKs: <https://ai-agent-sdk-docs.crypto.com/crypto.com-developer-platform/on-chain-developer-platform-client-sdk>
* **Crypto.com AI Agent SDK**

  <https://ai-agent-sdk-docs.crypto.com/crypto.com-ai-agent-sdk/quickstart>


# Outdated Contents


# Crypto.com AI Agent Client

### Introduction

The Crypto.com AI Agent Client is a library designed to facilitate easy and efficient interactions with the Crypto.com AI Agent Service API. This client library provides methods to send queries and fetch responses from the Crypto.com AI Agent Service seamlessly, currently the library supports:&#x20;

* **TypeScript/JavaScript**
  * [npm page](https://www.npmjs.com/package/@crypto.com/ai-agent-client)
  * [Github](https://github.com/crypto-com/cdc-ai-agent-client-ts)
* **Python**
  * [Pypi page](https://pypi.org/project/crypto-com-ai-agent-client/)
  * [Github](https://github.com/crypto-com/cdc-ai-agent-client-py)

{% hint style="success" %}
The implementation of the AI Agent Client is open source and can be found in this [Github repository](https://github.com/crypto-com/developer-platform-sdk-examples/tree/main/ai/cryptocom-ai-agent-service). \
Developers can also refer to [Self-Hosting AI-Agent-Server](/outdated-contents/self-hosting-ai-agent-server) example to host it independently.
{% endhint %}

### Features

{% hint style="info" %}
**Currently in beta**: Expect frequent updates and potential changes in future releases.
{% endhint %}

* Simple and intuitive API for interacting with the Crypto.com AI Agent.
* Supports sending queries and receiving AI-generated responses.
* Configurable client instances tailored to your specific endpoint and security needs.
* Support networks: **Cronos zkEVM** and **Cronos EVM** mainnet and testnet.&#x20;

### Installation

{% tabs %}
{% tab title="TypeScript / JavaScript" %}
To install the package, run the following command in your project directory:

```
npm install @crypto.com/ai-agent-client
```

{% endtab %}

{% tab title="Python " %}
To install the package, run the following command:

```
pip install crypto-com-ai-agent-client
```

{% endtab %}
{% endtabs %}

### Usage

Here’s how you can use the Crypto.com AI Agent Client in your project:

#### Configuring the Client

{% tabs %}
{% tab title="TypeScript / JavaScript" %}

```javascript
import { createClient } from "@crypto.com/ai-agent-client";
import { QueryOptions } from "@crypto.com/ai-agent-client/dist/integrations/cdc-ai-agent.interfaces";

const OPEN_AI_API_KEY = "OPEN-AI-API-KEY";
const CHAIN_ID = 240; // 25 for Cronos EVM Mainnet, 338 for Cronos EVM Testnet, 388 for Cronos ZkEVM Mainnet, 240 for Cronos ZkEVM Testnet

const EXPLORER_KEY = "ZKEVM-TESTNET-API-KEY";

// Function to send a query and log the response
async function sendQuery(query: string) {
  // Create client params
  const queryOptions: QueryOptions = {
    openAI: {
      apiKey: OPEN_AI_API_KEY,
      model: "gpt-4-turbo",
    },
    chainId: CHAIN_ID,
    explorerKeys: {
      cronosMainnetKey: "YOUR-CRONOS-EVM-MAINNET-EXPLORER-KEY",
      cronosTestnetKey: "YOUR-CRONOS-EVM-TESTNET-EXPLORER-KEY",
      cronosZkEvmKey: "YOUR-CRONOS-zkEVM-MAINNET-EXPLORER-KEY",
      cronosZkEvmTestnetKey: EXPLORER_KEY,
    },
    context: [],
    // signerAppUrl: 'https://my-signer-app', // Refer to: https://github.com/crypto-com/cdc-ai-agent-signer-app
    // customRPC: 'https://rpc.vvs.finance,
  };
}
```

{% endtab %}

{% tab title="Python" %}

```python
from crypto_com_ai_agent_client import create_client

client = create_client({
    'openAI': {
        'apiKey': 'YOUR_OPEN_AI_API_KEY',
        'model': 'gpt-4o'  # Optional, defaults to 'gpt-4-turbo'
    },
    'chainId': 240,  # 25 for Cronos EVM Mainnet, 338 for Cronos EVM Testnet, 388 for Cronos ZkEVM Mainnet, 240 for Cronos ZkEVM Testnet
    'explorerKeys': {
        'cronosMainnetKey': 'CRONOS_MAINNET_API_KEY',
        'cronosTestnetKey': 'CRONOS_TESTNET_API_KEY',
        'cronosZkEvmKey': 'CRONOS_ZKEVM_API_KEY',
        'cronosZkEvmTestnetKey': 'CRONOS_ZKEVM_TESTNET_API_KEY'
    },
    'context': [],  # Optional
    'signerAppUrl': '',  # Optional, for example - https://my-signer-app
    'customRPC': ''  # Optional, if not provided, the default RPC for the chainId will be used
})
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
Here are the key details for:

**Cronos zkEVM**

* [Network config](https://docs-zkevm.cronos.org/for-developers/develop-smart-contracts-and-dapps#overview)
* [Explorer](https://docs-zkevm.cronos.org/for-developers/developer-tools/developer-portal-apis)[ API Key](https://docs-zkevm.cronos.org/for-developers/developer-tools/developer-portal-apis)

**Cronos EVM**

* [Network config](https://docs.cronos.org/cronos-chain-protocol/cronos-general-faq#what-is-the-chain-id-for-cronos-mainnet)
* [Explorer](https://docs.cronos.org/block-explorers/block-explorer-and-api-keys)[ API Key](https://docs.cronos.org/block-explorers/block-explorer-and-api-keys)
  {% endhint %}

Sending a Query

{% tabs %}
{% tab title="TypeScript/JavaScript" %}

```typescript
const sendQuery = async (query) => {
  try {
    const response = await client.agent.generateQuery(query);
    console.log('Crypto.com AI Agent Response:', response);
  } catch (error) {
    console.error('Error sending query:', error);
  }
};
```

{% endtab %}

{% tab title="Python" %}

```python
def send_query(query):
    try:
        response = client.agent.generate_query(query)
        print('Crypto.com AI Agent Response:', response)
    except Exception as e:
        print(f"Error sending query: {str(e)}")

send_query("What is the latest block?")
```

{% endtab %}
{% endtabs %}

### API

#### Client Methods

* `generate_query(query)`: Generates a query that is send to the Crypto.com AI Agent Service and returns a response.


# AI Agent Service APIs

This service is part of the **Crypto.com AI Agent SDK**, designed to facilitate querying blockchain services via Natural Language Processing (NLP) integrated with OpenAI. The core logic of the service interprets user queries, matches them with blockchain functions, and interacts with blockchain nodes and explorers.

### Background

The Crypto.com AI Agent Service API integrates multiple technologies to provide a seamless interaction with blockchain services via natural language queries. The core logic is divided into several components:

1. **Agent Logic**: This stores the core mapping logic between user input and blockchain functions. It uses OpenAI's NLP capabilities to map the user’s query to the corresponding blockchain function.
2. **Blockchain Service**: A collection of blockchain commands such as `getLatestBlock`, `createWallet`, etc. These commands interact with blockchain nodes to retrieve or perform actions.
3. **Explorer Integration**: This component interacts with blockchain explorers to retrieve additional blockchain data using the Cronos explorer APIs.

* API url: [https://ai-agent-api.crypto.com/api/v1/cdc-ai-agent-service](https://ai-agent-api.crypto.com/api/v1/cdc-ai-agent-service/query) (***Rate limited to 50 requests per minute***)

### Features

* **NLP Query Mapping**: Maps user queries to blockchain functions using OpenAI.
* **Blockchain Commands**: Perform blockchain-specific commands such as retrieving blocks, creating wallets, and more.
* **Explorer API Integration**: Fetch blockchain data from the Cronos explorer APIs.
* **Health Monitoring**: A health check route to monitor the API’s status and uptime.

### How It works

The service exposes two main API routes:

1. **Health Check Route**: Provides basic uptime and response time of the service, allowing users or automated systems to monitor the API.
2. **Query Route**: Allows the user to input a query in natural language, which is processed by the core Agent logic. This logic, powered by OpenAI, maps the input to a specific blockchain function and executes the corresponding action on the blockchain.

The architecture:

* The **query server** accepts a query and processes it through the agent logic.
* **OpenAI** processes the query using NLP and matches it with a relevant function.
* The matched function is then executed by interacting with the **blockchain service** or **explorer APIs** to retrieve or perform the desired action.

### API Endpoints

**Health Check**

* **Endpoint**: `/healthcheck`
* **Method**: `GET`
* **Description**: Returns the uptime and health status of the service.

**Example**:&#x20;

```
curl https://ai-agent-api.crypto.com/healthcheck
```

**Response Example**:

```
{
  "status": "success",
  "result": {
    "uptime": 120.34,
    "responsetime": [0, 252939],
    "message": "OK",
    "timestamp": 1632846348163
  }
}
```

**Query Route**

* **Endpoint**: `/api/v1/cdc-ai-agent-service/query`
* **Method**: `POST`
* **Description**: Takes a natural language query, maps it to a blockchain command via OpenAI, and executes the command.

Example: Getting the latest block - With `get latest block`

{% tabs %}
{% tab title="Request Body Example:" %}

```
{
  "query": "get latest block",
  "options": {
    "openAI": {
      "apiKey": "<your-openai-api-key>"
    },
    "chain": {
      "id": 240,
      "name": "cronos-zkevm-testnet",
      "rpc": "https://testnet.zkevm.cronos.org"
    },
    "explorer": {
      "apiKey": "<your-explorer-api-key>"
    },
    "wallet": {
      "mnemonic": "<your-mnemonic-phrase>"
    }
  }
}
```

{% endtab %}

{% tab title="cURL example:" %}

```
curl --location 'https://ai-agent-api.crypto.com/api/v1/cdc-ai-agent-service/query' \
--header 'Content-Type: application/json' \
--data '{
    "query": "What is the latest block?",
    "options": {
        "openAI": {
            "apiKey": "<FILL-IN>"
        },
        "chainId": 388,
        "explorerKeys": {
            "cronosZkEvmKey": "<FILL-IN>"
        }
    }
}'
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
Here are the key details for:

**Cronos zkEVM**

* [Network config](https://docs-zkevm.cronos.org/for-developers/develop-smart-contracts-and-dapps#overview)
* [Explorer](https://docs-zkevm.cronos.org/for-developers/developer-tools/developer-portal-apis)[ API Key](https://docs-zkevm.cronos.org/for-developers/developer-tools/developer-portal-apis)

**Cronos EVM**

* [Network config](https://docs.cronos.org/cronos-chain-protocol/cronos-general-faq#what-is-the-chain-id-for-cronos-mainnet)
* [Explorer](https://docs.cronos.org/block-explorers/block-explorer-and-api-keys)[ API Key](https://docs.cronos.org/block-explorers/block-explorer-and-api-keys)
  {% endhint %}

**Response Example**:

```
{
  "status": "success",
  "result": {
    "action": "getBlock",
    "message": "Retrieved latest block",
    "data": {
      "blockNumber": 123456,
      "timestamp": "2023-09-12T10:12:15Z"
    }
  }
}
```


# Functions and Example Queries of AI agent services

### Introduction

This page provides detailed information on various on-chain functions and example queries available through the Crypto.com AI Agent SDK. Each function is accompanied by a sample query and explanation of the response format, offering developers guidance on how to interact with Cronos Chains using the AI agent services.

### 1. Transfer native token

Sends a transaction from one address to another.

{% tabs %}
{% tab title="Query " %}

* Example Query&#x20;

```
query: "Send 1 ZKCRO to 0xRecipientAddress"
```

**Function Name**: `SendTransaction`

* **Function Argument**:

  ```json
  {
    "to": "0xRecipientAddress",
    "amount": 1,
    "symbol": "ZKCRO"
  }
  ```

{% endtab %}

{% tab title="Response" %}

```json
{
  "status": "Success",
  "action": "SendTransaction",
  "message": "Signature url created successfully. Please sign the transaction on this link",
  "data": {
    "magicLink": "https://{provider}/sign-transaction/{transactionId}?token={token}"
  }
}
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
This function returns a magic link. [Read more about Magic Link](/crypto.com-ai-agent-sdk/ai-agent-sdk-examples/magic-link-signer).
{% endhint %}

### 2.  Obtain on-chain balance

Fetches the balance of multiple wallet addresses.

{% tabs %}
{% tab title="Query" %}

* Example Query&#x20;

```
query: "Get balance for 0xWalletAddress1 and 0xWalletAddress2"
```

**Function Name**: `GetBalance`

* **Function Argument**:

  ```json
  {
    "walletAddresses": ["0xWalletAddress1", "0xWalletAddress2"]
  }
  ```

{% endtab %}

{% tab title="Response" %}

```json
{
  "status": "Success",
  "action": "GetBalance",
  "message": "Balances: 0xAddress: 0.5 ETH",
  "data": {
    "balances": [
      {
        "address": "0xAddress",
        "balanceWei": "500000000000000000",
        "balanceEth": "0.5",
        "balanceVUsd": "1000"
      }
    ]
  }
}
```

{% endtab %}
{% endtabs %}

### 3. **Get Latest Block**

Fetches the latest block information.

{% tabs %}
{% tab title="Query" %}

* Example Query&#x20;

```
query: "Get latest block height"
```

**Function Name**: `GetLatestBlock`

* **Function Argument**:

  ```json
  {}
  ```

{% endtab %}

{% tab title="Response" %}

```json
{
  "status": "Success",
  "action": "GetLatestBlock",
  "message": "Latest block height: 123456",
  "data": {
    "blockHeight": 123456,
    "timestamp": "2023-09-24T14:22:00.000Z"
  }
}
```

{% endtab %}
{% endtabs %}

### **4. Get Transactions by Address**

Fetches transactions for a specific address.

{% tabs %}
{% tab title="Query" %}

* Example Query&#x20;

```
query: "Show transactions for 0xYourAddress"
```

**Function Name**: `GetTransactionsByAddress`

* **Function Argument**:

  ```json
  {
    "address": "0xYourAddress",
    "session": "ExplorerPageSession", // TODO: automatically adjust page based on user instruction
    "limit": 20
  }
  ```

{% endtab %}

{% tab title="Response" %}

```json
{
  "status": "Success",
  "action": "GetTransactionsByAddress",
  "message": "Retrieved 20 transactions for 0xAddress",
  "data": {
    "transactions": [...],
    "pagination": {...}
  }
}
```

{% endtab %}
{% endtabs %}

### 5. **Get Contract ABI**

Fetches the ABI (Application Binary Interface) of a contract.

{% tabs %}
{% tab title="Query" %}

* Example Query&#x20;

```
query: "Fetch the ABI for contract at 0xContractAddress"
```

**Function Name**: `GetContractABI`

* **Function Argument**:

  ```json
  {
    "address": "0xContractAddress"
  }
  ```

{% endtab %}

{% tab title="Response" %}

```json
{
  "status": "Success",
  "action": "GetContractABI",
  "message": "Fetched ABI for contract at 0xContractAddress",
  "data": { "abi": result }
}
```

{% endtab %}
{% endtabs %}

### 6. **Get Transaction by Hash**

Fetches the details of a transaction using its hash.

{% tabs %}
{% tab title="Query" %}

* Example Query&#x20;

```
query: "Get transaction details for 0xTransactionHash"
```

**Function Name**: `GetTransactionByHash`

* **Function Argument**:

  ```json
  {
    "txHash": "0xTransactionHash"
  }
  ```

{% endtab %}

{% tab title="Response" %}

```json
{
  "status": "Success",
  "action": "GetTransactionByHash",
  "message": "Retrieved details for transaction 0xTransactionHash",
  "data": { ... }
}
```

{% endtab %}
{% endtabs %}

### 7. **Get Block by Number**

Fetches the details of a block using its block number.

{% tabs %}
{% tab title="Query" %}

* Example Query&#x20;

```
query: "Fetch details of the latest block"
```

**Function Name**: `GetBlocksByNumber`

* **Function Argument**:

  ```json
  {
    "blockNumbers": ["latest"],
    "txDetail": false
  }
  ```

{% endtab %}

{% tab title="Response" %}

```json
{
  "status": "Success",
  "action": "GetBlocksByNumber",
  "message": "Retrieved information for blocks",
  "data": { ... }
}
```

{% endtab %}
{% endtabs %}

### 8. **Get Transaction Status**

Fetches the status of a transaction using its hash.

{% tabs %}
{% tab title="Query" %}

* Example Query&#x20;

```
query: "What is the status of transaction 0xTransactionHash?"
```

**Function Name**: `GetTransactionStatus`

* **Function Argument**:

  ```json
  {
    "txHash": "0xTransactionHash"
  }
  ```

{% endtab %}

{% tab title="Response" %}

```json
{
  "status": "Success",
  "action": "GetTransactionStatus",
  "message": "Transaction status: Success",
  "data": { ... }
}
```

{% endtab %}
{% endtabs %}

### 9. Wrapping zkCRO

Wraps zkCRO tokens into wrapped tokens.

{% tabs %}
{% tab title="Query" %}

* Example Query&#x20;

```
query: "Wrap 100 zkCRO tokens"
```

**Function Name**: `WrapToken`

* **Function Argument**:

  ```json
  {
    "amount": 100
  }
  ```

{% endtab %}

{% tab title="Response" %}

```json
{
  "status": "Success",
  "action": "WrapToken",
  "message": "Signature URL created successfully. Please sign the transaction on this link.",
  "data": {
    "magicLink": "http://{provider}/wrap-token/{transactionId}?token={token}"
  }
}
```

{% endtab %}
{% endtabs %}

**Note:** This function returns a magic link. [Read more about Magic Link](/crypto.com-ai-agent-sdk/ai-agent-sdk-examples/magic-link-signer).

### **10. Swap Token**

Swaps one token into another (e.g., zkCRO to VUSD).

{% tabs %}
{% tab title="Query" %}

* Example Query&#x20;

```
query: "Swap 100 zkCRO tokens to VUSD"
```

**Function Name**: `SwapToken`

* **Function Argument**:

  ```json
  {
    "amount": 100
  }
  ```

{% endtab %}

{% tab title="Response" %}

```json
{
  "status": "Success",
  "action": "SwapToken",
  "message": "Signature URL created successfully. Please sign the transaction on this link.",
  "data": {
    "magicLink": "http://{provider}/swap-token/{transactionId}?token={token}"
  }
}
```

{% endtab %}
{% endtabs %}

**Note:** This function returns a magic link. [Read more about Magic Link](/crypto.com-ai-agent-sdk/ai-agent-sdk-examples/magic-link-signer).


# Using Crypto.com AI Agent with Gemini

A guide to using the Crypto.com AI Agent with Google's Gemini model for blockchain interactions.

### Quick Start

#### 1. Setup

Start by cloning the repository and navigating to the appropriate directory, and install the dependencies:

```bash
# Clone the repository
git clone git@github.com:crypto-com/developer-platform-sdk-examples.git
cd developer-platform-sdk-examples/ai/cryptocom-ai-agent-pychatbot

# Install dependencies
pip install -r requirements.txt
```

<figure><img src="/files/KTogdeiUtv7lARaBPcN6" alt=""><figcaption></figcaption></figure>

#### 2. Configure API Keys

Direct to `Env`and set up the following API keys in your environment:

* `OPENAI_API_KEY` - For OpenAI functionality
* `GOOGLE_API_KEY` - For Gemini functionality
* `GOOGLE_PROJECT_ID`  - For Gemini functionality&#x20;

#### 3. Launch the Chat

```bash
python chat.py
```

<figure><img src="/files/fi1p0KieM9zNu1nL5Wqf" alt=""><figcaption></figcaption></figure>

When prompted, select `gemini` as your AI provider. <br>

### API Examples

#### Query Latest Block using Gemini

```bash
curl -X POST http://localhost:8000/api/v1/cdc-ai-agent-service/query \
-H "Content-Type: application/json" \
-d '{
  "query": "get latest block",
  "options": {
    "gemini": {
      "apiKey": "YOUR_GOOGLE_API_KEY"
    },
    "llmProvider": "gemini",    
    "context": []
  }
}'
```

#### Query Latest Block using OpenAI

```bash
curl -X POST http://localhost:8000/api/v1/cdc-ai-agent-service/query \
-H "Content-Type: application/json" \
-d '{
  "query": "get latest block",
  "options": {
    "openAI": {
      "apiKey": "YOUR_OPENAI_API_KEY"
    },
    "llmProvider": "openai",
    "context": []
  }
}'
```


# Self-Hosting AI-Agent-Server

### Introduction

By following this example, we will be able to self-host the AI element of the SDK, specifically the `AI agent client`, independently. This offers developers and projects greater control and flexibility compared to using the AI agent API directly. Underneath, the AI agent client utilizes the package to obtain data and interact with Cronos Chains. The example is fully opensource and can be found in this [repository](https://github.com/crypto-com/developer-platform-sdk-examples/tree/main/ai/cryptocom-ai-agent-service)<br>

Step 1 - Clone the repository:

```
git clone https://github.com/crypto-com/developer-platform-sdk-examples.git
cd developer-platform-sdk-examples/ai/cryptocom-ai-agent-service
```

#### Step 2 - **Install dependencies**:

```
npm install
```

**Step 3 - Create a `.env` file with the following content:**

```
NODE_ENV=development
EXPLORER_API_KEY=<Explorer_API_Key>
```

{% hint style="info" %}
We can follow the guide in [Resources for Developers](/resources/resources-for-developers#explorer-api-keys) to obtain our `Explorer_API_Key`, the explorer API keys of different Cronos chains
{% endhint %}

{% hint style="info" %}
The example is configured for the ***Cronos zkEVM Testnet.*** When connecting to another network, please update the chain in [Client.init](https://github.com/crypto-com/developer-platform-sdk-examples/blob/main/ai/cryptocom-ai-agent-service/src/services/agent/agent.service.ts#L33) within `agent.service.ts` accordingly.

```javascript
// Cronos EVM mainnet
CronosEvm.Mainnet 
// Cronos EVM testnet
CronosEvm.Testnet
// Cronos zkEVM mainnet
CronosZkEvm.Mainnet
```

{% endhint %}

**Step 4 - Run the development server / Production build:**

**Run the development server by**

```
npm run dev
```

Once done, the `AI agent client` will be running under `localhost:8000`

OR&#x20;

**Production build by**&#x20;

```
npm run build
npm start
```

Afterwards, we can interact with the `AI agent client` in a similar manner&#x20;

***

### API Endpoints

#### Health Check

* **Endpoint**: `/healthcheck`
* **Method**: `GET`
* **Description**: Returns the uptime and health status of the service.
* **Response Example**:

  ```
  {
    "status": "success",
    "result": {
      "uptime": 120.34,
      "responsetime": [0, 252939],
      "message": "OK",
      "timestamp": 1632846348163
    }
  }
  ```

#### Query Route

{% hint style="info" %}
More query example can be found in [Functions and Example Queries of AI agent services](/outdated-contents/functions-and-example-queries-of-ai-agent-services)
{% endhint %}

* **Endpoint**: `/api/v1/cdc-ai-agent-service/query`
* **Method**: `POST`
* **Description**: Takes a natural language query, maps it to a blockchain command via OpenAI, and executes the command.
* **Request Body Example**:

  <pre><code>{
    "query": "get latest block",
    "options": {
      "openAI": {
        "apiKey": "&#x3C;your-openai-api-key>"
      },
  <strong>    "chain": {
  </strong>      "id": "388",
        "name": "cronos-zkevm-testnet",
        "rpc": "https://testnet.zkevm.cronos.org"
      },
      "explorer": {
        "apiKey": "&#x3C;your-explorer-api-key>"
      }
    }
  }
  </code></pre>
* **Response Example**:

  ```
  {
    "status": "success",
    "result": {
      "action": "getBlock",
      "message": "Retrieved latest block",
      "data": {
        "blockNumber": 123456,
        "timestamp": "2023-09-12T10:12:15Z"
      }
    }
  }

  ```

#### **Querying with DeepSeek Model**

* **Endpoint**: `/api/v1/cdc-ai-agent-service/query`
* **Method**: `POST`
* **Description**: Takes a natural language query, maps it to a blockchain command via DeepSeek, and executes the command.
* **Request Body Example**:

  ```
  {
    "query": "get latest block",
    "options": {
      "deepSeek": {
        "apiKey": "<your-deepseek-api-key>",
        "model": "deepseek-chat"
      },
      "llmProvider": "deepseek",
      "chain": {
        "id": "388",
        "name": "cronos-zkevm-testnet",
        "rpc": "https://testnet.zkevm.cronos.org"
      },
      "explorer": {
        "apiKey": "<your-explorer-api-key>"
      }
    }
  }
  ```
* **Response Example**:

  ```
  {
    "status": "success",
    "result": {
      "action": "getBlock",
      "message": "Retrieved latest block",
      "data": {
        "blockNumber": 123456,
        "timestamp": "2023-09-12T10:12:15Z"
      }
    }
  }
  ```

#### **Querying with M**istral **Models**

* **Endpoint**: `/api/v1/cdc-ai-agent-service/query`
* **Method**: `POST`
* **Description**: Takes a natural language query, maps it to a blockchain command via DeepSeek, and executes the command.
* Supported models: `ministral-3b-latest`, `ministral-8b-latest`, `mistral-large-latest`, `mistral-small-latest`
* **Request Body Example With** `mistral-large-latest` :

  ```
  {
    "query": "get latest block",
    "options": {
      "mistral": {
        "apiKey": "<your-mistral-api-key>",
        "model": "mistral-large-latest"
      },
      "llmProvider": "mistral",
      "chain": {
        "id": "388",
        "name": "cronos-zkevm-testnet",
        "rpc": "https://testnet.zkevm.cronos.org"
      },
      "explorer": {
        "apiKey": "<your-explorer-api-key>"
      }
    }
  }
  ```
* **Response Example**:

  ```
  {
    "status": "success",
    "result": {
      "action": "getBlock",
      "message": "Retrieved latest block",
      "data": {
        "blockNumber": 123456,
        "timestamp": "2023-09-12T10:12:15Z"
      }
    }
  }
  ```

## Experimental feature - Assigning a key to the AI Agent

{% hint style="warning" %}
Please note that the following is an experimental feature intended for demonstration purposes only. Use this feature with caution, as it may result in the loss of funds.
{% endhint %}

As introduced in this [pull request](https://github.com/crypto-com/developer-platform-sdk-examples/pull/12), developers can follow the [instructions](https://github.com/crypto-com/developer-platform-sdk-examples/pull/12/files#diff-8fdb674999321ed747ca07aa825782ce00251fe4a96ef303079243423e34495fR172) to assign a private key directly to the AI agent, enabling it to perform transactions on the user's behalf.

In particular, we need to update the `agent.service.ts` file and the `.env` file with additional variables, such as the key to be assigned, the RPC URL for transaction broadcasting (see [Resources for Developers](/resources/resources-for-developers#cronos-zkevm-sepolia-testnet-urls)) and the DEX router for swaping:&#x20;

```
NODE_ENV=development
EXPLORER_API_KEY=
PRIVATE_KEY=
RPC_URL=
DEX_ROUTER_ADDRESS=
```

<figure><img src="/files/L6dh4hqui7elCOi7cbxD" alt=""><figcaption><p>Example of an Agent performing a transfer using the key assigned with <a data-mention href="/pages/IcOR1LnbXYJzWImKS7gL">/pages/IcOR1LnbXYJzWImKS7gL</a></p></figcaption></figure>

Developers may also refer to the `experimental` branch of this [repository](https://github.com/lezzokafka/developer-platform-sdk-examples/tree/experimental/ai/cryptocom-ai-agent-service) for further reference.&#x20;


# More SDK Example Use Cases

Using the Crypto.com AI Agent SDK, we can integrate the AI Agent into various user interfaces of our choice, such as Telegram, Discord, or any custom UI. Examples of these integrations are shown below

#### [Querying On-Chain block data](https://x.com/i/status/1839491194151452813)

#### [Wallet management actions](https://x.com/i/status/1839246209468477465)

#### [Interacting with smart contracts / swapping tokens](https://x.com/i/status/1839618231021285839)


# Removed Functions

### AI Agent SDK

#### 3.2 Get transaction by address

Retrieve a list of transactions for the specified blockchain\
address from the Crypto.com developer platform within a specified block range.

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  address (str): The blockchain address to query (CronosIds with the `.cro` suffix are supported).
  startBlock (int): The starting block number to get transactions from. The maximum range is 10,000 blocks.
  endBlock (int): The ending block number to get transactions to. The maximum range is 10,000 blocks.
  session (str, optional): Session identifier for pagination. Defaults to "".
  limit (str, optional): Maximum number of transactions to return. Defaults to "20".
  ```
* Example Query

  ```
  "Get transactions of <example-address> from block <example-start-block> to <example-end-block>"
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  str: A formatted string containing the list of transactions.
  ```
* Example Response

  ```
  The transactions for the address <example-address> are:

  * Transaction 1: 
    - Block Number: <example-block-number>
    - Transaction Hash: <example-transaction-hash>
    - Status: <example-status>
    - From: <example-from>
    - To: <example-to>
    - Value: <example-value>

  * Transaction 2:
    ...
  ```

{% endtab %}
{% endtabs %}

Example Code

```python
from crypto_com_agent_client import Agent

agent = Agent.init(
    llm_config={
        "provider": "OpenAI",
        "model": "gpt-4",
        "provider-api-key": "sk-proj-example-key",
        "temperature": "float-controlling-output-randomness",
    },
    blockchain_config={
        "api-key": "your-crypto.com-developer-platform-api-key",
        "private-key": "your-private-key",
        "sso-wallet-url": "your-sso-wallet-url",
        "timeout": "timeout-in-seconds-for-API-calls-default-20s")
    },
)
response = agent.interact("Get transactions of <example-address> from block <example-start-block> to <example-end-block>")
print(response)
```

### Developer Platform Client SDK

#### 3.1 Get Transactions By Address

Fetches transactions for a specific wallet address.

{% hint style="info" %}
**Note:** Click to see [how to get an explorer API key](/resources/resources-for-developers#explorer-api-keys).
{% endhint %}

{% tabs %}
{% tab title="Python" %}
Function Name

```python
get_transactions_by_address
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  address (str): The address to get transactions for (CronosIds with the `.cro` suffix are supported, e.g. `xyz.cro`)
  explorer_key (str): The explorer API key
  session (str): The session to get transactions for
  limit (str): The limit of transactions to get
  startBlock (Optional[int]): The starting block number to get transactions from. (The maximum number of blocks that can be fetched is 10,000)
  endBlock (Optional[int]): The ending block number to get transactions to. (The maximum number of blocks that can be fetched is 10,000)
  ```
* Example Code

  ```python
  from crypto_com_developer_platform_client import Transaction

  transations = Transaction.get_transactions_by_address('example-address', 'example-explorer-api-key')
  print(transations)
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  The transactions for the address.
  ```
* Errors

  ```python
  ValueError: If the Transaction class is not initialized with a Client instance.
  ```
* Example Return

  ```python
  { 'status': 'Success', 'data': { 'transactions': [ example-array ], 'pagination': { 'totalRecord': example-number, 'totalPage': example-number, 'currentPage': example-number, 'limit': example-number, 'session': 'example-session' } } }
  ```

{% endtab %}
{% endtabs %}
{% endtab %}

{% tab title="TypeScript" %}
Function Name

```typescript
getTransactionsByAddress
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```typescript
  {string} address: Wallet address (or CronosId `.cro`).
  {string} explorerKey: Blockchain explorer API key.
  {string} [session]: Pagination session.
  {string} [limit='20']: Result limit.
  {number} [startBlock]: Start block (optional).
  {number} [endBlock]: End block (optional).
  ```
* Example Code

  ```typescript
  import { Transaction } from '@crypto.com/developer-platform-client';

  const transactions = await Transaction.getTransactionsByAddress('example-address', 'example-explorer-api-key')

  console.log(transactions);
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```typescript
  {Promise<ApiResponse<TransactionsByAddress>>}: A promise that resolves to the transactions result
  ```
* Example Return

  ```typescript
  {
    status: 'Success',
    data: {
      transactions: [
  	example-array
      ],
      pagination: {
        totalRecord: example-number,
        totalPage: example-number,
        currentPage: example-number,
        limit: example-number,
        session: 'example-session'
      }
    }
  }
  ```

{% endtab %}
{% endtabs %}
{% endtab %}
{% endtabs %}

#### 5.1 Get Contract ABI

Fetches the ABI (Application Binary Interface) of a smart contract.

{% hint style="info" %}
**Note:** Click to see [how to get an explorer API key](/resources/resources-for-developers#explorer-api-keys).
{% endhint %}

{% tabs %}
{% tab title="Python" %}
Function Name

```python
get_contract_abi
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  contract_address (str): The address of the smart contract.
  explorer_key (str): The API key for the blockchain explorer (either Cronos or Cronos zkEVM).
  ```
* Example Code

  ```python
  from crypto_com_developer_platform_client import Contract

  abi = Contract.get_contract_abi('example-contract', 'example-explorer-api-key')
  print(abi)
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  The ABI of the smart contract.
  ```
* Errors

  ```python
  ValueError: If the Contract class is not initialized with a Client instance.
  ```
* Example Return

  ```python
  {'status': 'Success', 'data': {'abi': ['example-abi']}}
  ```

{% endtab %}
{% endtabs %}
{% endtab %}

{% tab title="TypeScript" %}
Function Name

```typescript
getContractABI
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```typescript
  {string} contractAddress: The smart contract address.
  {string} explorerKey: The API key for the blockchain explorer.
  ```
* Example Code

  ```typescript
  import { Contract } from '@crypto.com/developer-platform-client';

  try {
    const abi = await Contract.getContractABI('example-address');
    console.log(abi);
  }
    catch(err) {
    console.log(err);
  }
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```typescript
  {Promise<ApiResponse<ContractAbi>>}: A promise that resolves to the ABI of the contract.
  ```
* Errors

  ```typescript
  {Error} If the ABI retrieval fails.
  ```
* Example Return

  ```typescript
  {
    status: 'Success',
    data: {
      abi: [
  example-abi      
      ]
    }
  }
  ```

{% endtab %}
{% endtabs %}
{% endtab %}
{% endtabs %}


# Contract Operations

The AI Agent SDK simplifies smart contract interactions by allowing developers to fetch Contract ABI (Application Binary Interface) by providing a contract address. This feature enables seamless integration with smart contracts on Cronos Chains, making it easier to interact with deployed contracts and build powerful blockchain applications.

To learn more about the underlying Developer Platform functionalities, please visit [Developer Platform Client SDK Contract Module](/crypto.com-developer-platform/on-chain-developer-platform-client-sdk/contract-module).

#### 5.1 Get contract ABI

Retrieve the ABI for a specified smart contract using the Crypto.com developer platform.

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  contract_address (str): The address of the smart contract.
  ```
* Example Query

  ```
  "Get contract ABI of <example-contract-address>"
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  str: A formatted string containing the ABI of the smart contract.
  ```
* Example Response

  ````
  The ABI for the contract at address <example-contract-address> is as follows:
  ```json
  <example-abi>
  ```
  This ABI includes the contract's constructor, events, and functions, providing the necessary information to interact with the contract on the blockchain.
  ````

{% endtab %}
{% endtabs %}

Example Code

```python
from crypto_com_agent_client import Agent

agent = Agent.init(
    llm_config={
        "provider": "OpenAI",
        "model": "gpt-4",
        "provider-api-key": "sk-proj-example-key",
        "temperature": "float-controlling-output-randomness",
    },
    blockchain_config={
        "api-key": "your-crypto.com-developer-platform-api-key",
        "private-key": "your-private-key",
        "sso-wallet-url": "your-sso-wallet-url",
        "timeout": "timeout-in-seconds-for-API-calls-default-20s")
    },
)
response = agent.interact("Get contract ABI of <example-contract-address>")
print(response)
```


# AI Agent SDK

*Empower your dApp with AI-driven blockchain interactions*

Crypto.com AI Agent SDK is a powerful tool that enables developers to seamlessly integrate AI capabilities into their Web3 projects.&#x20;

With the PyPi and NPM packages, you can create AI agents that can create blockchain interactions, opening up a world of possibilities for your applications.

***

### Overview

*Best-in-class AI Blockchain Tool*

* ***Effortlessly Create AI-Driven Features***

  Our embedded LLM models[^1] serve as an intermediary layer, intelligently matching and executing the right functions and calls for both developers and end-users. This empowers non-technical users to engage with complex blockchain actions seamlessly.
* ***Seamless integration with the Cronos Ecosystem***

  The SDK is designed to integrate effortlessly with existing Cronos services, including public RPC endpoints, in-house explorers, and their APIs, providing a comprehensive toolkit for developers.
* ***Simplified Development***\
  Our SDK allows for seamless integration with a wide range of client-side applications, including frontend apps, messaging platforms like Telegram and Discord, and even terminal interfaces. This flexibility empowers developers to choose their preferred frontend solution, streamlining the integration process and enabling them to focus on building innovative applications.

### Use Cases

Our AI agent product is revolutionizing the way we interact with blockchain technology. By harnessing the power of natural language processing and machine learning, we're enabling developers to build innovative applications that simplify complex blockchain actions. Here are just a few examples of the exciting use cases our product makes possible:

1. **Blockchain Data Queries**\
   Imagine being able to ask questions like "What's the current market capitalization of Ethereum?" or "What's the average transaction fee on the Bitcoin network?" and receiving accurate, up-to-date answers in seconds. Crypto.com AI agent can transform user questions into actionable blockchain queries, generating valuable insights on market trends and implications.
2. **Wallet Management**\
   Managing cryptocurrency wallets can be a daunting task, especially for newcomers to the space. Crypto.com AI agent makes it easy to create crypto wallets, execute transfers, and manage addresses using simple text commands. In the future, we'll also be adding support for multi-signature wallets and account abstraction.
3. **Portfolio Management**\
   With our SDK, developers can create and deploy smart contracts that interact directly with AI-driven trading insights. This enables automated execution of trades based on real-time market analysis, giving users a significant edge in the market. For example, imagine building a portfolio management application that uses machine learning algorithms to analyze market trends and automatically execute trades when certain conditions are met.
4. ***Content Monetization***\
   Our AI agent product also enables developers to extend their current AI functionalities to include blockchain features. Imagine being able to embed crypto payments into shopping, travel services, subscriptions, and more. For instance, a travel booking platform could use our AI agent to accept cryptocurrency payments and automatically convert them into fiat currency, streamlining the booking process for users.

These are just a few examples of the many exciting use cases our AI agent product makes possible. By harnessing the power of AI-driven blockchain interactions, developers can build innovative applications that simplify complex blockchain actions and unlock new possibilities for users.

### Get Started

To start building with the AI Agent SDK, begin by exploring the foundational guide to understand its core functionalities: \
[Quick Start Guide: Simulation Entry Point](/crypto.com-ai-agent-sdk/quick-start-guide-simulation-entry-point)\
\
Then check out the [Examples](/crypto.com-ai-agent-sdk/ai-agent-sdk-examples) section to find use cases that best fit your application.

By leveraging these resources, you can customize and integrate this AI-driven agent into your Web3 applications, enabling automated chain interactions and enhancing the user experience.\
\
Join [our community](https://t.me/cryptocom_agent), follow our [X account](https://x.com/cryptocom_agent), and discover the limitless possibilities of AI and blockchain integration with the AI Agent SDK.

[^1]:


# Quick Start Guide: Simulation Entry Point

### **Introduction**

This file serves as a simulation and testing entry point for the Crypto.com Agent Client. It demonstrates how to initialize the agent, configure plugins, and interact with the LangGraph-based conversational AI.

### Overview

The simulation provides a controlled environment to experiment with the Crypto.com AI Agent’s capabilities before integrating it into real-world applications, configuring it with a large language model (LLM) and blockchain settings to enable seamless interactions. It integrates various plugins, including LangFuse for observability, SQLite for persistent storage, and custom tools for enhanced functionality. &#x20;

Additionally, the script features an interactive CLI-based testing loop, allowing developers to validate AI-driven blockchain interactions in real time which makes it a powerful tool for experimentation and development.

### Key Features

* Agent initialization with LLM and blockchain configurations.
* Plugin integration (LangFuse, SQLite for storage, and custom tools).
* Interactive CLI loop for testing agent responses.

### Prerequisites

Before starting, ensure you have the following components ready.&#x20;

1. Python installed (version ≥ 3.12)
2. API Key for Crypto.com Developer Platform, [click here to learn how to obtain your Crypto.com Developer Platform API key](/crypto.com-developer-platform/developer-platform-dashboard).
3. API Keys of AI provider, refer to the [Dynamic AI Model Manager ](/crypto.com-ai-agent-sdk/core-concepts-overview/dynamic-ai-model-manager)to see which providers are supported by the AI Agent SDK. Only the API keys for the selected AI provider are required when initializing the agent.
4. For Windows Users:
   1. Windows 10 SDK or Windows 11 SDK depends on system version
   2. MSVC v143 - C++ x64/86 build tools

### Get Started&#x20;

Step 1 - Run this with the following command or to [this Pypi Package page](https://pypi.org/project/cryptocom-agent-client/).

```python
pip install cryptocom-agent-client
```

Step 2 - Before running the script, ensure that all configurations are properly set up: Replace placeholders such as `your-api-key` with valid credentials to enable proper functionality. Then run the python file to initialize the bot.

#### Simulation Example Code

{% tabs %}
{% tab title="OpenAI as Provider" %}

```python
from crypto_com_agent_client import Agent, SQLitePlugin, tool, DefaultMemoryConfigs

# (OPTIONAL) Use SQLiteStorage for persistence
custom_storage = SQLitePlugin(db_path="agent_state.db")

# (OPTIONAL) LangFuse plugin configuration
user_langfuse_handler = {
    "public-key": "user-public-key",
    "secret-key": "user-secret-key",
    "host": "https://langfuse.example.com",
}

# (OPTIONAL) Custom personality and character
personality = {
    "tone": "friendly",
    "language": "German",
    "verbosity": "high",
}
# (OPTIONAL)
instructions = (
    "You are a humorous assistant that always includes a joke in your responses."
)

# (OPTIONAL)
@tool
def get_weather(location: str) -> str:
    """
    Provide the current weather for a given location.

    Args:
        location (str): The name of the location for which to retrieve weather information.

    Returns:
        str: A message describing the current weather in the given location.
    """
    # Simulated weather response for demonstration purposes
    weather_data = {
        "New York": "sunny, 25°C",
        "Berlin": "cloudy, 18°C",
        "Tokyo": "rainy, 22°C",
    }

    weather = weather_data.get(location, "unavailable at the moment")
    return f"The current weather in {location} is {weather}."

# Initialize the agent with LLM and blockchain configurations
agent = Agent.init(
    llm_config={
        "provider": "OpenAI",
        "model": "gpt-4o-mini",
        "provider-api-key": "your-api-key",
        "temperature": 0.7, # This parameter controls the randomness and creativity of the generated text.
        "transfer-limit": -1,  # -1 means no limit (unlimited), 0 disables transfers completely, any positive number (e.g. 5) allows exactly that transfer amount
    },
    blockchain_config={
        "api-key": "your-crypto.com-developer-platform-api-key",
        "private-key": "your-private-key",
        "sso-wallet-url": "your-sso-wallet-url",
        "timeout": "timeout-in-seconds-for-API-calls-default-20s")
    },
    plugins={
        "personality": {
            "tone": "friendly",
            "language": "English",
            "verbosity": "high",
        },
        "instructions": "You are a humorous assistant that always includes a joke in your responses.",
        "tools": [get_weather],
        "storage": custom_storage,
        "memory_config": DefaultMemoryConfigs.balanced(), # Setting to optimize token usage and manage conversation memory in AI agents.
    },
)

# Run the Graph Interactively
# Interactive CLI loop for testing
if __name__ == "__main__":
    print("Welcome to the interactive Crypto.com Agent! Type 'exit' to quit.\n")

    while True:
        user_input = input("You: ")
        if user_input.lower() == "exit":
            print("Goodbye!")
            break

        # Get the agent's response
        response = agent.interact(user_input)
        print(f"Agent: {response}\n")

```

{% endtab %}

{% tab title="Gemini as Provider " %}

```python
from crypto_com_agent_client import Agent, SQLitePlugin, tool

# (OPTIONAL) Use SQLiteStorage for persistence
custom_storage = SQLitePlugin(db_path="agent_state.db")

# (OPTIONAL) LangFuse plugin configuration
user_langfuse_handler = {
    "public-key": "user-public-key",
    "secret-key": "user-secret-key",
    "host": "https://langfuse.example.com",
}

# (OPTIONAL) Custom personality and character
personality = {
    "tone": "friendly",
    "language": "German",
    "verbosity": "high",
}
# (OPTIONAL)
instructions = (
    "You are a humorous assistant that always includes a joke in your responses."
)

# (OPTIONAL)
@tool
def get_weather(location: str) -> str:
    """
    Provide the current weather for a given location.

    Args:
        location (str): The name of the location for which to retrieve weather information.

    Returns:
        str: A message describing the current weather in the given location.
    """
    # Simulated weather response for demonstration purposes
    weather_data = {
        "New York": "sunny, 25°C",
        "Berlin": "cloudy, 18°C",
        "Tokyo": "rainy, 22°C",
    }

    weather = weather_data.get(location, "unavailable at the moment")
    return f"The current weather in {location} is {weather}."

# Initialize the agent with LLM and blockchain configurations
agent = Agent.init(
    llm_config={
        "provider": "GoogleGenAI",
        "model": "gemini-2.0-flash",
        "provider-api-key": "your-api-key",
        "temperature": 0.7, # This parameter controls the randomness and creativity of the generated text.
        "transfer-limit": -1,  # -1 means no limit (unlimited), 0 disables transfers completely, any positive number (e.g. 5) allows exactly that transfer amount
    },
    blockchain_config={
        "api-key": "your-crypto.com-developer-platform-api-key",
        "private-key": "your-private-key",
        "sso-wallet-url": "your-sso-wallet-url",
        "timeout": "timeout-in-seconds-for-API-calls-default-20s")
    },
    plugins={
        "personality": {
            "tone": "friendly",
            "language": "English",
            "verbosity": "high",
        },
        "instructions": "You are a humorous assistant that always includes a joke in your responses.",
        "tools": [get_weather],
        "storage": custom_storage,
        "memory_config": DefaultMemoryConfigs.balanced(), # Setting to optimize token usage and manage conversation memory in AI agents.
    },
)

# Run the Graph Interactively
# Interactive CLI loop for testing
if __name__ == "__main__":
    print("Welcome to the interactive Crypto.com Agent! Type 'exit' to quit.\n")

    while True:
        user_input = input("You: ")
        if user_input.lower() == "exit":
            print("Goodbye!")
            break

        # Get the agent's response
        response = agent.interact(user_input)
        print(f"Agent: {response}\n")

```

{% endtab %}
{% endtabs %}

### **What’s Next?**

This Quick Start provide a foundation. To dive deeper, refer to the [Examples](/crypto.com-developer-platform/developer-platform-client-sdk-examples) section for more use cases and advanced scenarios​ that suit your interest, including building your own Telegram bot, AI Agent Chatbot, "Magic Link" Signer and more.\
\
Visit the [API Reference](/resources/resources-for-developers) for detailed information on available functionalities.


# Core Concepts Overview

### Crypto.com AI Agent SDK&#x20;

The AI Agent SDK extends blockchain functionality by bridging natural language processing (NLP) with blockchain interactions to make it easier for users to execute blockchain actions through AI-driven commands.

The AI Agent SDK integrates pre-built blockchain functions from the Crypto.com Developer Platform SDK, allowing AI-driven blockchain operations. The AI component acts as an interpreter, translating user queries into blockchain function calls, allowing users to interact with the blockchain effortlessly. It translates user queries into corresponding tool function calls which bring easier user-blockchain interactions.

With the AI Agent SDK, users can:

* Query blockchain data (e.g., latest blocks, transactions, market trends).
* Execute on-chain actions (e.g., token transfers, contract interactions).

Manage wallets using natural language commands.

### Plugin Features

The AI Agent SDK includes extensive plugin support, allowing developers to enhance and customize their AI-driven applications:

* SQLite Plugin: provides local state persistence, ensuring session continuity.
* LangFuse: enables real-time telemetry and interaction monitoring for performance tracking.
* Personality Plugin: allows customization of the agent’s personality and response style.
* Instructions Plugin: enables modification of agent behavior through customized instructions.
* Telegram Plugin: allows users to connect the agent to their Telegram bot with just a few lines of code.

By leveraging these plugins, developers can tailor AI-powered blockchain interactions to meet their specific needs, whether for DeFi applications, NFT marketplaces, or on-chain analytics.

### System Flow

Crypto.com AI Agent SDK simplifies blockchain interactions by acting as a bridge between users, AI models, and the Cronos blockchain.

<figure><img src="/files/v8nlMo6QM4ae4mGqfWwZ" alt=""><figcaption></figcaption></figure>

Below is a step-by-step breakdown of how the system functions.

1. **User Interaction**\
   A user interacts with the AI-powered application via natural language queries (e.g., “What is the latest block for Cronos EVM Chain?” or “Transfer 10 CRO to Alice.cro”).
2. **AI Processing**\
   The AI Agent SDK interprets the user’s query using AI models (such as OpenAI, Google, or Llama). It converts the request into structured blockchain commands.\
   To organize actions and decision-making, the AI Agent SDK leverages LangGraph, a graph-based execution framework. LangGraph structures the agent’s logic, enabling it to determine the correct sequence of actions, manage dependencies, and execute workflows efficiently.
3. **Function Execution**  \
   The AI Agent SDK invokes relevant blockchain functions from the Developer Platform Client SDK, which executes API calls to interact with the Cronos EVM or Cronos zkEVM chain.
4. **Blockchain Processing & Response**

   The Cronos blockchain processes the requested action (e.g., retrieving a block, executing a transaction). The Developer Platform Client SDK retrieves the response and passes it back to the AI Agent SDK.
5. **Enhancements via Plugins**

   The AI Agent SDK supports several plugins that enhance functionality and customization.&#x20;

   * The SQLite Plugin: stores AI session data, ensuring continuity between user interactions.&#x20;
   * The LangFuse Plugin: tracks AI interactions and logs them for observability and debugging, helping developers monitor and improve system performance.
   * The Personality Plugin: customizes AI-generated responses and developers can adjust tone, response style, and engagement levels to better fit their application’s needs.
   * Telegram Plugin - builds Telegram bot that interacts with the Cronos network.
6. **User Receives Response**\
   The AI-powered application returns a human-readable response, simplifying complex blockchain interactions for the user.<br>


# Blockchain Functions

### Introduction

The AI Agent SDK integrates various functions from the Crypto.com On-Chain Developer Platform Client SDK as tools. These special tools serve as pre-built blockchain-related functions, which enable developers to interact with Cronos Chains in an easier way. <br>

The SDK offers a wide range of features, including:

* **Wallet Management**: \
  Create wallets, check balances, and use SSO wallet integration for a seamless user experience.
* **Token Interactions**: \
  Retrieve token balances (native & ERC20), perform transfers, wrapping, and swapping.
* **On-Chain Queries**: \
  Access transaction details, fetch blocks by tag or number, fetch smart contracts ABI, and resolve CronosID.
* **DeFi Features**: \
  Retrieve whitelisted tokens, explore available farms, and obtain detailed farm information from specified DeFi protocols.
* **Exchange Integration:**&#x20;

  Access real-time market data and trading pair information from the Crypto.com Exchange.

## Functions and Examples

Below section provides detailed information on these blockchain functions and example interactions, guiding developers on how to effectively interact with Cronos Chains using the AI Agent SDK.

{% content-ref url="/pages/OVgisxErFogYIV9YI5ki" %}
[Wallet Management](/crypto.com-ai-agent-sdk/core-concepts-overview/blockchain-functions/wallet-management)
{% endcontent-ref %}

{% content-ref url="/pages/kgwH91z90AaIstz5EuSO" %}
[Token Interaction](/crypto.com-ai-agent-sdk/core-concepts-overview/blockchain-functions/token-interaction)
{% endcontent-ref %}

{% content-ref url="/pages/EFzCyfUxwnYWe7yNxTHp" %}
[Transaction Queries](/crypto.com-ai-agent-sdk/core-concepts-overview/blockchain-functions/transaction-queries)
{% endcontent-ref %}

{% content-ref url="/pages/CNdbATEgTt157pqBRuG3" %}
[Block Information](/crypto.com-ai-agent-sdk/core-concepts-overview/blockchain-functions/block-information)
{% endcontent-ref %}

{% content-ref url="/pages/Kugfc04XoGUpVzF1Ylae" %}
[CronosID Operations](/crypto.com-ai-agent-sdk/core-concepts-overview/blockchain-functions/cronosid-operations)
{% endcontent-ref %}

{% content-ref url="/pages/1zLmXeSYVbgHU6Hc1guD" %}
[Defi Operations](/crypto.com-ai-agent-sdk/core-concepts-overview/blockchain-functions/defi-operations)
{% endcontent-ref %}

{% content-ref url="/pages/3dADbnu3pe32tHSCZuIx" %}
[Crypto.com Exchange](/crypto.com-ai-agent-sdk/core-concepts-overview/blockchain-functions/crypto.com-exchange)
{% endcontent-ref %}


# Wallet Management

The SDK includes essential wallet features, such as wallet creation, balance checks, and support for Single Sign-On (SSO) wallets. These functionalities simplify dApp development and blockchain interactions.&#x20;

With just a few lines of code, developers can integrate wallet management capabilities into their AI agents, which makes it easier to build decentralized applications with enhanced blockchain interaction.

To learn more about the underlying Developer Platform functionalities, please visit [Developer Platform Client SDK Wallet Module](/crypto.com-developer-platform/on-chain-developer-platform-client-sdk/wallet-module).

{% hint style="warning" %}
**Security Warning: Private Key Storage**\
Private keys generated and stored locally on a developer's or end-user's machine may be exposed to compromise due to inadequate protection of the local environment. If the machine is infected with malware, improperly secured, or lacks encryption and access controls, unauthorized parties could gain access to the private key material. This could result in irreversible loss of digital assets, unauthorized transactions, or compromise of wallet integrity.
{% endhint %}

#### 1.1 Create wallet

Create a new blockchain wallet. It retrieves the wallet's address and private key using the Crypto.com developer platform.

{% tabs %}
{% tab title="Query" %}

* Example Query

  ```
  "Create a wallet"
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  <pre class="language-python"><code class="lang-python"><strong>str: A formatted string containing the wallet's address and private key.
  </strong></code></pre>
* Example Response

  ```
  A new wallet has been created successfully. Here are the details:
  - Wallet Address: <example-address>
  - Private Key: <example-private-key>
  Please ensure to store the private key securely, as it is essential for accessing your wallet.
  ```

{% endtab %}
{% endtabs %}

Example Code

```python
from crypto_com_agent_client import Agent

agent = Agent.init(
    llm_config={
        "provider": "OpenAI",
        "model": "gpt-4o-mini",
        "temperature": 1,
        "provider-api-key": "sk-proj-example-key",
        "temperature": "float-controlling-output-randomness",
        "transfer-limit": -1,  # -1 means no limit (unlimited), 0 disables transfers completely, any positive number (e.g. 5) allows exactly that transfer amount
    },
    blockchain_config={
        "api-key": "your-crypto.com-developer-platform-api-key",
        "private-key": "your-private-key",
        "sso-wallet-url": "your-sso-wallet-url",
        "timeout": "timeout-in-seconds-for-API-calls-default-20s")
    },
)

response = agent.interact("Create a wallet")
print(response)
```

#### 1.2 Get Wallet Balance

Retrieve the balance of a specified wallet address.

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  address (str): The address to get the balance for (e.g., "xyz.cro").
  ```
* Example Query

  ```
  "Get wallet balance of <example-wallet-address>"
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  str: A formatted string containing the wallet balance.
  ```
* Example Response

  ```
  The wallet balance for address <example-wallet-address> is <example-balance>.
  ```

{% endtab %}
{% endtabs %}

Example Code

```python
from crypto_com_agent_client import Agent
agent = Agent.init(
    llm_config={
        "provider": "OpenAI",
        "model": "gpt-4o-mini",
        "provider-api-key": "sk-proj-example-key",
        "temperature": 1,
        "transfer-limit": -1,  # -1 means no limit (unlimited), 0 disables transfers completely, any positive number (e.g. 5) allows exactly that transfer amount
    },
    blockchain_config={
        "api-key": "your-crypto.com-developer-platform-api-key",
        "private-key": "your-private-key",
        "sso-wallet-url": "your-sso-wallet-url",
        "timeout": "timeout-in-seconds-for-API-calls-default-20s")
    },
)

response = agent.interact("Get wallet balance of <example-wallet-address>")
print(response)
```

#### 1.3 Send via SSO Wallet

Generate a URL that can be used to initiate a token transfer through the SSO wallet interface. If "null" is specified as the receiver, it will use the null address (`0x0000000000000000000000000000000000000000`).

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  receiver (str): The recipient's blockchain address or "null" for null address.
  amount (int): The amount of tokens to transfer in Wei.
  data (str, optional): Additional data for the transfer. Defaults to "0x"
  ```
* Example Query

  ```
  "Send <example-amount> Wei to <example-recipient> with data <example-data> through sso wallet"
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  str: A formatted URL for the SSO wallet transfer.
  ```
* Example Response

  ```
  The token transfer has been initiated. 
  You can use the following URL to complete the transaction through the SSO wallet:
  [Transfer Token](None/transfer-token?recipient=<example-recipient>&amount=<example-amount>&data=<example-data>)
  Please follow the link to proceed with the transfer.
  ```

{% endtab %}
{% endtabs %}

Example Code

```python
from crypto_com_agent_client import Agent

agent = Agent.init(
    llm_config={
        "provider": "OpenAI",
        "model": "gpt-4o-mini",
        "provider-api-key": "sk-proj-example-key",
        "temperature": 1,
        "transfer-limit": -1,  # -1 means no limit (unlimited), 0 disables transfers completely, any positive number (e.g. 5) allows exactly that transfer amount
    },
    blockchain_config={
        "api-key": "your-crypto.com-developer-platform-api-key",
        "private-key": "your-private-key",
        "sso-wallet-url": "your-sso-wallet-url",
        "timeout": "timeout-in-seconds-for-API-calls-default-20s")
    },
)

response = agent.interact("Send <example-amount> Wei to <example-recipient> with data <example-data> through sso wallet")
print(response)
```


# Token Interaction

The AI Agent SDK offers powerful token interaction capabilities on the Cronos blockchain. It supports retrieving token balances for both native tokens and ERC20 tokens, performing token transfers, as well as wrapping and swapping tokens.

This comprehensive feature set makes it easy for developers to build AI agents that smoothly interact with tokens.

To learn more about the underlying Developer Platform functionalities, please visit [Developer Platform Client SDK Token Module](/crypto.com-developer-platform/on-chain-developer-platform-client-sdk/token-module).

#### 2.1 Get native balance

Query the native token balance for the specified blockchain address using the Crypto.com developer platform.

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  address (str): The blockchain address to query.
  ```
* Example Query

  ```
  "Get native balance of <example-address>"
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  str: A formatted string containing the native token balance for the address.
  ```
* Example Response

  ```
  The native balance for address <example-address> is <example-amount> CRO (CRO being the native token).
  ```

{% endtab %}
{% endtabs %}

Example Code

```python
from crypto_com_agent_client import Agent

agent = Agent.init(
    llm_config={
        "provider": "OpenAI",
        "model": "gpt-4o-mini",
        "temperature": 1,
        "provider-api-key": "sk-proj-example-key",
        "transfer-limit": -1,  # -1 means no limit (unlimited), 0 disables transfers completely, any positive number (e.g. 5) allows exactly that transfer amount
    },
    blockchain_config={
        "api-key": "your-crypto.com-developer-platform-api-key",
        "private-key": "your-private-key",
        "sso-wallet-url": "your-sso-wallet-url",
        "timeout": "timeout-in-seconds-for-API-calls-default-20s")
    },
)
response = agent.interact("Get native balance of <example-address>")
print(response)
```

#### 2.2 Get ERC20 Token Balance

Query the ERC20 token balance for the specified blockchain address and ERC20 contract address.

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  address (str): The blockchain address to query.
  contract_address (str): The contract address of the ERC20 token.
  ```
* Example Query

  ```
  "Get ERC20 balance of <example-address> in contract <example-contract>"
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  str: A formatted string containing the ERC20 token balance for the address.
  ```
* Example Response

  ```
  The ERC20 balance for address <example-address> in the contract <example-contract> is <example-amount> tokens.
  ```

{% endtab %}
{% endtabs %}

Example Code

```python
from crypto_com_agent_client import Agent

agent = Agent.init(
    llm_config={
        "provider": "OpenAI",
        "model": "gpt-4o-mini",
        "temperature": 1,
        "provider-api-key": "sk-proj-example-key",
        "transfer-limit": -1,  # -1 means no limit (unlimited), 0 disables transfers completely, any positive number (e.g. 5) allows exactly that transfer amount
    },
    blockchain_config={
        "api-key": "your-crypto.com-developer-platform-api-key",
        "private-key": "your-private-key",
        "sso-wallet-url": "your-sso-wallet-url",
        "timeout": "timeout-in-seconds-for-API-calls-default-20s")
    },
)
response = agent.interact("Get ERC20 balance of <example-address> in contract <example-contract>")
print(response)
```

#### 2.3 Transfer native token

Transfer native tokens (cro, CRO, tcro, tCRO, zkcro, zkCRO, zktcro, zkTCRO) to a specified address using the Crypto.com developer platform.

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  state (dict): The current state of the workflow.
  to (str): The recipient's blockchain address. 
  amount (float): The amount of native tokens to transfer.
  ```
* Example Query

  ```
  "Transfer <example-amount> CRO to <example-to>"
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  str: A formatted string confirming the success of the token transfer.
  ```
* Example Response

  ```
  The transfer of <example-amount> CRO to <example-to> was successful. 
  You can view the transaction details [here](<example-transaction-explorer-link>).
  ```

{% endtab %}
{% endtabs %}

Example Code

```python
from crypto_com_agent_client import Agent

agent = Agent.init(
    llm_config={
        "provider": "OpenAI",
        "model": "gpt-4o-mini",
        "temperature": 1,
        "provider-api-key": "sk-proj-example-key",
        "transfer-limit": -1,  # -1 means no limit (unlimited), 0 disables transfers completely, any positive number (e.g. 5) allows exactly that transfer amount
    },
    blockchain_config={
        "api-key": "your-crypto.com-developer-platform-api-key",
        "private-key": "your-private-key",
        "sso-wallet-url": "your-sso-wallet-url",
        "timeout": "timeout-in-seconds-for-API-calls-default-20s")
    },
)
response = agent.interact("Transfer <example-amount> CRO to <example-to>")
print(response)
```

#### 2.4 Transfer ERC20 token

Transfer ERC20 tokens to a specified address.&#x20;

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  state (dict): The current state of the workflow.
  to (str): The recipient's blockchain address. 
  amount (float): The amount of tokens to transfer. 
  token_symbol_or_address (str): The ERC20 token symbol or contract address.
  ```
* Example Query

  ```
  "Transfer <exmaple-amount> to <example-to> of contract <example-token>"
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  str: A formatted string confirming the success of the token transfer.
  ```
* Example Response

  ```
  The transfer of <exmaple-amount> to <example-to> of contract <example-token> was successful. 

  You can view the transaction details [here](<example-transaction-explorer-link>).
  ```

{% endtab %}
{% endtabs %}

Example Code

```python
from crypto_com_agent_client import Agent

agent = Agent.init(
    llm_config={
        "provider": "OpenAI",
        "model": "gpt-4o-mini",
        "temperature": 1,
        "provider-api-key": "sk-proj-example-key",
        "transfer-limit": -1,  # -1 means no limit (unlimited), 0 disables transfers completely, any positive number (e.g. 5) allows exactly that transfer amount
    },
    blockchain_config={
        "api-key": "your-crypto.com-developer-platform-api-key",
        "private-key": "your-private-key",
        "sso-wallet-url": "your-sso-wallet-url",
        "timeout": "timeout-in-seconds-for-API-calls-default-20s")
    },
)
response = agent.interact("Transfer <exmaple-amount> to <example-to> of contract <example-token>")
print(response)

```

#### 2.5 Wrap token

Wrap native tokens into wrapped tokens using the Crypto.com developer platform.

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  state (dict): The current state of the workflow.
  amount (float): The amount of native tokens to wrap.
  ```
* Example Query

  ```
  "Wrap <example-amount> CRO token"
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  str: A formatted string confirming the success of the wrapping operation.
  ```
* Example Response

  ```
  The CRO token wrapping was successful. 
  - Transaction Hash: <example-transaction-hash>
  - Transaction Link: [View Transaction](<example-transaction-explorer-link>)
  ```

{% endtab %}
{% endtabs %}

Example Code

```python
from crypto_com_agent_client import Agent

agent = Agent.init(
    llm_config={
        "provider": "OpenAI",
        "model": "gpt-4o-mini",
        "temperature": 1,
        "provider-api-key": "sk-proj-example-key",
        "transfer-limit": -1,  # -1 means no limit (unlimited), 0 disables transfers completely, any positive number (e.g. 5) allows exactly that transfer amount
    },
    blockchain_config={
        "api-key": "your-crypto.com-developer-platform-api-key",
        "private-key": "your-private-key",
        "sso-wallet-url": "your-sso-wallet-url",
        "timeout": "timeout-in-seconds-for-API-calls-default-20s")
    },
)
response = agent.interact("Wrap <example-amount> CRO token")
print(response)
```

#### 2.6 Swap token

Swap tokens between two different tokens.

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  state: The current state of the workflow.
  from_token_symbol_or_address (str): The symbol or contract address of the token to swap from.
  to_token_symbol_or_address (str): The symbol or contract address of the token to swap to.
  amount (float): The amount of tokens to swap.
  ```
* Example Query

  ```
  "Swap <example-amount> <example-from-token> for <example-to-token>"
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  str: A formatted string confirming the success of the token swap.
  ```
* Example Response

  ```
  The token swap of <example-amount> <example-from-token> for <example-to-token> was successful. 

  - Transaction Hash: [<example-transaction-hash>](<example-explorer-link>) 

  You can view the transaction details by clicking on the link.
  ```

{% endtab %}
{% endtabs %}

Example Code

```python
from crypto_com_agent_client import Agent

agent = Agent.init(
    llm_config={
        "provider": "OpenAI",
        "model": "gpt-4o-mini",
        "temperature": 1,
        "provider-api-key": "sk-proj-example-key",
        "transfer-limit": -1,  # -1 means no limit (unlimited), 0 disables transfers completely, any positive number (e.g. 5) allows exactly that transfer amount
    },
    blockchain_config={
        "api-key": "your-crypto.com-developer-platform-api-key",
        "private-key": "your-private-key",
        "sso-wallet-url": "your-sso-wallet-url",
        "timeout": "timeout-in-seconds-for-API-calls-default-20s")
    },
)
response = agent.interact("Swap <example-amount> <example-from-token> for <example-to-token>")
print(response)
```


# Transaction Queries

The AI Agent SDK enables efficient transaction management on Cronos Chains by providing features for querying transactions by address or hash. It also supports fetching transaction statuses, making it easy to track and verify blockchain activities accurately.

This functionality allows developers to build AI agents capable of monitoring and analyzing transactions in real-time, enhancing their applications' reliability and responsiveness.

To learn more about the underlying Developer Platform functionalities, please visit [Developer Platform Client SDK Transaction Module](/crypto.com-developer-platform/on-chain-developer-platform-client-sdk/transaction-module).

#### 3.1 Get transaction by hash

Retrieve transaction details for the specified hash using the Crypto.com developer platform.

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  hash (str): The hash of the transaction to retrieve.
  ```
* Example Query

  ```
  "Get transaction of transaction hash <example-hash>"
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  str: A formatted string containing the transaction details.
  ```
* Example Response

  ```
  The transaction details for the hash <example-hash> are as follows:

      Status: <example-status>
      Block Number: <example-block-number>
      From Address: <example-from>
      To Address: <example-to>
      Value: <example-value>
      Gas Price: <example-gas-price>
      Nonce: <example-nonce>
      Transaction Index: <example-transaction-index>  
      Gas Used: <example-gas-used>
  ```

{% endtab %}
{% endtabs %}

Example Code

```python
from crypto_com_agent_client import Agent

agent = Agent.init(
    llm_config={
        "provider": "OpenAI",
        "model": "gpt-4",
        "provider-api-key": "sk-proj-example-key",
        "temperature": "float-controlling-output-randomness",
        "transfer-limit": -1,  # -1 means no limit (unlimited), 0 disables transfers completely, any positive number (e.g. 5) allows exactly that transfer amount
    },
    blockchain_config={
        "api-key": "your-crypto.com-developer-platform-api-key",
        "private-key": "your-private-key",
        "sso-wallet-url": "your-sso-wallet-url",
        "timeout": "timeout-in-seconds-for-API-calls-default-20s")
    },
)
response = agent.interact("Get transaction of transaction hash <example-hash>")
print(response)
```

#### 3.2 Get transaction status

Retrieve the status of a transaction using its hash using the Crypto.com developer platform.

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  hash (str): The hash of the transaction to check.
  ```
* Example Query

  ```
  "Get transaction status of <example-transation-hash>"
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  str: A formatted string containing the transaction status.
  ```
* Example Response

  ```
  The transaction status for the hash <example-transation-hash> is <example-result>.
  ```

{% endtab %}
{% endtabs %}

Example Code

```python
from crypto_com_agent_client import Agent

agent = Agent.init(
    llm_config={
        "provider": "OpenAI",
        "model": "gpt-4",
        "provider-api-key": "sk-proj-example-key",
        "temperature": "float-controlling-output-randomness",
        "transfer-limit": -1,  # -1 means no limit (unlimited), 0 disables transfers completely, any positive number (e.g. 5) allows exactly that transfer amount
    },
    blockchain_config={
        "api-key": "your-crypto.com-developer-platform-api-key",
        "private-key": "your-private-key",
        "sso-wallet-url": "your-sso-wallet-url",
        "timeout": "timeout-in-seconds-for-API-calls-default-20s")
    },
)
response = agent.interact("Get transaction status of <example-transation-hash>")
print(response)
```


# Block Information

The AI Agent SDK provides robust block operation capabilities, allowing developers to fetch blocks by tag (e.g., latest, pending) or by specific block number on Cronos Chains.

This feature makes it easy to retrieve detailed block information, enabling seamless integration of real-time blockchain data into your AI-powered applications.

To learn more about the underlying Developer Platform functionalities, please visit [Developer Platform Client SDK Block Module](/crypto.com-developer-platform/on-chain-developer-platform-client-sdk/block-module).

#### 4.1 Get block by tag&#x20;

Retrieve block data for a specified tag using the Crypto.com developer platform.

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  tag (str): Integer of a block number in hex, or the string "earliest", "latest" 
  or "pending".
  tx_detail (str, optional): If "true", returns full transaction objects; 
  if "false", only transaction hashes.
  ```
* Example Query

  ```
  "Get <example-tag> block with detail"
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  str: A formatted string containing the block data.
  ```
* Example Response

  ```
  The latest block data with details is as follows:

    Block Number: <example-block-number> 
    Block Hash: <example-block-hash>
    Parent Hash: <example-parent-hash>
    Timestamp: <example-timestamp>
    Transactions Root: <example-transaction-root>
    Receipts Root: <example-receipts-root>
    State Root: <example-state-root>
    Gas Limit: <example-gas-limit>
    Gas Used: <example-gas-used>
    Miner: <example-miner>
    Difficulty: <example-difficulty>
    Total Difficulty: <example-total-difficulty>
    Gas Price: <example-gas-price>
    Base Fee Per Gas: <example-base-fee-per-gase>
    Nonce: <example-nonce>
    Transactions:
      Transaction Hash: <example-transaction-hash>
      From: <example-from>
      To: <example-to>
      Value: <example-value>
      Gas: <example-gas>
      Transaction Index: <example-transaction-index>
      Max Fee Per Gas: <example-max-fee-per-gas>
      Max Priority Fee Per Gas: <example-max-priority-fee-per-gas>

  This block contains a single transaction and has not been mined by a specific miner. The details also indicate that the block has a gas limit of approximately <example-number> trillion and has utilized around <example-percentage> of that limit. If you need further information or specific details, please let me know!
  ```

{% endtab %}
{% endtabs %}

Example Code

```python
from crypto_com_agent_client import Agent

agent = Agent.init(
    llm_config={
        "provider": "OpenAI",
        "model": "gpt-4",
        "provider-api-key": "sk-proj-example-key",
        "temperature": "float-controlling-output-randomness",
        "transfer-limit": -1,  # -1 means no limit (unlimited), 0 disables transfers completely, any positive number (e.g. 5) allows exactly that transfer amount
    },
    blockchain_config={
        "api-key": "your-crypto.com-developer-platform-api-key",
        "private-key": "your-private-key",
        "sso-wallet-url": "your-sso-wallet-url",
        "timeout": "timeout-in-seconds-for-API-calls-default-20s")
    },
)
response = agent.interact("Get lastest block with detail")
print(response)

```


# CronosID Operations

The AI Agent SDK offers powerful CronosID-related features, allowing developers to map CronosIDs and associated blockchain addresses.

These features enhance user-friendliness and accessibility by enabling seamless name-to-address and address-to-name resolutions on Cronos Chains.

To learn more about the underlying Developer Platform functionalities, please visit [Developer Platform Client SDK CronosID Module](/crypto.com-developer-platform/on-chain-developer-platform-client-sdk/cronosid-module).

#### 5.1 Resolve CronosId name

Resolve a given CronosId name to its associated blockchain address using the Crypto.com developer platform.

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  name (str): The CronosId name to resolve (e.g., "xyz.cro").
  ```
* Example Query

  ```
  "Resolve CronosId name <example-cronos-id>"
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  str: A formatted string containing the resolved blockchain address.
  ```
* Example Response

  ```
  The CronosId name <example-cronos-id> has been successfully resolved to the blockchain address: <example-address>.
  ```

{% endtab %}
{% endtabs %}

Example Code

```python
from crypto_com_agent_client import Agent

agent = Agent.init(
    llm_config={
        "provider": "OpenAI",
        "model": "gpt-4o-mini",
        "temperature": 1,
        "provider-api-key": "sk-proj-example-key",
        "transfer-limit": -1,  # -1 means no limit (unlimited), 0 disables transfers completely, any positive number (e.g. 5) allows exactly that transfer amount
    },
    blockchain_config={
        "api-key": "your-crypto.com-developer-platform-api-key",
        "private-key": "your-private-key",
        "sso-wallet-url": "your-sso-wallet-url",
        "timeout": "timeout-in-seconds-for-API-calls-default-20s")
    },
)
response = agent.interact("Resolve CronosId name <example-cronos-id>")
print(response)

```

#### 5.2 Lookup CronosId address

Lookup a given blockchain address to find the associated CronosId name from the Crypto.com developer platform.

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  address (str): The blockchain address to lookup.
  ```
* Example Query

  ```
  "Lookup CronosId for <example-address>"
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  str: A formatted string containing the CronosId name.
  ```
* Example Response

  ```
  The CronosId for the address <example-address> is <example-cronos-id>
  ```

{% endtab %}
{% endtabs %}

Example Code

```python
from crypto_com_agent_client import Agent

agent = Agent.init(
    llm_config={
        "provider": "OpenAI",
        "model": "gpt-4o-mini",
        "temperature": 1,
        "provider-api-key": "sk-proj-example-key",
        "transfer-limit": -1,  # -1 means no limit (unlimited), 0 disables transfers completely, any positive number (e.g. 5) allows exactly that transfer amount
    },
    blockchain_config={
        "api-key": "your-crypto.com-developer-platform-api-key",
        "private-key": "your-private-key",
        "sso-wallet-url": "your-sso-wallet-url",
        "timeout": "timeout-in-seconds-for-API-calls-default-20s")
    },
)
response = agent.interact("Lookup CronosId for <example-address>")
print(response)

```


# Defi Operations

The AI Agent SDK provides powerful DeFi-related features, enabling seamless access to essential data from the Crypto.com ecosystem. It allows developers to retrieve a list of whitelisted tokens for a specified DeFi protocol, fetch information about all available farms, and obtain detailed information about a specific farm identified by its symbol.

To learn more about the underlying Developer Platform functionalities, please visit [Developer Platform Client SDK Defi Module](/crypto.com-developer-platform/on-chain-developer-platform-client-sdk/defi-module).

#### 6.1 Get whitelisted tokens&#x20;

Retrieve a list of whitelisted tokens for the specified DeFi protocol from the Crypto.com developer platform.

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  protocol (str): The DeFi protocol name (e.g., "H2", "VVS").
  ```
* Example Query

  ```
  "Get whitelisted tokens of protocol <example-protocol>"
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  str: A formatted string containing the list of whitelisted tokens.
  ```
* Example Response

  ```
  Here are the whitelisted tokens for the <example-protocol> protocol:

  <example-token-name>
     - Address: [<example-address>](<example-explore-link>)
     - Decimal: <example-decimal>
     - Swappable: <example-boolean>
     - ![<example-token-name> Logo](<example-img-link>)
  <example-token-name>
  ...

  Feel free to ask if you need more information about any specific token!
  ```

{% endtab %}
{% endtabs %}

Example Code

```python
from crypto_com_agent_client import Agent

agent = Agent.init(
    llm_config={
        "provider": "OpenAI",
        "model": "gpt-4",
        "provider-api-key": "sk-proj-example-key",
        "temperature": "float-controlling-output-randomness",
        "transfer-limit": -1,  # -1 means no limit (unlimited), 0 disables transfers completely, any positive number (e.g. 5) allows exactly that transfer amount
    },
    blockchain_config={
        "api-key": "your-crypto.com-developer-platform-api-key",
        "private-key": "your-private-key",
        "sso-wallet-url": "your-sso-wallet-url",
        "timeout": "timeout-in-seconds-for-API-calls-default-20s")
    },
)
response = agent.interact("Get whitelisted tokens of protocol <example-protocol>")
print(response)
```

#### 6.2 Get all farms&#x20;

Retrieve information about all available farms for the specified DeFi protocol from the Crypto.com developer platform.

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  protocol (str): The DeFi protocol name (e.g., "H2", "VVS").
  ```
* Example Query

  ```
  "Get all farms of protocol <example-protocol>"
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  str: A formatted string containing information about all farms.
  ```
* Example Response

  ```
  Here are the farms available for the <example-protocol>:
  <example-farm-symbol>
     - LP Address: <example-lp-address>
     - Base APR: <example-percentage>
     - Base APY: <example-percentage>
     - Reward Start Date: <example-date>
     - Chain: <example-chain-name>
  <example-farm-symbol>
  ...
  ```

{% endtab %}
{% endtabs %}

Example Code

```python
from crypto_com_agent_client import Agent

agent = Agent.init(
    llm_config={
        "provider": "OpenAI",
        "model": "gpt-4",
        "provider-api-key": "sk-proj-example-key",
        "temperature": "float-controlling-output-randomness",
        "transfer-limit": -1,  # -1 means no limit (unlimited), 0 disables transfers completely, any positive number (e.g. 5) allows exactly that transfer amount
    },
    blockchain_config={
        "api-key": "your-crypto.com-developer-platform-api-key",
        "private-key": "your-private-key",
        "sso-wallet-url": "your-sso-wallet-url",
        "timeout": "timeout-in-seconds-for-API-calls-default-20s")
    },
)
response = agent.interact("Get all farms of protocol <example-protocol>")
print(response)
```

#### 6.3 Get farm by symbol&#x20;

Retrieve detailed information about a specific farm identified by its symbol for the specified DeFi protocol.

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  protocol (str): The DeFi protocol name (e.g., "H2", "VVS").
  symbol (str): The farm symbol (e.g., "zkCRO-MOON", "CRO-GOLD").
  ```
* Example Query

  ```
  "Get farm of protocol <example-protocol> symbol <example-symbol>"
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  str: A formatted string containing information about the specific farm.
  ```
* Example Response

  ```
  Here is the information for the farm with the symbol <example-symbol> in the <example-protocol> protocol:

  - Farm ID: <example-farm-id>
  - LP Symbol: <example-lp-symbol>
  - LP Address: [<example-lp-address>](<example-explorer-link>)
  - Token:
    - Symbol: <example-token-symbol>
    - Address: [<example-token-address>](<example-explorer-link>)
  - Quote Token:
    - Symbol: <example-quote-token-symbol>
    - Address: [<example-quote-token-address>](<example-explorer-link>)
  - Version: <example-version>
  - Reward Start Date: <example-date>, at <example-time>
  - Finished: <example-boolean>
  - Migrated: <example-boolean>
  - Boost Enabled: <example-boolean>
  - Auto Harvest Enabled: <example-boolean>
  - Chain: <example-chain-name>
  - Chain ID: <example-chain-id>
  - Base APR: <example-percentage>
  - Base APY: <example-percentage>
  - LP APR: <example-percentage>
  - LP APY: <example-percentage>

  If you need further assistance or more details, feel free to ask!
  ```

{% endtab %}
{% endtabs %}

Example Code

```python
from crypto_com_agent_client import Agent

agent = Agent.init(
    llm_config={
        "provider": "OpenAI",
        "model": "gpt-4",
        "provider-api-key": "sk-proj-example-key",
        "temperature": "float-controlling-output-randomness",
        "transfer-limit": -1,  # -1 means no limit (unlimited), 0 disables transfers completely, any positive number (e.g. 5) allows exactly that transfer amount
    },
    blockchain_config={
        "api-key": "your-crypto.com-developer-platform-api-key",
        "private-key": "your-private-key",
        "sso-wallet-url": "your-sso-wallet-url",
        "timeout": "timeout-in-seconds-for-API-calls-default-20s")
    },
)

response = agent.interact("Get farm of protocol <example-protocol> symbol <example-symbol>")
print(response)
```


# Crypto.com Exchange

The AI Agent SDK offers comprehensive Exchange-related features by retrieving information about all available trading pairs and their current market data from the Crypto.com Exchange. It also supports fetching real-time market data for a specified trading instrument, providing developers with valuable insights for building trading and analytics applications.

To learn more about the underlying Developer Platform functionalities, please visit [Developer Platform Client SDK Exchange Module](/crypto.com-developer-platform/on-chain-developer-platform-client-sdk/exchange-module).

#### 7.1 Get all tickers

Retrieve information about all available trading pairs and their current market data from the Crypto.com Exchange.

{% tabs %}
{% tab title="Query" %}

* Example Query

  ```
  "Get all tickers"
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  str: A formatted string containing information about all available tickers.
  ```
* Example Response

  <pre><code>Here are some of the current tickers available:

  <strong>1. &#x3C;example-pair>
  </strong>   - Last Price: &#x3C;example-price>
     - High: &#x3C;example-high-price>
     - Low: &#x3C;example-low-price>
     - Volume: &#x3C;example-volume>
  2. &#x3C;example-pair>
  ...

  This is just a selection of available tickers. If you would like more details or specific information regarding other tickers, please let me know!
  </code></pre>

{% endtab %}
{% endtabs %}

Example Code

```python
from crypto_com_agent_client import Agent

agent = Agent.init(
    llm_config={
        "provider": "OpenAI",
        "model": "gpt-4",
        "provider-api-key": "sk-proj-example-key",
        "temperature": "float-controlling-output-randomness",
        "transfer-limit": -1,  # -1 means no limit (unlimited), 0 disables transfers completely, any positive number (e.g. 5) allows exactly that transfer amount
    },
    blockchain_config={
        "api-key": "your-crypto.com-developer-platform-api-key",
        "private-key": "your-private-key",
        "sso-wallet-url": "your-sso-wallet-url",
        "timeout": "timeout-in-seconds-for-API-calls-default-20s")
    },
)
response = agent.interact("Get all tickers")
print(response)
```

#### 7.2 Get ticker by instrument&#x20;

Retrieve current market data for a specified trading instrument from the Crypto.com Exchange.

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  instrument_name (str): The name of the trading instrument (e.g., "BTC_USDT").
  ```
* Example Query

  ```
  "What's the ticker information of <example-instrument>"
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  str: A formatted string containing the ticker information for the specified instrument.
  ```
* Errors

  ```python
  ValueError: If instrument_name is empty or None.
  ```
* Example Response

  ```
  Here is the ticker information for the <example-instrument> trading pair:

  - Instrument Name: <example-instrument>
  - High Price: <example-high-price>
  - Low Price: <example-low-price>
  - Last Price: <example-last-price>
  - 24h Volume: <example-volume>
  - 24h Volume Value: <example-volume-value>
  - Price Change: <example-price-change> (approximately <example-percentage>)
  - Best Bid: <example-best-bid-price>
  - Best Ask: <example-best-ask-price>
  - Open Interest: <example-open-interest>
  - Timestamp: <example-timestamp>

  If you need further information, feel free to ask!
  ```

{% endtab %}
{% endtabs %}

Example Code

```python
from crypto_com_agent_client import Agent

agent = Agent.init(
    llm_config={
        "provider": "OpenAI",
        "model": "gpt-4",
        "provider-api-key": "sk-proj-example-key",
        "temperature": "float-controlling-output-randomness",
        "transfer-limit": -1,  # -1 means no limit (unlimited), 0 disables transfers completely, any positive number (e.g. 5) allows exactly that transfer amount
    },
    blockchain_config={
        "api-key": "your-crypto.com-developer-platform-api-key",
        "private-key": "your-private-key",
        "sso-wallet-url": "your-sso-wallet-url",
        "timeout": "timeout-in-seconds-for-API-calls-default-20s")
    },
)

response = agent.interact("What's the ticker information of <example-instrument>")
print(response)
```


# Plugins

Plugins allow you to extend the functionality of the agent. Below are the available plugins and examples of their usage.

### Storage Plugin

The SQLitePlugin provides a mechanism for state persistence using SQLite.

A critical persistence component for AI Agents that leverages SQLite's robust database engine to maintain state and memory across interactions.\
This plugin enables agents to store and recall important information, conversation history, and learned patterns using SQLite's self-contained, serverless architecture, ensuring reliable data management without external database dependencies.

> **Disclaimer:**\
> Cryptocom AI Agent SDK does not provide built-in encryption for data stored via SQLitePlugin. Developers are fully responsible for securing any data written to disk using this plugin. Crypto.com is not liable for any data leakage or compromise resulting from insecure use of this storage method.

#### Best Practices

For production use, developers are responsible for ensuring secure data handling. Key guideline to follow:

* Do not store private keys, secrets, or personal user data in the agent state unless encryption is implemented.
* Consider using encrypted database extensions (e.g., SQLCipher) or manually encrypting sensitive fields before storage.
* Store the database `.db` file in secure, access-controlled directories to prevent unauthorized access.
* If your application is running on user devices or servers, utilize OS-level encryption and enforce strict permissions to safeguard data.&#x20;
* Transmit data over secure connections to protect data in transit (e.g., HTTPS).

**Example Usage**

```python
from crypto_com_agent_client import Agent, SQLitePlugin

agent = Agent.init(
    llm_config={
        "provider": "OpenAI",
        "model": "gpt-4",
        "provider-api-key": "sk-proj-example-key",
        "temperature": "float-controlling-output-randomness",
        "transfer-limit": -1,  # -1 means no limit (unlimited), 0 disables transfers completely, any positive number (e.g. 5) allows exactly that transfer amount
    },
    blockchain_config={
        "api-key": "your-crypto.com-developer-platform-api-key",
        "private-key": "your-private-key",
        "sso-wallet-url": "your-sso-wallet-url",
        "timeout": "timeout-in-seconds-for-API-calls-default-20s")
    },
    plugins={                
        "storage": SQLitePlugin(db_path="agent_state.db"),
    },
)
```

### MemoryConfig Plugin

The MemoryConfig Plugin optimizing token usage and managing conversation memory in AI agents.

Supported values:

* DefaultMemoryConfigs.conservative(): conservative configuration for limited resources (GPT-3.5 optimal)
* DefaultMemoryConfigs.balanced(): balanced configuration for general use (Default - GPT-4 optimal)
* DefaultMemoryConfigs.aggressive(): aggressive configuration for maximum retention (Claude/GPT-4 Turbo optimal)
* DefaultMemoryConfigs.no\_pruning(): behaves like traditional chatbot.

These ready-to-use presets help developers avoid token overflow on smaller models, keep costs low with conservative pruning, maintain rich context with balanced settings, or achieve maximum recall with aggressive/no-pruning modes, making it easy to optimize any agent for GPT-3.5, GPT-4, Claude, or other LLMs without manual tuning.

**Example Usage**

```python
from crypto_com_agent_client import Agent, DefaultMemoryConfigs

agent = Agent.init(
    llm_config={
        "provider": "OpenAI",
        "model": "gpt-4",
        "provider-api-key": "sk-proj-example-key",
        "temperature": "float-controlling-output-randomness",
        "transfer-limit": -1,  # -1 means no limit (unlimited), 0 disables transfers completely, any positive number (e.g. 5) allows exactly that transfer amount
    },
    blockchain_config={
        "api-key": "your-crypto.com-developer-platform-api-key",
        "private-key": "your-private-key",
        "sso-wallet-url": "your-sso-wallet-url",
        "timeout": "timeout-in-seconds-for-API-calls-default-20s")
    },
    plugins={
         "memory_config": DefaultMemoryConfigs.balanced(),   
    },
)
```

### LangFuse Plugin

The LangFusePlugin integrates telemetry for monitoring interactions.

An observability and monitoring solution specifically designed for AI Agents, providing detailed telemetry of agent-user interactions and performance metrics.\
This open-source plugin enables development teams to track, debug, and optimize their agent's behavior through comprehensive analytics and collaborative tools, making it easier to identify areas for improvement and ensure optimal agent performance.

Provide the required keys as a dictionary.&#x20;

**Example Usage**

```python
from crypto_com_agent_client import Agent

agent = Agent.init(
    llm_config={
        "provider": "OpenAI",
        "model": "gpt-4",
        "provider-api-key": "sk-proj-example-key",
        "temperature": "float-controlling-output-randomness",
        "transfer-limit": -1,  # -1 means no limit (unlimited), 0 disables transfers completely, any positive number (e.g. 5) allows exactly that transfer amount
    },
    blockchain_config={
        "api-key": "your-crypto.com-developer-platform-api-key",
        "private-key": "your-private-key",
        "sso-wallet-url": "your-sso-wallet-url",
        "timeout": "timeout-in-seconds-for-API-calls-default-20s")
    },
    plugins={
        "langfuse": {
            "public-key": "user-public-key",
            "secret-key": "user-secret-key",
            "host": "https://langfuse.example.com",
        }
    },
)
```

### Personality Plugin

Customize the agent’s personality and instructions. A configuration module that enables fine-tuned control over an agent's communication style and behavior patterns.&#x20;

**Supported Keys**:&#x20;

* Tone: e.g., "friendly", "professional", "humorous"
* Language: e.g., "English", "German", "Spanish"
* Verbosity: e.g., "low", "medium", "high"

These keys allow developers to easily control the agent's communication style to suit specific use cases or brand requirements, ensuring consistent and appropriate interactions across all scenarios.

**Example Usage**

```python
from crypto_com_agent_client import Agent

agent = Agent.init(
    llm_config={
        "provider": "OpenAI",
        "model": "gpt-4",
        "provider-api-key": "sk-proj-example-key",
        "temperature": "float-controlling-output-randomness",
        "transfer-limit": -1,  # -1 means no limit (unlimited), 0 disables transfers completely, any positive number (e.g. 5) allows exactly that transfer amount
    },
    blockchain_config={
        "api-key": "your-crypto.com-developer-platform-api-key",
        "private-key": "your-private-key",
        "sso-wallet-url": "your-sso-wallet-url",
        "timeout": "timeout-in-seconds-for-API-calls-default-20s")
    },
    plugins={
        "personality": {
            "tone": "friendly",
            "language": "English",
            "verbosity": "high",
        },
    },
)

```

For more advanced behavior control, developers can combine personality configuration with freeform instructions. This enables deeper modification of the AI Agent’s behavior for complex and nuanced personality traits that enhance task performance and user interactions.

Learn more in the [Advanced Usage](/crypto.com-ai-agent-sdk/core-concepts-overview/advanced-usage-custom-instructions).

***


# Messaging Platform Plugins

### Introduction

Crypto.com AI Agent SDK offers built-in support for integrating AI-powered blockchain interactions into popular messaging platforms. This functionality enables developers to create user friendly bots that allow users to interact with blockchain services using natural language.

### Available Messaging Platform Plugins

{% content-ref url="/pages/3J3wkUNko5hh8UBniWZE" %}
[Telegram Plugin](/crypto.com-ai-agent-sdk/core-concepts-overview/plugins/messaging-platform-plugins/telegram-plugin)
{% endcontent-ref %}

{% content-ref url="/pages/TIGjIm7OkTTKcbgcsNqY" %}
[Discord Plugin](/crypto.com-ai-agent-sdk/core-concepts-overview/plugins/messaging-platform-plugins/discord-plugin)
{% endcontent-ref %}

Both plugins are designed for developer friendly integration, requiring only a few lines of code to set up. They leverage the capabilities of the AI Agent SDK to interpret user inputs and execute corresponding blockchain functions.

### Upcoming Integrations

Crypto.com AI Agent SDK is continuously evolving, with plans to support additional messaging platforms in the future. Stay tuned for updates as we expand our plugin offerings to include more platforms, enhancing the accessibility and versatility of AI-powered blockchain interactions.


# Telegram Plugin

### Introduction

The Crypto.com AI Agent SDK Telegram plugin allows users to connect the agent to their Telegram bot with just a few lines of code.

This guide demonstrates how to build a Telegram bot that interacts with the Cronos network. The bot enables users to query blockchain information and execute transactions smoothly.&#x20;

A video demo is available in the [Crypto.com AI Agent SDK X post](https://x.com/cryptocom_agent/status/1901907004140192067).

### Prerequisites

* [Crypto.com AI Agent SDK](https://pypi.org/project/crypto-com-ai-agent-client/) installed.
* Python installed (version >= 3.12).
* API Key for Crypto.com Developer Platform, [click here to learn how to obtain your Crypto.com Developer Platform API key](/crypto.com-developer-platform/developer-platform-dashboard).
* API Keys of AI provider, refer to the [Dynamic AI Model Manager ](/crypto.com-ai-agent-sdk/core-concepts-overview/dynamic-ai-model-manager)to see which providers are supported by the AI Agent SDK.
* Required account: [Telegram Bot Token](https://core.telegram.org/bots#how-do-i-create-a-bot).&#x20;

### Get a Telegram Bot Token

* Open Telegram and search for **@BotFather**.
* Type `/start and /newbot`, then follow the prompts to name your bot (must end in bot, e.g., CryptoHelper).
* After creation, **@BotFather** will give you a TOKEN (e.g., `7008008900:AAEKe6vIwM0gokw..`), which should be safely kept.

### Telegram Plugin

We need to add Telegram plugin when initializing the Agent:&#x20;

{% tabs %}
{% tab title="OpenAI as Provider" %}

```python
import os
from crypto_com_agent_client import Agent
from dotenv import load_dotenv

load_dotenv()

# Initialize the agent with LLM and blockchain configurations
# Current chainID refers to Cronos zkEVM Testnet, optionally change it to other Cronos networks
agent = Agent.init(
   llm_config={
       "provider": "OpenAI",
       "model": "gpt-4o-mini",
       "provider-api-key": os.getenv("OPENAI_API_KEY"),
       "temperature": "float-controlling-output-randomness",
       "transfer-limit": -1,  # -1 means no limit (unlimited), 0 disables transfers completely, any positive number (e.g. 5) allows exactly that transfer amount
   },
   blockchain_config={
       "api-key": os.getenv("DEVELOPER_PLATFORM_API_KEY"),
       "private-key": os.getenv("PRIVATE_KEY"),
       "sso-wallet-url": "your-sso-wallet-url",
       "timeout": "timeout-in-seconds-for-API-calls-default-20s")
   },
   plugins={
       "instructions": "You are a humorous assistant that always includes a joke in your responses.",
       "telegram": {"bot_token": os.getenv("TELEGRAM_BOT_TOKEN")},
   },
)

agent.start_telegram()
```

{% endtab %}

{% tab title="Gemini as Provider" %}

```python
import os
from crypto_com_agent_client import Agent
from dotenv import load_dotenv
​
load_dotenv()
​
# Initialize the agent with LLM and blockchain configurations
# Current chainID refers to Cronos zkEVM Testnet, optionally change it to other Cronos networks
agent = Agent.init(
  llm_config={
      "provider": "GoogleGenAI",
      "model": "gemini-2.0-flash",
      "provider-api-key": os.getenv("GEMINI_API_KEY"),
      "temperature": "float-controlling-output-randomness",
  },
  blockchain_config={
      "api-key": os.getenv("DEVELOPER_PLATFORM_API_KEY"),
      "private-key": os.getenv("PRIVATE_KEY"),
      "sso-wallet-url": "your-sso-wallet-url",
      "timeout": "timeout-in-seconds-for-API-calls-default-20s")
  },
  plugins={
      "instructions": "You are a humorous assistant that always includes a joke in your responses.",
      "telegram": {"bot_token": os.getenv("TELEGRAM_BOT_TOKEN")},
  },
)
​
agent.start_telegram()

```

{% endtab %}
{% endtabs %}

### Run everything

As shown in the example code, we start the Telegram bot by invoking the Agent's built-in function:

```
agent.start_telegram()
```

Once the bot is running, test it to ensure it’s working as expected:

* Open Telegram and search for your bot using the bot name you set up with **@BotFather**.
* Send a sample command or message, such as `/start`, to see if the bot responds.

### Troubleshooting

If you encounter issues during setup or execution, follow these tips:

* Check your API keys to ensure they are correctly set in the environment variables.
* Review Telegram Bot API limitations to ensure compliance with rate limits and usage guidelines.


# Discord Plugin

### Introduction

Crypto.com AI Agent SDK Discord plugin allows users to create interactive blockchain experiences within Discord communities. By setting up a custom bot, users can interact with the Cronos network using natural language to access wallet data, track transactions, and execute commands directly in server channels.&#x20;

This guide provides step-by-step instructions to get your Discord bot up and running in no time.&#x20;

A video demo is available in the [Crypto.com AI Agent SDK X post](https://x.com/cryptocom_agent/status/1917126794265956642).

<figure><img src="/files/VLISOEmchkzaleXj1QYo" alt=""><figcaption></figcaption></figure>

### Prerequisites

* [Crypto.com AI Agent SDK](https://pypi.org/project/crypto-com-ai-agent-client/) installed.
* Python installed (version >= 3.12)
* API Key for Crypto.com Developer Platform, [click here to learn how to obtain your Crypto.com Developer Platform API key](/crypto.com-developer-platform/developer-platform-dashboard).
* API Keys of AI provider, refer to the [Dynamic AI Model Manager ](/crypto.com-ai-agent-sdk/core-concepts-overview/dynamic-ai-model-manager)to see which providers are supported by the AI Agent SDK.
* Required account: [Discord Bot Token](https://discord.com/developers/applications/).

### Get a Discord Bot Token

1. Open your browser and navigate to the [Discord Developer Portal](https://discord.com/developers/applications).
2. Click on "New Application", enter a name for your bot (e.g., *CryptoHelper*), and click "Create".
3. In the left sidebar, select "Bot", then click "Add Bot" and confirm by clicking "Yes, do it!"
4. Under the "Token" section, click "Click to Reveal Token" to view your bot's token.
5. Copy and securely store this token (e.g., `MTM3Mjc0MjI3MzUzNTcwNTE5MA.GHuA_M.dSXMKfwfXxd1kWZ8fBPLvB7EwuWcM6StENS43g`). Never share this token publicly, as it grants control over your bot

### **Invite the Bot to Your Server**

1. In the Developer Portal, navigate to the "OAuth2" section and select "URL Generator".
2. Under "Scopes", check the boxes for "bot" and "applications.commands".
3. Under "Bot Permissions", select the permissions your bot needs (e.g., "Send Messages", "Read Message History").
4. Copy the generated URL at the bottom of the page.
5. Paste the URL into your browser, select the server you want to add the bot to, and click "Continue".
6. Review the permissions and click "Authorize".
7. Complete any CAPTCHA verification if prompted.

### Discord Plugin

Add Discord plugin when initializing the Agent:&#x20;

{% tabs %}
{% tab title="OpenAI as Provider" %}

```python
import os
from crypto_com_agent_client import Agent
from dotenv import load_dotenv

load_dotenv()

# Initialize the agent with LLM and blockchain configurations
# Current chainID refers to Cronos zkEVM Testnet, optionally change it to other Cronos networks
agent = Agent.init(
   llm_config={
       "provider": "OpenAI",
       "model": "gpt-4o-mini",
       "provider-api-key": os.getenv("OPENAI_API_KEY"),
       "temperature": "float-controlling-output-randomness",
       "transfer-limit": -1,  # -1 means no limit (unlimited), 0 disables transfers completely, any positive number (e.g. 5) allows exactly that transfer amount
   },
   blockchain_config={
       "api-key": os.getenv("DEVELOPER_PLATFORM_API_KEY"),
       "private-key": os.getenv("PRIVATE_KEY"),
       "sso-wallet-url": "your-sso-wallet-url",
       "timeout": "timeout-in-seconds-for-API-calls-default-20s")
   },
   plugins={
       "instructions": "You are a humorous assistant that always includes a joke in your responses.",
       "discord": {"bot_token": os.getenv("DISCORD_BOT_TOKEN")},
   },
)

agent.start_discord()
```

{% endtab %}

{% tab title="Gemini as Provider" %}

```python
import os
from crypto_com_agent_client import Agent
from dotenv import load_dotenv
​
load_dotenv()
​
# Initialize the agent with LLM and blockchain configurations
# Current chainID refers to Cronos zkEVM Testnet, optionally change it to other Cronos networks
agent = Agent.init(
  llm_config={
      "provider": "GoogleGenAI",
      "model": "gemini-2.0-flash",
      "provider-api-key": os.getenv("GEMINI_API_KEY"),
      "temperature": "float-controlling-output-randomness",
  },
  blockchain_config={
      "api-key": os.getenv("DEVELOPER_PLATFORM_API_KEY"),
      "private-key": os.getenv("PRIVATE_KEY"),
      "sso-wallet-url": "your-sso-wallet-url",
      "timeout": "timeout-in-seconds-for-API-calls-default-20s")
  },
  plugins={
      "instructions": "You are a humorous assistant that always includes a joke in your responses.",
      "discord": {"bot_token": os.getenv("DISCORD_BOT_TOKEN")},
   },
)

agent.start_discord()
```

{% endtab %}
{% endtabs %}

### Run everything

As shown in the example code, we start the Discord bot by invoking the Agent's built-in function:

```
agent.start_discord()
```

Once the bot is running, test it to ensure it’s working as expected:

* Ensure your bot is running and connected to Discord.
* Open Discord and navigate to the server where you've added your bot.
* Interact with the bot and observe if it responds appropriately to confirm it's functioning correctly.

### Troubleshooting

If you encounter issues during setup or execution, follow these tips:

* Check your API keys to ensure they are correctly set in the environment variables.
* Review Discord Bot API limitations to ensure compliance with rate limits and usage guidelines.


# Tools

Tools are user-defined functions that enhance the agent’s capabilities and are integrated into the AI Agent SDK as plugins. They allow the AI agent to fetch data, perform computations, and interact with external APIs. \
\
Tools need to be decorated with `@tool` to be recognized and registered in the AI Agent. \
\
It can serve various purposes, from fetching data to performing calculations, and integrating with external APIs.

### Set Up

Before defining a tool, import the `@tool` decorator to register the function properly:

```python
from crypto_com_agent_client import tool
```

### Implementation Examples

1. **Custom Greeting Tool**\
   This tool generates a personalized greeting message for a user.

```python
@tool
def greet_user(name: str) -> str:
    """
    Generate a personalized greeting message.

    Args:
        name (str): The name of the user to greet.

    Returns:
        str: A greeting message addressed to the user.
    """
    return f"Hello, {name}! How can I assist you today?"
```

2. **Token Information Tool**\
   This tool retrieves token information from Cronos EVM using the VVS Finance API (a third-party Cronos project). It fetches liquidity and volume data from underlying subgraphs.

```python
@tool
def get_token_info(address: str) -> str:
   """ 
   Returns the token information, based on address.
   Args:
    address (str): The token contract address to query.

   Returns:
    str: Formatted token details.
   """
   try:
       response = requests.get(f"https://api.vvs.finance/info/api/tokens/{address}")
       response.raise_for_status()
       return f"Token at {address} is {response.json()}."
   except requests.RequestException as e:
       print(f"Error fetching data: {e}")
       return f"Error getting token information: {str(e)}"
```

3. **APR Query Tool**\
   This example demonstrates how to query APR from blockchain projects. Here, we integrate H2 Finance (a third-party Cronos project) leveraging its API to incorporate it as a plugin within the AI Agent SDK. \
   The AI agent can automatically parse the JSON response, extract relevant information, and provide structured answers to various APR-related queries.

```python
import requests

@tool
def get_h2_apr() -> str:
    """  
    Fetches the latest APR data from H2 Finance API 

    Returns:
        str: Formatted APR details.
    """
    try:
        response = requests.get("https://api.h2.finance/general/api/info/v1/farm-aprs")
        response.raise_for_status()
        return f"H2 Finance APR information is {response.json()}."
        
    except requests.RequestException as e:
        print(f"Error fetching data: {e}")
        return f"Error getting H2 Finance APR information: {str(e)}"

```

4. **Cronos Blockchain Status Tool**<br>

   This blockchain status tool provides real-time insights into the Cronos EVM and Cronos zkEVM networks. With a single function call, users can access key network metrics, including the latest block number, current gas prices, transaction count in the most recent block, network difficulty, and timestamp details.\
   \
   The tool interacts directly with blockchain nodes via standard RPC endpoints, to ensure accurate and up-to-date status reports in a structured format. It offers developers instant access to the Cronos chains' performance data without requiring complex setup or configuration.

<pre class="language-python"><code class="lang-python"><strong>@tool
</strong>def get_blockchain_status(network: str = "cronos" "cronos zkevm") -> str:
    """
    Provide real-time blockchain network status including gas prices and block info

    Args:
        network (str): Supported networks: Cronos EVM, Cronos zkEVM.

    Returns:
        str: Formatted network status report or an error message.
    """
  
    from web3 import Web3
    from datetime import datetime, timezone
    
    

# Map networks to their RPC endpoints
    rpc_endpoints = {
        "cronos": "https://evm.cronos.com",
	"cronos zkevm": "https://mainnet.zkevm.cronos.org/"
    }
    
    if network.lower() not in rpc_endpoints:
        return f"Error: Unsupported network '{network}'. Supported networks: {', '.join(rpc_endpoints.keys())}"
    
    try:
        # Initialize Web3 connection
        web3 = Web3(Web3.HTTPProvider(rpc_endpoints[network.lower()]))
        
        # Check connection
        if not web3.is_connected():
            return f"Error: Could not connect to {network} network"
        
        # Fetch blockchain data
        latest_block = web3.eth.block_number
        gas_price_wei = web3.eth.gas_price
        gas_price_gwei = web3.from_wei(gas_price_wei, 'gwei')
        block_info = web3.eth.get_block(latest_block)
        
        # Convert timestamp to timezone-aware datetime object
        timestamp_dt = datetime.fromtimestamp(block_info['timestamp'], tz=timezone.utc)
        formatted_time = timestamp_dt.strftime('%Y-%m-%d %H:%M:%S UTC')
        
        return (
            f" Blockchain Status for {network.capitalize()} ".center(40, "=") + "\n"
            f"Latest Block:       {latest_block}\n"
            f"Gas Price:          {gas_price_gwei:.2f} Gwei\n"
            f"Transactions:       {len(block_info['transactions'])} in current block\n"
            f"Difficulty:         {block_info['difficulty']}\n"
            f"Timestamp:          {block_info['timestamp']} ({formatted_time})"
        )
    
    except Exception as err:
        return f"Error fetching {network} data: {str(err)}"

</code></pre>

### &#x20;Using Tools in the Agent

To use the tools in your agent, initialize it with the required configurations:

```python
from crypto_com_agent_client import Agent

agent = Agent.init(
    llm_config={
        "provider": "OpenAI",
        "model": "gpt-4",
        "provider-api-key": "sk-proj-example-key",
        "temperature": "float-controlling-output-randomness",
        "transfer-limit": -1,  # -1 means no limit (unlimited), 0 disables transfers completely, any positive number (e.g. 5) allows exactly that transfer amount
    },
    blockchain_config={
        "api_key": "your-crypto.com-developer-platform-api-key",
        "private-key": "your-private-key",
        "sso-wallet-url": "your-sso-wallet-url",
        "timeout": "timeout-in-seconds-for-API-calls-default-20s")
    },
    plugins={
         "tools": [greet_user, get_token_info, get_h2_apr, get_blockchain_status],
    },
)
```

### Query and Response

Take `get_h2_apr`  for example, the AI Agent can automatically extract information from the result JSON and provide answers to various queries. Developers don’t need to manually search for specific fields in the JSON response - the AI Agent SDK handles that for you.

#### Example Query (APY)

```python
response = agent.interact("What's the APY of H2 Finance?")
print(response)
```

Response &#x20;

```python
Here are the APYs (Annual Percentage Yields) for various liquidity pools in H2 Finance:

1. **zkCRO-CRO**
   - Emission APY: 8.81%
   - LP APY: 1.12%

2. **zkCRO-AMPLY**
   - Emission APY: 72.25%
   - LP APY: 0.63%

3. **zkCRO-vETH**
   - Emission APY: 13.66%
   - LP APY: 4.21%

4. **zkCRO-MOON**
   - Emission APY: 0.00%
   - LP APY: 5.35%
   - Rewarders APY (MOON): 129.04%

5. **vUSD-USDC**
   - Emission APY: 3.33%
   - LP APY: 1.89%

...

These values reflect the current returns for participating in these liquidity pools. If you have any specific pool you want more details on, let me know!
```

#### Example Query (APR)

```python
response = agent.interact("What's the APR of h2 finance?")
```

Response

```python
Here are the current APR (Annual Percentage Rate) details for H2 Finance:

1. **zkCRO-CRO**
   - Emission APR: 8.45%
   - LP APR: 1.11%

2. **zkCRO-AMPLY**
   - Emission APR: 54.42%
   - LP APR: 0.62%

3. **zkCRO-vETH**
   - Emission APR: 12.80%
   - LP APR: 4.13%

4. **zkCRO-MOON**
   - Emission APR: 0.00%
   - LP APR: 5.21%
   - Rewarders APR (MOON): 82.97%

5. **vUSD-USDC**
   - Emission APR: 3.28%
   - LP APR: 1.88%

6. **zkCRO-H2**
   - Emission APR: 63.05%
   - LP APR: 1.16%
   
   ...

These APR values are subject to change, so please check regularly for updates.

```


# Advanced Usage: Custom Instructions

## Custom Instructions

The AI Agent SDK allows developers to customize agent behavior using custom instructions, enabling the assistant to take on specific personas or expertise. This helps tailor the tone, depth, and domain of the agent’s responses based on your application needs.

### **Setting Custom Instructions**

To modify agent behavior, use the `instructions` plugin when initializing the agent:

```javascript
from crypto_com_agent_client import Agent

agent = Agent.init(
    llm_config={
        "provider": "OpenAI",
        "model": "gpt-4",
        "provider-api-key": "sk-proj-example-key",
        "temperature": "float-controlling-output-randomness",
        "transfer-limit": -1,  # -1 means no limit (unlimited), 0 disables transfers completely, any positive number (e.g. 5) allows exactly that transfer amount
    },
    blockchain_config={
        "api-key": "your-crypto.com-developer-platform-api-key",
        "private-key": "your-private-key",
        "sso-wallet-url": "your-sso-wallet-url",
        "timeout": "timeout-in-seconds-for-API-calls-default-20s")
    },
    plugins={
        "instructions": "Be concise and professional."
    },
)
```

### **Instruction-Based Personas: Examples**

{% hint style="warning" %}
**Disclaimer:** Crypto.com AI Agent’s investment advice is for informational purposes only and should not be considered financial advice. Always conduct your own research and consult a licensed financial advisor. The AI Agent is not responsible for any financial losses.
{% endhint %}

#### **1. DeFi Investment Advisor**

**Instruction:**

```python
"instructions": "You are a DeFi investment advisor specializing in yield farming and liquidity pools. Help users assess risk, suggest optimal investment strategies, and explain the potential returns and risks of different protocols in the DeFi space."
```

**Conversation Example**

```t4-cs
Q: What are some good yield farming opportunities on Cronos right now?

A: Here are some promising yield farming opportunities on the Cronos network right now, categorized by the two key DeFi protocols: H2 and VVS.
H2 Protocol (Top 3 Pools)
1. zkCRO-CRO (Base APY: 8.32%, LP APY: 1.18%) - Reward Start Date: August 15, 2024
2. zkCRO-AMPLY (Base APY: 65.20%, LP APY: 0.72%) - Reward Period: Oct 31, 2024 – Feb 6, 2025
3. zkCRO-H2 (Base APY: 90.11%, LP APY: 1.00%) - Reward Start Date: August 15, 2024

VVS Protocol (Top 3 Pools)
1. CRO-LION (Base APY: 15.99%, LP APY: 1.21%) - Reward Period: Mar 3, 2025 – Jun 2, 2025
2. CRO-MOON LP (Base APY: 34.09%) - Reward Start Date: May 7, 2024
3. CRO-GOAT (Base APY: 4.06%, LP APY: 448.74%) - Reward Period: Nov 1, 2024 – Feb 6, 2025

Considerations
- Volatility & Risk: Yield farming returns can be volatile. Assess risk of impermanent loss and review the protocol’s security.
- Research: Thoroughly evaluate the underlying assets and project health before investing.
```

```t4-cs
Q: Can you suggest a diversified DeFi investment strategy?

A: Here's a structured approach for a diversified DeFi investment strategy:
1. Asset Allocation
- Stablecoins (30%) - Invest in USDC or DAI for stable returns via lending platforms.
- Major Cryptocurrencies (30%) - BTC, ETH, or other established assets for appreciation and protocol integration.
- Emerging Tokens (20%) - Research new DeFi tokens with growth potential.
- Liquidity Pools (20%) - Diversify across stablecoin and volatile pairs (e.g., ETH/USDC, BTC/DAI).

2. Choosing Protocols
- Lending Platforms: Utilize platforms like Aave for stablecoin lending.
- Yield Farming: Target reputable platforms (e.g., Uniswap, SushiSwap) for liquidity farming.
- Cross-Chain Opportunities: Explore protocols on multiple blockchains.

3. Risk Management & Rebalancing
- Regularly review and rebalance your portfolio based on market conditions.
- Set stop-loss orders to prevent significant losses.
- Monitor protocol governance and market trends to stay updated.
```

#### **2. NFT Marketplace Advisor**

**Instruction:**

```python
"instructions": "You are an NFT marketplace advisor. Help users navigate NFT platforms, provide advice on buying, selling, and minting NFTs, and explain the value of different NFT collections. Offer insights into current market trends and how to evaluate NFT investments."
```

**Conversation Example**

```t4-cs
Q: How do I determine the value of an NFT collection?

A: Evaluating NFT value involves several factors:
- Rarity and Scarcity: Limited editions or unique pieces generally hold higher value.
- Artistic Quality and Creator Reputation: Established artists or popular creators tend to have higher-priced works.
- Historical Sales Data: Analyze past transactions to spot price trends and frequency of sales.
- Community and Engagement: Active communities can increase demand and drive up value.
- Utility and Functionality: NFTs with extra features or real-world use can enhance value.
- Market Trends: Stay aware of market conditions that impact NFT demand and pricing.
- Comparative Analysis: Compare similar collections to gauge relative value.
- Platform Quality: Well-established platforms offer better liquidity and visibility.
- Cultural Significance: NFTs linked to significant events or famous collaborations may have added value.

By considering these factors, you can better assess the potential value and make informed investment decisions.
```

```t4-cs
Q: Any tips on selling NFTs more effectively?

A: Selling NFTs successfully requires a combination of strategies:
- Optimize Your Listing: Use compelling titles, high-quality visuals, and relevant tags to boost visibility.
- Choose the Right Platform: Align your choice of marketplace with your target audience and the type of NFTs.
- Build a Strong Community: Engage on social media and NFT communities to build credibility.
- Leverage Social Media: Regularly post updates and behind-the-scenes content to maintain interest.
- Create a Marketing Strategy: Plan promotional activities, collaborations, and exclusive drops.
- Highlight Utility and Features: Clearly state any additional benefits your NFTs offer.
- Set Realistic Pricing: Research market trends and start with lower prices to attract initial interest.
- Engage with Buyers: Respond promptly and professionally to inquiries to build rapport.
- Use Limited Editions and Scarcity: Generate demand with limited releases and advance announcements.
- Track Analytics and Feedback: Monitor data to refine your approach and improve future sales.
- Implementing these strategies will help you maximize NFT sales and build a loyal following in the space.
```

Using custom instructions, you can tailor the AI Agent to deliver domain-specific expertise and adapt its tone, verbosity, and capabilities to fit your application's needs. &#x20;


# Dynamic AI Model Manager

AI Agent SDK supports multiple AI model providers. Below are the currently available `llm_config` provider options:

* OpenAI
* Anthropic
* Mistral
* Fireworks
* GoogleGenAI
* Grok
* Groq
* VertexAI
* AWS Bedrock

### Provider Enum

Here is an example to access the Crypto.com AI Agent SDK Provider enums:

<pre class="language-python"><code class="lang-python">from crypto_com_agent_client.lib.enums.provider_enum import Provider

for provider in Provider:
    print(provider.name, provider.value)
    
# Output:
<strong># OpenAI OpenAI
</strong># Anthropic Anthropic
# Mistral Mistral
# Fireworks Fireworks
# GoogleGenAI GoogleGenAI
# Grok Grok
# Groq Groq
# VertexAI VertexAI
# Bedrock Bedrock
</code></pre>

### Example: Using Crypto.com AI Agent with Gemini

Here is an example to use the Crypto.com AI Agent with Google's Gemini model for Cronos chain interactions:

```javascript
from crypto_com_agent_client import Agent, SQLitePlugin
from crypto_com_agent_client.lib.enums.provider_enum import Provider

# Initialize the agent
agent = Agent.init(
   llm_config={
       "provider": Provider.GoogleGenAI,
       "model": "gemini-2.0-flash",
       "provider-api-key": "your-api-key",
       "temperature": "float-controlling-output-randomness",
       "transfer-limit": -1,  # -1 means no limit (unlimited), 0 disables transfers completely, any positive number (e.g. 5) allows exactly that transfer amount
   },
   blockchain_config={
        "api-key": "your-crypto.com-developer-platform-api-key",
        "private-key": "your-private-key",
        "sso-wallet-url": "your-sso-wallet-url",
        "timeout": "timeout-in-seconds-for-API-calls-default-20s")
   },
   plugins={
       "storage": SQLitePlugin(db_path="agent_state.db"),
       "instructions": "You are an assistant that always provides useful responses."
   },
)


# Interaction
response = agent.interact("Get latest block height")
print(response)

```


# AWS Bedrock

### Introduction

[AWS Bedrock](https://aws.amazon.com/bedrock/) is Amazon’s fully managed foundation model (FM) service that allows developers to build and scale generative AI applications without provisioning or maintaining infrastructure. Bedrock provides access to a wide selection of foundation models from providers such as Anthropic, Meta, Cohere, and Amazon, through a single API. &#x20;

With the new support in the Crypto.com AI Agent SDK, developers can connect the agent to Bedrock and decide exactly how it should work.

When setting it up with Crypto.com AI Agent SDK ([v1.3.3](https://github.com/crypto-com/agent-client-py/releases/tag/v1.3.3) and above), developers can choose:

* AI model: pick the specific model that works the best for you (for example, Anthropic Claude).
* Knowledge base: connect to a Bedrock knowledge base so answers can draw from your own data or project documentation
* Guardrail: set rules and safety checks to ensure responses follow compliance and usage requirements.

This integration allows developers to create scalable, secure AI agents that combine Crypto.com’s AI Agent SDK with AWS’s enterprise-grade AI infrastructure, which gives developers flexibility to decide which model powers the agent, what information it uses, and what constraints it follows.

### Prerequisites: AWS Bedrock & Access Setup

#### 1. Create a Bedrock Account & Pick a Model

1. Sign in to AWS [Bedrock](https://aws.amazon.com/bedrock/) Console.
2. Browse AI models and choose one to use (e.g., `anthropic.claude-3-haiku`). You can find the model details, including region availability, under the `Infer` section.
3. Note down the model ID and the regions where it’s available.

#### 2. Access Bedrock

You can access Bedrock in two ways:

**a. Access Key (Local Dev / Scripts)**\
Use an AWS access key ID and secret access key:

* Create an IAM user with BedrockFullAccess.
* Generate an access key (ID + secret).
* Store it securely in environment variables.

[Learn more about creating AWS access keys.](https://repost.aws/knowledge-center/create-access-key)

**b. IAM Role (Production)**\
Assign an IAM role with Bedrock permissions to your Lambda or EC2, ECS, EKS service.&#x20;

Example using Lambda:

{% content-ref url="/pages/YFMRuWcKu4cwvqxRU6Yx" %}
[AWS Lambda with Docker](/crypto.com-ai-agent-sdk/ai-agent-sdk-examples/aws-lambda-with-docker)
{% endcontent-ref %}

Example using EC2:

* Launch an EC2 instance.
* Attach an IAM role with BedrockFullAccess to the instance.
* Connect to the EC2 instance, install Python and `cryptocom-agent-client` , create your dApp there.
* Your dApp can now call Bedrock without manually providing credentials.

[Learn more about IAM roles.](https://aws.amazon.com/iam/features/manage-roles/)

#### 3. (Optional) Create a Knowledge Base

Use AWS Knowledge Base if you want the agent to pull answers from your own data:

* Prepare your data. If using S3, ensure the bucket is in the same region as your Bedrock instance.
* Create an IAM user with the necessary permissions, such as Bedrock access, S3 vector permissions (if using S3 Vector), and S3 bucket access (if your data is stored in S3).
* Create the Knowledge Base with your data source under the IAM user.
* Note down the Knowledge Base ID, you’ll use it when initializing your Crypto.com AI Agent.

[Learn more about AWS Knowledge Bases.](https://aws.amazon.com/bedrock/knowledge-bases/)

#### **4. (Optional) Create a Guardrail**

Use a Guardrail ID and version to enforce content rules and safety checks:

* Prepare an IAM role with permissions like `bedrock:CreateGuardrail`.
* In the Bedrock console, create a guardrail using that IAM role.
* A single guardrail can have multiple versions.
* Copy the Guardrail ID and version, you’ll use them to apply the guardrail to your models or agents.

[Learn more about AWS Guardrail.](https://aws.amazon.com/bedrock/guardrails/)

### Get Started

Here is the sample code using AWS Bedrock as the provider, with the AWS access key or an IAM role.&#x20;

{% tabs %}
{% tab title="AWS Access Key" %}

```python
from crypto_com_agent_client import Agent, SQLitePlugin

agent = Agent.init(
    llm_config={
       "provider": "Bedrock",
        "model": "your-ai-model-name",  # Example: "anthropic.claude-3-sonnet-20240229-v1:0"
        "provider-api-key": f"{your_aws_access_key_id}:{your_aws_secret_access_key}:{your_aws_region}",
        "location-id": aws_region,  # AWS region for Bedrock, example: "us-east-1"
        "knowledge-base-id": your_knowledge_base_id,  # AWS Bedrock Knowledge Base ID
        "guardrail-id": your_guardrail_id,  # Optional AWS Bedrock Guardrail ID 
        "guardrail-version": your_guardrail_version,  # Optional AWS Bedrock Guardrail version
        "model-kwargs": your_model_kwargs,  # Optional model-specific parameters, example: {"temperature": 0.7, "max_tokens": 1024}
        "debug-logging": True,  # Enable to see knowledge base queries
        "temperature": 0.7,  # Will be overridden by model_kwargs if specified
        "transfer-limit": -1,  # -1 means no limit (unlimited), 0 disables transfers completely, any positive number (e.g. 5) allows exactly that transfer amount
    },
    blockchain_config={
        "api-key": os.getenv("DEVELOPER_SDK_API_KEY"),
    },
    plugins={
        "storage": SQLitePlugin(db_path="bedrock_agent.db"),
        "personality": {
            "tone": "professional",
            "language": "English",
            "verbosity": "medium",
        },
        "instructions": "You are an AI assistant with access to company knowledge base. Provide accurate, helpful responses based on available information."
    },
)


response = agent.interact("What are the latest blockchain trends?")
print(response)
```

{% endtab %}

{% tab title="IAM role" %}

```python
from crypto_com_agent_client import Agent, SQLitePlugin

agent = Agent.init(
    llm_config={
       "provider": "Bedrock",
        "model": "your-ai-model-name",  # Example: "anthropic.claude-3-sonnet-20240229-v1:0",
        "provider-api-key": None,
        "location-id": aws_region,  # AWS region for Bedrock, example: "us-east-1"
        "knowledge-base-id": your_knowledge_base_id,  # Optional AWS Bedrock Knowledge Base ID
        "guardrail-id": your_guardrail_id,  # Optional AWS Bedrock Guardrail ID 
        "guardrail-version": your_guardrail_version,  # Optional AWS Bedrock Guardrail version
        "model-kwargs": your_model_kwargs,  # Optional model-specific parameters, example: {"temperature": 0.7, "max_tokens": 1024}
        "debug-logging": True,  # Enable to see knowledge base queries
        "temperature": 0.7,  # Will be overridden by model_kwargs if specified
    },
    blockchain_config={
        "api-key": os.getenv("DEVELOPER_SDK_API_KEY"),
    },
    plugins={
        "storage": SQLitePlugin(db_path="bedrock_agent.db"),
        "personality": {
            "tone": "professional",
            "language": "English",
            "verbosity": "medium",
        },
        "instructions": "You are an AI assistant with access to company knowledge base. Provide accurate, helpful responses based on available information."
    },
)


response = agent.interact("What are the latest blockchain trends?")
print(response)
```

{% endtab %}
{% endtabs %}

{% hint style="warning" %}
**Note:**&#x20;

It is recommended to store sensitive data in environment variables.&#x20;

Avoid hardcoding or exposing any keys in both development and production environments.
{% endhint %}


# AI Agent SDK Examples

This page provides examples and demonstrations of how the AI Agent SDK interacts with the blockchain to perform on-chain actions:

1. Clone and run a local signer app for processing signature requests. The Magic Link will redirect to this app, allowing you to sign transactions or token swaps when interacting with the AI agent SDK.

{% content-ref url="/pages/KDVaWdniN5Y7U3UFcvrl" %}
["Magic Link" Signer](/crypto.com-ai-agent-sdk/ai-agent-sdk-examples/magic-link-signer)
{% endcontent-ref %}

2. The Crypto.com AI Agent Chatbot guide demonstrates how to build a chatbot app that allows users to interact with blockchain services through natural language.

{% content-ref url="/pages/bPCTxvCMMtcE6SxkLmIl" %}
[AI Agent Chatbot](/crypto.com-ai-agent-sdk/ai-agent-sdk-examples/ai-agent-chatbot)
{% endcontent-ref %}

3. The Crypto.com AI Agent SDK BigQuery Integration example provides a BigQuery integration for the Crypto.com AI Agent Client, enabling natural language queries against blockchain data stored in Google Cloud BigQuery. The integration allows users to query blockchain information using conversational language, which is then converted to SQL and executed against BigQuery datasets.

{% content-ref url="/pages/7ngORRw0PiGswv3xGX24" %}
[Crypto.com AI Agent SDK BigQuery Integration](/crypto.com-ai-agent-sdk/ai-agent-sdk-examples/crypto.com-ai-agent-sdk-bigquery-integration)
{% endcontent-ref %}

Stay tuned for more examples on our [Crypto.com AI Agent SDK Updates](https://x.com/cryptocom_agent).&#x20;


# "Magic Link" Signer

## Magic Link Signer

To successfully test and utilize the Magic Link functionality, you need to clone and run a local signer app that processes the signature requests. The **magic link** will redirect to this app, allowing you to sign transactions or token swaps.

**Steps to Set Up the Magic Link Signer App**

1. **Clone the Signer App Repository**: Clone the repository that contains the signer app:

   ```javascript
   git clone https://github.com/crypto-com/cdc-ai-agent-signer-app
   ```
2. **Install Dependencies**: Navigate into the cloned directory and install the required dependencies:

   ```javascript
   cd cdc-ai-agent-signer-app
   npm install
   ```
3. **Run the Signer App**: Start the app using the following command:

   ```javascript
   npm run dev
   ```

   This will start the signer app locally on `http://localhost:5173`.
4. **Pass the Provider in the Client Library**: In the client library configuration, you need to pass this local signer app as the provider in the options:

   ```javascript
   "custom": {
     "provider": "http://localhost:5173"
   }
   ```
5. **Magic Link Redirection**: When you generate a magic link for actions such as sending transactions or swapping tokens, it will redirect the user to this signer app (`http://localhost:5173`). The developer can customize this app to handle various signing operations or UI changes as per their project requirements.

### **Example Magic Link Response**

Here’s how the response looks with a magic link:

```javascript
{
  "status": "Success",
  "action": "SendTransaction",
  "message": "Signature URL created successfully. Please sign the transaction on this link.",
  "data": {
    "magicLink": "http://localhost:5173/sign-transaction/{transactionId}?token={token}"
  }
}
```

In this case, the magic link will redirect to `http://localhost:5173`, where the signer app will display the details of the transaction for the user to approve or reject.

#### **Customizing the Signer App**

The developer can further customize the signer app by modifying the cloned repository to:

* Add custom branding
* Implement additional validation
* Modify the signing flow according to specific use cases

By running the app locally, the developer can see the magic link redirect in action and tweak the behavior to suit their project.


# AI Agent Chatbot

The [Crypto.com AI Agent Chatbot](https://github.com/crypto-com/developer-platform-sdk-examples/tree/main/sdk-examples/categories/chatbot) is an example of an application built with the suite of AI Agent SDK tools, demonstrating how to build a chatbot app that allows users to interact with blockchain services with natural language.

This example contains both the **AI-powered chatbot backend** (Flask server) and the **React frontend** (Vite app) for interacting with the chatbot.

### Structure

```markdown
├── README.md                # Monorepo root guide
├── ai-chatbot-server/       # Python Flask backend
│   └── README.md
├── ai-chatbot-app/          # React + Vite frontend
│   └── README.md
```

### Installation

#### 1. Clone the repository

```
git clone https://github.com/crypto-com/developer-platform-sdk-examples.git
cd developer-platform-sdk-examples/sdk-examples/categories/chatbot
```

#### 2. Backend setup (Python)

```python
cd ai-chatbot-server
python -m venv venv
source venv/bin/activate  # or .\venv\Scripts\activate on Windows
pip install -r requirements.txt
```

#### 3. Frontend setup (React + Vite)

```
cd ../ai-chatbot-app
npm install
```

#### 4. Config environment variables

Create `ai-chatbot-server/.env`&#x20;

```
OPENAI_API_KEY=your-openai-api-key
SDK_API_KEY=your-sdk-api-key        // Your Crypto.com Developer Platform API key
PRIVATE_KEY=your-wallet-private-key
AI_CHATBOT_APP_URL=http://localhost:5173
```

{% hint style="info" %}
For Crypto.com Developer Platform API Key, [click here to learn how to obtain your Crypto.com Developer Platform API key](/crypto.com-developer-platform/developer-platform-dashboard).
{% endhint %}

Create `ai-chatbot-app/.env`

```
VITE_CHATBOT_SERVER_BASE_URL=http://localhost:5000
```

### Usage

#### Start the backend (Flask)

```bash
cd ai-chatbot-server
flask run
```

This will start the Flask server at `http://localhost:5000`&#x20;

#### Start the frontend (Vite)

```bash
cd ai-chatbot-app
npm run dev
```

This will start the React app at `http://localhost:5173`&#x20;

### Demo Video

{% embed url="<https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FktUMyU5bBece2vVjrTg7%2Fuploads%2FDEObFXhm6qLmxKgH9ZJI%2FAI%20Agent%20Chatbot%20Demo.mp4?alt=media&token=18ab6cad-57b5-444c-86b8-2192808f6caf>" %}


# Crypto.com AI Agent SDK BigQuery Integration

This example provides a BigQuery integration for the Crypto.com AI Agent Client, enabling natural language queries against blockchain data stored in Google Cloud BigQuery. The integration allows users to query blockchain information using conversational language, which is then converted to SQL and executed against BigQuery datasets.

### Features

* **Natural Language Queries**: Convert plain English questions into SQL queries
* **Multi-Chain Support**: Query data from multiple blockchain networks (Cronos zkEVM, Cronos EVM)
* **Automated Schema Management**: Automatically download and cache table schemas
* **Cost Controls**: Built-in query limits and timeouts to manage BigQuery costs
* **Comprehensive Blockchain Tools**: Specialized tools for querying blocks, transactions, and addresses
* **Real-time Results**: Get instant answers to blockchain data questions

### Requirements

* Python 3.12+
* Google Cloud Project with BigQuery enabled
* API Keys of AI provider, refer to the [Dynamic AI Model Manager ](/crypto.com-ai-agent-sdk/core-concepts-overview/dynamic-ai-model-manager)to see which providers are supported by the AI Agent SDK.
* Crypto.com Developer Platform API key, [click here to learn how to obtain your Crypto.com Developer Platform API key](/crypto.com-developer-platform/developer-platform-dashboard).
* Google Cloud credentials configured, [click here to learn how to install gcloud CLI](https://cloud.google.com/sdk/docs/install)

#### Supported Datasets

This integration supports multiple blockchain datasets:

* **Cronos zkEVM Mainnet**: `cronos_zkevm_mainnet`&#x20;
  * Click [here](https://console.cloud.google.com/bigquery/analytics-hub/discovery/projects/596763852542/locations/us/dataExchanges/cronos_zkevm_1922b84ea5e/listings/cronos_zkevm_mainnet_1922b96033f) to subscribe it
* **Cronos EVM Mainnet**: `public_preview___blockchain_analytics_cronos_mainnet`&#x20;
  * Click [here](https://console.cloud.google.com/bigquery/analytics-hub/discovery/projects/938420344946/locations/us/dataExchanges/preview_google_cloud_blockchain_analytics_189b1d89e86/listings/public_preview_blockchain_analytics_cronos_mainnet_chain_18add08d212) to subscribe it

### Installation

**1. Clone the repository**

```bash
git clone https://github.com/crypto-com/developer-platform-sdk-examples.git
cd developer-platform-sdk-examples/integrations/bigqueryai
```

**2. Install dependencies:**

```
pip install -r requirements.txt
```

**3. Set up environment variables**:&#x20;

Create a `.env` file in the project root:

```
# Required
PROJECT_ID=your-google-cloud-project-id
OPENAI_API_KEY=your-openai-api-key
DASHBOARD_API_KEY=your-cryptocom-developer-platform-api-key
PRIVATE_KEY=your-private-key

# Optional
DEBUG_LOGGING=false
```

**4. Configure Google Cloud credentials**:

```
# Option 1: Service account key
export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/service-account-key.json"

# Option 2: gcloud CLI
gcloud auth application-default login
```

### Usage

#### Basic Usage

Run the main script:

```
python bigquery.py
```

The script will:

1. Initialize the BigQuery connection
2. Download and cache table schemas
3. Start an interactive session for natural language queries

#### Example Queries

Examples of natural language questions you can ask about blockchain data:

```
"How many transactions were there in the last 24 hours?"
"What are the top 10 addresses by transaction count?"
"Show me the latest blocks"
"What's the average gas price for recent transactions?"
"Find all transactions with value greater than 1000 CRO"
"What blocks were mined in the last hour?"
```


# AWS Lambda with Docker

Deploy cryptocom-agent-client as a serverless AWS Lambda function using Docker.

### Overview

This example demonstrates how to:

* Deploy a [cryptocom-agent-client](https://pypi.org/project/cryptocom-agent-client/) powered AI agent to AWS Lambda
* Use Docker containers for Lambda deployment
* Create custom tools (functions) the agent can invoke
* Query blockchain data through the Crypto.com Developer Platform

### Features

* **AI Agent**: Uses OpenAI GPT-4o-mini with [cryptocom-agent-client](https://pypi.org/project/cryptocom-agent-client/)
* **Custom Tools**:
  * `get_current_time()` - Returns current local and UTC time
  * `fibonacci(n)` - Calculates the nth Fibonacci number
* **Blockchain Integration**: Query Cronos blockchain data via [Developer Platform Dashboard](/crypto.com-developer-platform/developer-platform-dashboard) API
* **Serverless**: Auto-scaling, pay-per-use AWS Lambda deployment

### Prerequisites

* [AWS CLI](https://aws.amazon.com/cli/) configured with appropriate credentials
* [Docker Desktop](https://www.docker.com/products/docker-desktop/) running
* [jq](https://jqlang.github.io/jq/) for JSON processing
* AWS account with permissions for Lambda, ECR, and IAM
* [OpenAI API key](https://platform.openai.com/api-keys)
* [Crypto.com Developer Platform API key](https://developer.crypto.com/)

### Quick Start

#### 1. Configure Environment

```bash
cp .env.example .env
```

Edit `.env` with your credentials:

```bash
# AWS (use profile or access keys)
AWS_PROFILE=default
AWS_DEFAULT_REGION=us-east-1

# API Keys
OPENAI_API_KEY=sk-...
DASHBOARD_API_KEY=your-dashboard-api-key
```

#### 2. Deploy to AWS

```bash
./deploy.sh
```

This will:

* Build Docker image (ARM64 optimized)
* Create ECR repository and push image
* Create IAM role with basic execution permissions
* Deploy Lambda function (300s timeout, 1024MB memory)

#### 3. Test the Function

```bash
# Default prompt
./run.sh

# Custom prompts
./run.sh "What is the current time?"
./run.sh "Calculate fibonacci of 10"
./run.sh "Get the latest block on Cronos"
```

#### 4. Clean Up

```bash
./cleanup.sh
```

### Local Testing

Test the Lambda function locally before deploying:

```bash
./test-local.sh "What is the current time?"
```

### Project Structure

```markdown
.
├── handler.py          # Lambda handler with AI agent
├── requirements.txt    # Python dependencies
├── Dockerfile          # Container configuration
├── deploy.sh           # Deploy to AWS Lambda
├── run.sh              # Invoke the Lambda function
├── test-local.sh       # Test locally with Docker
├── cleanup.sh          # Remove all AWS resources
└── .env.example        # Environment template
```

### Customization

#### Adding Custom Tools

Edit `handler.py` to add your own tools:

```python
from crypto_com_agent_client import tool

@tool
def my_custom_tool(param: str) -> str:
    """
    Description of what this tool does.

    Args:
        param: Description of parameter

    Returns:
        Description of return value
    """
    # Your implementation
    return result
```

Register the tool in the agent initialization:

```python
agent = Agent.init(
    llm_config={...},
    blockchain_config={...},
    plugins={
        "tools": [get_current_time, fibonacci, my_custom_tool],
    },
)
```

#### Changing the LLM Model

Modify the `llm_config` in `handler.py`:

```python
llm_config={
    "provider": Provider.OpenAI,
    "model": "gpt-4o",  # or "gpt-3.5-turbo", etc.
    "provider-api-key": openai_api_key,
}
```

#### Using Different Providers

The `cryptocom-agent-client` supports multiple LLM providers:

```python
from crypto_com_agent_client.lib.enums.provider_enum import Provider

# AWS Bedrock
llm_config={
    "provider": Provider.AWSBedrock,
    "model": "anthropic.claude-3-haiku-20240307-v1:0",
}

# Google AI
llm_config={
    "provider": Provider.GoogleAI,
    "model": "gemini-pro",
    "provider-api-key": google_api_key,
}
```

### Architecture

```markdown
┌─────────────┐    ┌─────────────────┐    ┌──────────────┐
│   Client    │───>│  AWS Lambda     │───>│   OpenAI     │
│  (run.sh)   │    │  (handler.py)   │    │   GPT-4o     │
└─────────────┘    └────────┬────────┘    └──────────────┘
                            │
                            v
                   ┌─────────────────┐
                   │   Crypto.com    │
                   │   Dashboard     │
                   │   (Blockchain)  │
                   └─────────────────┘
```

### Lambda Configuration

| Setting      | Value                |
| ------------ | -------------------- |
| Runtime      | Python 3.12 (Docker) |
| Architecture | ARM64                |
| Timeout      | 300 seconds          |
| Memory       | 1024 MB              |

### AWS Resource Identifiers

#### What is ARN?

ARN (Amazon Resource Name) is a unique identifier for any resource in AWS.

**Format:**

```
arn:aws:<service>:<region>:<account-id>:<resource-type>/<resource-name>
```

**Example for this Lambda:**

```
arn:aws:lambda:us-east-1:123456789012:function:cryptocom-agent-lambda
         │       │          │              │
         │       │          │              └─ Function name
         │       │          └─ Your AWS account ID
         │       └─ Region (e.g., us-east-1)
         └─ Service (lambda)
```

#### Resource Identifiers Used

| Resource        | Identifier                      |
| --------------- | ------------------------------- |
| Lambda Function | `cryptocom-agent-lambda`        |
| ECR Repository  | `cryptocom-agent-lambda`        |
| IAM Role        | `lambda-exec-cryptocom-agent`   |
| Docker Image    | `cryptocom-agent-lambda:latest` |

When invoking the Lambda in the same account/region, scripts use just the function name. AWS resolves the full ARN automatically from your credentials.

### Security Notes

* API keys are passed at runtime in the request payload, not stored in Lambda environment
* The IAM role has minimal permissions (`AWSLambdaBasicExecutionRole` only)
* Never commit `.env` files with real credentials

### Troubleshooting

#### Docker Build Issues

* Ensure Docker Desktop is running
* On macOS, the build uses ARM64 for Apple Silicon optimization

#### Lambda Timeout

* Default timeout is 300 seconds
* First invocation may take longer due to cold start
* Subsequent invocations use cached agent instance

#### ECR Push Failures

* Verify AWS credentials are configured: `aws sts get-caller-identity`
* Check ECR permissions in your AWS account

### Related Resources

* [cryptocom-agent-client on PyPI](https://pypi.org/project/cryptocom-agent-client/)
* [Crypto.com Developer Platform](https://developer.crypto.com/)
* [AWS Lambda Container Images](https://docs.aws.amazon.com/lambda/latest/dg/images-create.html)

### License

Apache-2.0


# On-Chain Developer Platform

The Crypto.com On‑Chain Developer Platform is a comprehensive toolkit that helps developers build, manage, and interact with applications on Cronos EVM and Cronos zkEVM. It offers all the essential tools needed to access on-chain data, interact with smart contracts, manage tokens and wallets, and integrate DeFi or exchange-related features.&#x20;

The platform consists of two core components that work together to support seamless blockchain development:

#### 1. Developer Platform Dashboard

The Dashboard is your control center for managing access to the Developer Platform. With it, you can:

* Create and manage projects
* Generate and manage API keys
* Assign Cronos chain permissions per project
* Monitor data usage and infrastructure health

This service provides secure, centralized management of projects and credentials, allowing developers to control access to blockchain functionality through API keys tailored to specific environments or teams.

{% content-ref url="/pages/BTultEZRI7GfltzdChTh" %}
[Developer Platform Dashboard](/crypto.com-developer-platform/developer-platform-dashboard)
{% endcontent-ref %}

#### 2. Developer Platform Client SDK (Python & TypeScript)

This SDK is a client library designed to interact with the Developer Platform Service API in a familiar, idiomatic way. It abstracts HTTP calls into clean methods, providing support for:

* Wallet operations (create, retrieve balances)
* Token operations (balance, transfer, swap and wrap operations for native, ERC‑20 and ERC‑721 tokens)
* Transaction queries (by address, hash, status)
* Smart contract access
* Block data retrieval
* CronosID lookup and reverse lookup
* DeFi protocol interactions (e.g. farms & tokens)
* Market and exchange data

Developers can import this SDK in Python or TypeScript/JavaScript and call high-level modules directly (e.g. Token.getNativeTokenBalance, Transaction.getTransactionByHash) with minimal setup.

{% content-ref url="/pages/3AMzrIIV0wZkM40Uo55X" %}
[On-Chain Developer Platform Client SDK](/crypto.com-developer-platform/on-chain-developer-platform-client-sdk)
{% endcontent-ref %}

***


# Developer Platform Dashboard

### Introduction

The Crypto.com Developer Platform Dashboard is a service that enables developers to securely manage user authentication, API keys, and access permissions for building on the Cronos chain, with the [Developer Platform Dashboard Client Application](https://pypi.org/project/crypto-com-developer-platform-client/).&#x20;

It serves as the gateway for developers to generate API keys that unlock the full potential of the Developer Platform Service API, which allows developers to interact with core blockchain infrastructure on both Cronos EVM and Cronos zkEVM.

With a single integration, developers can access essential capabilities such as:&#x20;

* Sending and receiving native and ERC20/ERC721 tokens
* Querying wallet balances, transactions, and on-chain data
* Interacting with smart contracts and retrieving ABI/bytecode
* Accessing DeFi protocol data, staking information, and liquidity pools
* Performing Cronos ID resolution for blockchain-based identity lookups
* Monitoring blocks, fees, and network activity

The platform is designed to support a wide range of applications. For details on how to apply them, visit [Usage under On-Chain Developer Platform Client SDK](/crypto.com-developer-platform/on-chain-developer-platform-client-sdk#usage).

### Features

The platform is built to support core development workflows on Cronos through a reliable, production-ready API. It focuses on practical capabilities that allow developers to integrate with the chain efficiently and securely.

**API Key Management**

Manage access through scoped API keys tied to individual projects. Keys can be created, named, revoked, and rotated directly through the dashboard, enabling granular control across environments and teams.

**Smart Contract Tooling**

Facilitates querying of smart contract ABI and bytecode for contract integration.&#x20;

**On-Chain Data Retrieval**

Developers can query individual transactions, block metadata, and current network conditions (e.g., gas fees, block height). These endpoints support features like transaction tracking, analytics dashboards, and automation workflows

**SDK Integration and Extendability**

The platform is natively compatible with both the Developer Platform Client SDK and the AI Agent SDK. This enables fast development of tools, bots, and interfaces that use natural language or scripting to trigger blockchain operations.

### Get Started

To begin using the Developer Platform Dashboard, follow the steps below to set up your account, create a project, and generate an API key.

{% embed url="<https://developer.crypto.com/auth>" %}

#### Step 1

Sign Up for an Account for the Developer Platform Dashboard using your email address.

<figure><img src="/files/n42ID3vPJe9auQYUJ69k" alt="" width="332"><figcaption></figcaption></figure>

#### Step 2

Check your inbox for the verification email. Click **Verify Email** to activate your account.

<figure><img src="/files/GMNX3MXckOcCcsxrQoMk" alt="" width="375"><figcaption></figcaption></figure>

#### Step 3

After verification, log in to the Developer Platform using your registered email and password.

<figure><img src="/files/sWahLAHB69C8xiFbON2N" alt="" width="321"><figcaption></figcaption></figure>

#### Step 4

From the dashboard, click **New Project.**

<figure><img src="/files/rYeUuocSiJPNIrckRBKX" alt="" width="375"><figcaption></figcaption></figure>

#### Step 5

Set a Project Name, Description and the Cronos Chain for your project.

<figure><img src="/files/LbHYPGyfk6qQkqqBzJmY" alt="" width="375"><figcaption></figcaption></figure>

<figure><img src="/files/OsgaBxYDaWR1JfzURcxR" alt="" width="375"><figcaption></figcaption></figure>

#### Step 6

Once your project is created, navigate to the project and select **Generate API Key**.

<figure><img src="/files/wV4vAhFzJQOdeqj2Ie9Y" alt="" width="375"><figcaption></figcaption></figure>

#### Step 7

Name your API key, recommand to use the purpose as the name for easy tracking.

<figure><img src="/files/FdTcuTJdAc13dywAI8yD" alt="" width="375"><figcaption></figcaption></figure>

<figure><img src="/files/YdSxdX4xWa5oxwxJg6fX" alt="" width="375"><figcaption></figcaption></figure>

Your API Key is now ready to use. Save the API key in a secure environment. &#x20;

<figure><img src="/files/jZVRYdARkvxgpUVhJYql" alt="" width="375"><figcaption></figcaption></figure>


# On-Chain Developer Platform Client SDK

## Introduction

The Crypto.com On-Chain Developer Platform Client SDK is designed to interact seamlessly with the Crypto.com Developer Platform Service API. This client library simplifies interactions with the Cronos blockchain, supporting native tokens, ERC20 tokens, smart contracts, transactions, blocks, and wallets.

### Features

{% hint style="info" %}
**Currently in beta**: Expect frequent updates and potential changes in future releases.
{% endhint %}

* Supports `Cronos EVM` and `Cronos zkEVM`.
* Simple and intuitive API for interacting with Cronos blockchain networks.
* Native and ERC20/ERC721 token operations
* Token transfers, wrapping, and swapping.
* Transaction queries by address or hash, and fetching transaction statuses.
* Smart contract ABI and bytecode fetching by contract address.
* Wallet creation and balance management.
* Cronos ID forward/reverse resolution.
* DeFi protocols and features, including yield farming and token utilities.
* Crypto.com exchange data

### Installation

{% tabs %}
{% tab title="Python" %}
To install the package, run the following command:

```python
pip install crypto-com-developer-platform-client
```

{% endtab %}

{% tab title="TypeScript / JavaScript" %}
To install the package, run the following command in your project directory:

```
npm install @crypto.com/developer-platform-client
```

{% endtab %}
{% endtabs %}

### Usage

Here’s how you can use the Crypto.com Client for Developer Platform in your project:

#### Initialize the Client

First, initialize the client with your API key. To obtain an API key, please refer to the following page:

{% content-ref url="/pages/BTultEZRI7GfltzdChTh" %}
[Developer Platform Dashboard](/crypto.com-developer-platform/developer-platform-dashboard)
{% endcontent-ref %}

{% tabs %}
{% tab title="Python" %}

```python
from crypto_com_developer_platform_client import Client

Client.init(
    api_key="YOUR_API_KEY",
    provider="https://your-provider.com"  # Optional
)
```

{% endtab %}

{% tab title="TypeScript / JavaScript" %}

```typescript
import { Client } from '@crypto.com/developer-platform-client';

Client.init({
  apiKey: 'YOUR_API_KEY',
  provider: 'https://your-provider-url.com', // Optional
});
```

{% endtab %}
{% endtabs %}

#### Supported Chains

The SDK supports both **Cronos EVM** and **Cronos ZK EVM** networks.

{% tabs %}
{% tab title="Python" %}

```python
from crypto_com_developer_platform_client.interfaces.chain_interfaces import CronosEvm, CronosZkEvm

CronosEvm.MAINNET     # Chain ID: 25
CronosEvm.TESTNET     # Chain ID: 338
CronosZkEvm.MAINNET   # Chain ID: 388
CronosZkEvm.TESTNET   # Chain ID: 240
```

{% endtab %}

{% tab title="TypeScript / JavaScript" %}

<pre class="language-typescript"><code class="lang-typescript"><strong>import { CronosEvm, CronosZkEvm } from '@crypto.com/developer-platform-client';
</strong>
CronosEvm.Mainnet; // Chain ID: 25
CronosEvm.Testnet; // Chain ID: 338
CronosZkEvm.Mainnet; // Chain ID: 388
CronosZkEvm.Testnet; // Chain ID: 240
</code></pre>

{% endtab %}
{% endtabs %}

#### Modules and Examples

Below section provides detailed information on these blockchain functions and example interactions, guiding developers on how to effectively interact with Cronos Chains using the Developer Platform Client SDK.

{% content-ref url="/pages/WtCRA7xj6YnCxHuqyfK0" %}
[Wallet Module](/crypto.com-developer-platform/on-chain-developer-platform-client-sdk/wallet-module)
{% endcontent-ref %}

{% content-ref url="/pages/kFXul71c58dO9uQFOLLe" %}
[Token Module](/crypto.com-developer-platform/on-chain-developer-platform-client-sdk/token-module)
{% endcontent-ref %}

{% content-ref url="/pages/k0Nwxh2PoS7YCaXMZcd0" %}
[Transaction Module](/crypto.com-developer-platform/on-chain-developer-platform-client-sdk/transaction-module)
{% endcontent-ref %}

{% content-ref url="/pages/3HvwAV6tgoxqSSG4PLxp" %}
[Block Module](/crypto.com-developer-platform/on-chain-developer-platform-client-sdk/block-module)
{% endcontent-ref %}

{% content-ref url="/pages/y7AhF15U4HGW6sG7YgRb" %}
[Contract Module](/crypto.com-developer-platform/on-chain-developer-platform-client-sdk/contract-module)
{% endcontent-ref %}

{% content-ref url="/pages/arObB9kZv5BzNGT29Qhg" %}
[CronosID Module](/crypto.com-developer-platform/on-chain-developer-platform-client-sdk/cronosid-module)
{% endcontent-ref %}

{% content-ref url="/pages/3qWjI2eV3uzKw7c5OF3O" %}
[Defi Module](/crypto.com-developer-platform/on-chain-developer-platform-client-sdk/defi-module)
{% endcontent-ref %}

{% content-ref url="/pages/qrYepsZzhEHhzwH8LPpb" %}
[Exchange Module](/crypto.com-developer-platform/on-chain-developer-platform-client-sdk/exchange-module)
{% endcontent-ref %}

{% content-ref url="/pages/aWiQJQgvChafFotESSsK" %}
[Event Module](/crypto.com-developer-platform/on-chain-developer-platform-client-sdk/event-module)
{% endcontent-ref %}

{% content-ref url="/pages/SKfHkbzjYYAVYdfcDTZb" %}
[Network Module](/crypto.com-developer-platform/on-chain-developer-platform-client-sdk/network-module)
{% endcontent-ref %}

***


# Wallet Module

Wallet module handles operations related to wallet creation and balance retrieval.

To learn more about how to use the AI Agent SDK to interact with the wallet module, please visit [AI Agent SDK Wallet Management](/crypto.com-ai-agent-sdk/core-concepts-overview/blockchain-functions/wallet-management).

#### 1.1 Create Wallet

Creates a new wallet

{% tabs %}
{% tab title="Python" %}
Function Name

```python
create_wallet
```

{% tabs %}
{% tab title="Query" %}

* Example Code

  ```python
  from crypto_com_developer_platform_client import Wallet

  wallet = Wallet.create_wallet()
  print(wallet)
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  The address of the new wallet.
  ```
* Errors

  ```python
  ValueError: If the Wallet class is not initialized with a Client instance.
  ```
* Example Return

  ```python
  {'status': 'Success', 'data': {'address': 'example-address', 'privateKey': 'example-private-key', 'mnemonic': 'example-mnemonic'}}
  ```

{% endtab %}
{% endtabs %}
{% endtab %}

{% tab title="TypeScript" %}
Function Name

```typescript
create
```

{% tabs %}
{% tab title="Query" %}

* Example Code

  ```typescript
  import { Wallet } from '@crypto.com/developer-platform-client';

  try {
    const wallet = await Wallet.create();
    console.log(wallet);
  }
  catch(err) {
    console.log(err);
  }
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```typescript
  {Promise<ApiResponse<CreateWalletData>>}: A promise that resolves to the newly created wallet details.
  ```
* Errors

  ```typescript
  {Error}: Throws an error if the request fails.
  ```
* Example Return

  ```typescript
  {
    status: 'Success',
    data: {
      address: 'example-address',
      privateKey:'example-private-key',
      mnemonic: 'example-mnemonic'
    }
  }
  ```

{% endtab %}
{% endtabs %}
{% endtab %}
{% endtabs %}

#### 1.2 Get Wallet Balance

Retrieves the balance of the wallet for a specific address.

{% tabs %}
{% tab title="Python" %}
Function Name

```python
get_balance
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  wallet_address (str): The address to get the balance for (CronosIds with the `.cro` suffix are supported, e.g. `xyz.cro`)
  ```
* Example Code

  ```python
  from crypto_com_developer_platform_client import Wallet

  balance = Wallet.get_balance('example-wallet')
  print(balance)
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  The balance of the wallet.
  ```
* Errors

  ```python
  ValueError: If the Wallet class is not initialized with a Client instance.
  ```
* Example Return

  ```python
  {'status': 'Success', 'data': {'balance': 'example-balance'}}
  ```

{% endtab %}
{% endtabs %}
{% endtab %}

{% tab title="TypeScript" %}
Function Name

```typescript
balance
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```typescript
  {string} walletAddress: The wallet address to fetch the balance for (CronosIds with the `.cro` suffix are supported, e.g. `XXX.cro`)
  ```
* Example Code

  ```typescript
  import { Wallet } from '@crypto.com/developer-platform-client';

  try {
    const balance = await Wallet.balance('example-wallet');
    console.log(balance);
  }
  catch(err) {
    console.log(err);
  }
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```typescript
  {Promise<ApiResponse<Balance>>}: A promise that resolves to the balance of the wallet.
  ```
* Errors

  ```typescript
  {Error}: Throws an error if the request fails.
  ```
* Example Return

  ```typescript
  { status: 'Success', data: { balance: 'example-balance' } }
  ```

{% endtab %}
{% endtabs %}
{% endtab %}
{% endtabs %}


# Token Module

Token module handles operations related to native tokens, ERC20 tokens, and NFTs.

To learn more about how to use the AI Agent SDK to interact with the token module, please visit [AI Agent SDK Token Interaction](/crypto.com-ai-agent-sdk/core-concepts-overview/blockchain-functions/token-interaction).

#### 2.1 Get Native Token Balance

Fetches the native token balance of a specific wallet address.

{% tabs %}
{% tab title="Python" %}
Function Name

```python
get_native_balance
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  address (str): The address to get the balance for (CronosIds with the `.cro` suffix are supported, e.g. `xyz.cro`)
  ```
* Example Code

  ```python
  from crypto_com_developer_platform_client import Token

  balance = Token.get_native_balance('example-wallet')
  print(balance)
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  The balance of the native token.
  ```
* Errors

  ```python
  ValueError: If the Token class is not initialized with a Client instance.
  ```
* Example Return

  ```python
  {'status': 'Success', 'data': {'balance': 'example-balance'}}
  ```

{% endtab %}
{% endtabs %}
{% endtab %}

{% tab title="TypeScript" %}
Function Name

```typescript
getNativeTokenBalance
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```typescript
  {string} address: The wallet address (or CronosId `.cro`) to check.
  ```
* Example Code

  ```typescript
  import { Token } from '@crypto.com/developer-platform-client';

  try {
    const balance = await Token.getNativeTokenBalance('example-wallet');
    console.log(balance);
  }
  catch(err) {
    console.log(err);
  }
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```typescript
  {Promise<ApiResponse<Balance>>}: A promise that resolves to the native token balance.
  ```
* Errors

  ```typescript
  {Error}: Throws an error if the request fails.
  ```
* Example Return

  ```typescript
  { status: 'Success', data: { balance: 'example-balance' } }
  ```

{% endtab %}
{% endtabs %}
{% endtab %}
{% endtabs %}

#### 2.2 Get ERC20 Token Balance

Fetches the ERC20 token balance of a wallet for a given ERC20 contract.

{% tabs %}
{% tab title="Python" %}
Function Name

```python
get_erc20_balance
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  wallet_address (str): The address to get the balance for (CronosIds with the `.cro` suffix are supported, e.g. `xyz.cro`)
  contract_address (str): The contract address to get the balance for.
  block_height (str): The block height to get the balance for.
  ```
* Example Code

  ```python
  from crypto_com_developer_platform_client import Token

  balance = Token.get_erc20_balance('example-wallet', 'example-contract', 'latest')
  print(balance)
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  The balance of the ERC20 token.
  ```
* Errors

  ```python
  ValueError: If the Token class is not initialized with a Client instance.
  ```
* Example Return

  ```python
  {'status': 'Success', 'data': {'balance': 'example-balance'}}
  ```

{% endtab %}
{% endtabs %}
{% endtab %}

{% tab title="TypeScript" %}
Function Name

```typescript
getERC20TokenBalance
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```typescript
  {string} address: The wallet address (or CronosId `.cro`) to check.
  {string} contractAddress: The ERC20 contract address.
  {string} [blockHeight='latest']: Optional block height (default 'latest').
  ```
* Example Code

  ```typescript
  import { Token } from '@crypto.com/developer-platform-client';

  try {
    const balance = await Token.getERC20TokenBalance('example-wallet', 'example-contract');
    console.log(balance);
  }
  catch(err) {
    console.log(err);
  }
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```typescript
  {Promise<ApiResponse<TokenBalance>>}: A promise that resolves to the ERC20 token balance.
  ```
* Errors

  ```typescript
  {Error}: Throws an error if the request fails.
  ```
* Example Return

  ```typescript
  { status: 'Success', data: { balance: 'example-balance' } }
  ```

{% endtab %}
{% endtabs %}
{% endtab %}
{% endtabs %}

#### 2.3 Transfer Token

Transfers native or ERC20 tokens.

{% tabs %}
{% tab title="Python" %}
Function Name

```python
transfer_token
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  to (str): The address to transfer the token to (CronosIds with the `.cro` suffix are supported, e.g. `xyz.cro`)
  amount (int): The amount of the token to transfer.
  contract_address (str): Optional. The contract address of the token to transfer.
  ```
* Example Code

  ```python
  from crypto_com_developer_platform_client import Token

  tx = Token.transfer_token('example-recipient', example-number)
  print(tx)
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  The transaction hash.
  ```
* Errors

  ```python
  ValueError: If the Token class is not initialized with a Client instance.
  ```
* Example Return

  ```python
  {'status': 'Success', 'data': {'magicLink': 'example-magic-link'}}
  ```

{% endtab %}
{% endtabs %}
{% endtab %}

{% tab title="TypeScript" %}
Function Name

```typescript
transfer
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```typescript
  {object} payload: Transfer parameters.
  {string} payload.to: Recipient address.
  {number} payload.amount: Amount to transfer.
  {string} [payload.contractAddress]: ERC20 contract address (optional)
  ```
* Example Code

  ```typescript
  import { Token } from '@crypto.com/developer-platform-client';

  try {
    const result = await Token.transfer({ to: 'example-recipient', amount: example-number, contractAddress: 'example-contract-address'});
    console.log(result);
  }
  catch(err) {
    console.log(err);
  }
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```typescript
  {Promise<ApiResponse<MagicLinkData>>}: A promise that resolves to the transaction result.
  ```
* Errors

  ```typescript
  {Error}: Throws an error if the request fails.
  ```
* Example Return

  ```typescript
  {
    status: 'Success',
    data: {
      magicLink: 'example-magic-link'
    }
  }
  ```

{% endtab %}
{% endtabs %}
{% endtab %}
{% endtabs %}

#### 2.4 Wrap Token

Wrap tokens.

{% tabs %}
{% tab title="Python" %}
Function Name

```python
wrap_token
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  amount (float): The amount of the token to wrap.
  ```
* Example Code

  ```python
  from crypto_com_developer_platform_client import Token

  tx = Token.wrap_token(example-amount)
  print(tx)
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  The transaction hash.
  ```
* Errors

  ```python
  ValueError: If the Token class is not initialized with a Client instance.
  ```
* Example Return

  ```python
  {'status': 'Success', 'data': {'magicLink': 'example-magic-link'}}
  ```

{% endtab %}
{% endtabs %}
{% endtab %}

{% tab title="TypeScript" %}
Function Name

```typescript
wrap
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```typescript
  {object} payload: Wrap parameters.
  {number} payload.amount: Amount to wrap.
  ```
* Example Code

  ```typescript
  import { Token } from '@crypto.com/developer-platform-client';

  try {
    const result = await Token.wrap({ amount: example-number});
    console.log(result);
  }
  catch(err) {
    console.log(err);
  }
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```typescript
  {Promise<ApiResponse<MagicLinkData>>}: A promise that resolves to the wrap transaction result.
  ```
* Errors

  ```typescript
  {Error}: Throws an error if the request fails.
  ```
* Example Return

  ```typescript
  {
    status: 'Success',
    data: {
      magicLink: 'example-magic-link'
    }
  }
  ```

{% endtab %}
{% endtabs %}
{% endtab %}
{% endtabs %}

#### 2.5 Swap Token

Swap tokens.

{% tabs %}
{% tab title="Python" %}
Function Name

```python
swap_token
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  from_contract_address (str): The token to swap from.
  to_contract_address (str): The token to swap to.
  amount (int): The amount of the token to swap.
  ```
* Example Code

  ```python
  from crypto_com_developer_platform_client import Token

  tx = Token.swap_token('example-from', 'example-to', 'example-amount')
  print(tx)
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  The transaction hash.
  ```
* Errors

  ```python
  ValueError: If the Token class is not initialized with a Client instance.
  ```
* Example Return

  ```python
  {'status': 'Success', 'data': {'magicLink': 'example-magic-link'}}
  ```

{% endtab %}
{% endtabs %}
{% endtab %}

{% tab title="TypeScript" %}
Function Name

```typescript
swap
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```typescript
  {object} payload: Swap parameters.
  {string} payload.fromContractAddress: Token being swapped.
  {string} payload.toContractAddress: Token to receive.
  {number} payload.amount: Amount to swap.
  ```
* Example Code

  ```typescript
  import { Token } from '@crypto.com/developer-platform-client';

  try {
    const result = await Token.swap({ fromContractAddress: 'example-from-contract', toContractAddress: 'example-to-contract', amount: example-number
  });
    console.log(result);
  }
  catch(err) {
    console.log(err);
  }
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```typescript
  {Promise<ApiResponse<MagicLinkData>>}: A promise that resolves to the swap transaction result.
  ```
* Errors

  ```typescript
  {Error}: Throws an error if the request fails.
  ```
* Example Return

  ```typescript
  {
    status: 'Success',
    data: {
      magicLink: 'example-magic-link'
    }
  }
  ```

{% endtab %}
{% endtabs %}
{% endtab %}
{% endtabs %}

#### 2.6 Get ERC721 Token Balance

Fetches the ERC721 token balance for a wallet and contract.

{% tabs %}
{% tab title="Python" %}
Function Name

```python
get_erc721_balance
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  wallet_address (str): The address to get the balance for.
  contract_address (str): The ERC721 contract address.
  ```
* Example Code

  ```python
  from crypto_com_developer_platform_client import Token

  balance = Token.get_erc721_balance('example-wallet','example-contract')
  print(balance)
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  The ERC721 token balance.
  ```
* Errors

  ```python
  ValueError: If the Token class is not initialized with a Client instance.
  ```
* Example Return

  ```python
  {'status': 'Success', 'data': {'balance': 'example-balance'}}
  ```

{% endtab %}
{% endtabs %}
{% endtab %}

{% tab title="TypeScript" %}
Function Name

```typescript
getERC721TokenBalance
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```typescript
  {string} walletAddress: Wallet address to check.
  {string} contractAddress: ERC721 contract address.
  ```
* Example Code

  ```typescript
  import { Token } from '@crypto.com/developer-platform-client';

  try {
    const balance = await Token.getERC721TokenBalance('example-wallet', 'example-contract');
    console.log(balance);
  }
  catch(err) {
    console.log(err);
  }
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```typescript
  {Promise<ApiResponse<Balance>>}: A promise that resolves to the ERC721 token balance.
  ```
* Errors

  ```typescript
  {Error}: Throws an error if the request fails.
  ```
* Example Return

  ```typescript
  { status: 'Success', data: { balance: 'example-balance' } }
  ```

{% endtab %}
{% endtabs %}
{% endtab %}
{% endtabs %}

#### 2.7 Get ERC721 Token Owner

Fetches the owner of a specific ERC721 token.

{% tabs %}
{% tab title="Python" %}
Function Name

```python
get_token_owner
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  contract_address (str): The ERC721 contract address.
  token_id (str): The token ID.
  ```
* Example Code

  ```python
  from crypto_com_developer_platform_client import Token

  owner = Token.get_token_owner('example-contract', 'example-token-id')
  print(owner)
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  The owner of the token.
  ```
* Errors

  ```python
  ValueError: If the Token class is not initialized with a Client instance.
  ```
* Example Return

  ```python
  {'status': 'Success', 'data': 'example-address'}
  ```

{% endtab %}
{% endtabs %}
{% endtab %}

{% tab title="TypeScript" %}
Function Name

```typescript
getTokenOwner
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```typescript
  {string} contractAddress: ERC721 contract address.
  {string} tokenId: Token ID.
  ```
* Example Code

  ```typescript
  import { Token } from '@crypto.com/developer-platform-client';

  try {
    const owner = await Token.getTokenOwner('example-contract', 'example-token-id');
    console.log(owner);
  }
  catch(err) {
    console.log(err);
  }
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```typescript
  {Promise<ApiResponse<string>>}: A promise that resolves to the token owner information.
  ```
* Errors

  ```typescript
  {Error}: Throws an error if the request fails.
  ```
* Example Return

  ```typescript
  {
    status: 'Success',
    data: 'example-owner'
  }
  ```

{% endtab %}
{% endtabs %}
{% endtab %}
{% endtabs %}

#### 2.8 Get Token URI

Fetches the token URI of a specific ERC721 token.

{% tabs %}
{% tab title="Python" %}
Function Name

```python
get_token_uri
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  contract_address (str): The ERC721 contract address.
  token_id (str): The token ID.
  ```
* Example Code

  ```python
  from crypto_com_developer_platform_client import Token

  uri = Token.get_token_uri('example-contract', 'example-token-id')
  print(uri)
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  The token URI.
  ```
* Errors

  ```python
  ValueError: If the Token class is not initialized with a Client instance.
  ```
* Example Return

  ```python
  {'status': 'Success', 'data': 'example-token-uri'}
  ```

{% endtab %}
{% endtabs %}
{% endtab %}

{% tab title="TypeScript" %}
Function Name

```typescript
getTokenURI
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```typescript
  {string} contractAddress: ERC721 contract address.
  {string} tokenId: Token ID.
  ```
* Example Code

  ```typescript
  import { Token } from '@crypto.com/developer-platform-client';

  try {
    const uri = await Token.getTokenURI('example-contract', 'example-token-id');
    console.log(uri);
  }
  catch(err) {
    console.log(err);
  }
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```typescript
  {Promise<ApiResponse<string>>}: A promise that resolves to the token URI information.
  ```
* Errors

  ```typescript
  {Error}: Throws an error if the request fails.
  ```
* Example Return

  ```typescript
  {
    status: 'Success',
    data: 'example-token-uri'
  }
  ```

{% endtab %}
{% endtabs %}
{% endtab %}
{% endtabs %}

#### 2.9 Get ERC721 Metadata

Fetches metadata for a specific ERC721 contract.

{% tabs %}
{% tab title="Python" %}
Function Name

```python
get_erc721_metadata
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  contract_address (str): The ERC721 contract address.
  ```
* Example Code

  ```python
  from crypto_com_developer_platform_client import Token

  metadata = Token.get_erc721_metadata('example-contract')
  print(metadata)
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  The contract metadata.
  ```
* Errors

  ```python
  ValueError: If the Token class is not initialized with a Client instance.
  ```
* Example Return

  ```python
  {'status': 'Success', 'data': {'name': 'example-name', 'symbol': 'example-symbol'}}
  ```

{% endtab %}
{% endtabs %}
{% endtab %}

{% tab title="TypeScript" %}
Function Name

```typescript
getERC721Metadata
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```typescript
  {string} contractAddress: ERC721 contract address.
  ```
* Example Code

  ```typescript
  import { Token } from '@crypto.com/developer-platform-client';

  try {
    const metadata = await Token.getERC721Metadata('example-contract');
    console.log(metadata);
  }
  catch(err) {
    console.log(err);
  }
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```typescript
  {Promise<ApiResponse<TokenMetadata>>} A promise that resolves to the ERC721 contract metadata.
  ```
* Errors

  ```typescript
  {Error}: Throws an error if the request fails.
  ```
* Example Return

  ```typescript
  { status: 'Success', data: { name: 'example-token-name', symbol: 'example-token-symbol' } }
  ```

{% endtab %}
{% endtabs %}
{% endtab %}
{% endtabs %}

#### 2.10 Get ERC20 Metadata

Fetches metadata for a specific ERC20 contract.

{% tabs %}
{% tab title="Python" %}
Function Name

```python
get_erc20_metadata
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  contract_address (str): The ERC20 contract address.
  ```
* Example Code

  ```python
  from crypto_com_developer_platform_client import Token

  metadata = Token.get_erc20_metadata('example-contract')
  print(metadata)
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  The contract metadata.
  ```
* Errors

  ```python
  ValueError: If the Token class is not initialized with a Client instance.
  ```
* Example Return

  ```python
  {'status': 'Success', 'data': {'name': 'example-name', 'symbol': 'example-symbol', 'decimals': 'example-token-decimals'}}
  ```

{% endtab %}
{% endtabs %}
{% endtab %}

{% tab title="TypeScript" %}
Function Name

```typescript
getERC20Metadata
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```typescript
  {string} contractAddress: ERC20 contract address.
  ```
* Example Code

  ```typescript
  import { Token } from '@crypto.com/developer-platform-client';

  try {
    const metadata = await Token.getERC20Metadata('example-contract');
    console.log(metadata);
  }
  catch(err) {
    console.log(err);
  }
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```typescript
  {Promise<ApiResponse<TokenMetadata>>} A promise that resolves to the ERC20 contract metadata.
  ```
* Errors

  ```typescript
  {Error}: Throws an error if the request fails.
  ```
* Example Return

  ```typescript
  {
    status: 'Success',
    data: { name: 'example-token-name', symbol: 'example-token-symbol', decimals: 'example-token-decimals' }
  }
  ```

{% endtab %}
{% endtabs %}
{% endtab %}
{% endtabs %}


# Transaction Module

Transaction module handles blockchain transaction operations and queries.

To learn more about how to use the AI Agent SDK to interact with the transaction module, please visit [AI Agent SDK Transaction Queries](/crypto.com-ai-agent-sdk/core-concepts-overview/blockchain-functions/transaction-queries).

#### 3.1 Get Transaction By Hash

Fetches a transaction by hash.

{% tabs %}
{% tab title="Python" %}
Function Name

```python
get_transaction_by_hash
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  hash (str): The hash of the transaction.
  ```
* Example Code

  ```python
  from crypto_com_developer_platform_client import Transaction

  tx = Transaction.get_transaction_by_hash('example-hash')
  print(tx)
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  The transaction details.
  ```
* Errors

  ```python
  ValueError: If the Transaction class is not initialized with a Client instance.
  ```
* Example Return

  ```python
  {'status': 'Success', 'data': {'transaction': {'_type': 'TransactionResponse', 'accessList': example-list, 'blockNumber': example-block-number, 'blockHash': 'example-hash', 'blobVersionedHashes': example-hashes, 'chainId': 'example-chain0id', 'data': 'example-data', 'from': 'example-from', 'gasLimit': 'example-gas-limit', 'gasPrice': 'example-gas-price', 'hash': 'example-hash', 'maxFeePerGas': 'example-fee', 'maxPriorityFeePerGas': 'example-fee', 'maxFeePerBlobGas': example-fee, 'nonce': example-nonce, 'signature': {'_type': 'signature', 'networkV': 'example-V', 'r': 'example-r', 's': 'example-s', 'v': example-v}, 'to': 'example-to', 'index': example-index, 'type': example-type, 'value': 'example-value'}}}
  ```

{% endtab %}
{% endtabs %}
{% endtab %}

{% tab title="TypeScript" %}
Function Name

```typescript
getTransactionByHash
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```typescript
  {string} txHash: Transaction hash.
  ```
* Example Code

  ```typescript
  import { Transaction } from '@crypto.com/developer-platform-client';

  const tx = await Transaction.getTransactionByHash('example-hash');
  console.log(tx);
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```typescript
  {Promise<ApiResponse<TransactionByHash>>}: A promise that resolves to the transaction result
  ```
* Example Return

  ```typescript
  {
    status: 'Success',
    data: {
      transaction: {
        _type: 'TransactionResponse',
        accessList: example-list,
        blockNumber: example-block-number,
        blockHash: 'example-hash',
        blobVersionedHashes: example-hashes,
        chainId: 'example-chain-id',
        data: 'example-data',
        from: 'example-from',
        gasLimit: 'example-gas-limit',
        gasPrice: 'example-gas-price',
        hash: 'example-hash',
        maxFeePerGas: 'example-fee',
        maxPriorityFeePerGas: 'example-fee',
        maxFeePerBlobGas: example-fee,
        nonce: example-nonce,
        signature: [example-singature],
        to: 'example-to',
        index: example-index,
        type: example-type,
        value: 'example-value'
      }
    }
  }
  ```

{% endtab %}
{% endtabs %}
{% endtab %}
{% endtabs %}

#### 3.2 Get Transaction Status

Fetches transaction status by hash.

{% tabs %}
{% tab title="Python" %}
Function Name

```python
get_transaction_status
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  hash (str): The hash of the transaction.
  ```
* Example Code

  ```python
  from crypto_com_developer_platform_client import Transaction

  status = Transaction.get_transaction_status('example-hash')
  print(status)
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  The transaction status.
  ```
* Errors

  ```python
  ValueError: If the Transaction class is not initialized with a Client instance.
  ```
* Example Return

  ```python
  {'status': 'Success', 'data': {'status': 1}}
  ```

{% endtab %}
{% endtabs %}
{% endtab %}

{% tab title="TypeScript" %}
Function Name

```typescript
getTransactionStatus
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```typescript
  {string} txHash: Transaction hash.
  ```
* Example Code

  ```typescript
  import { Transaction } from '@crypto.com/developer-platform-client';

  const status = await Transaction.getTransactionStatus('example-hash');
  console.log(status);
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```typescript
  Promise<ApiResponse<TransactionStatus>>}: A promise that resolves to the transaction status.
  ```
* Example Return

  ```typescript
  { status: 'Success', data: { status: 1 } }
  ```

{% endtab %}
{% endtabs %}
{% endtab %}
{% endtabs %}

#### 3.3 Get Transaction Count

Fetches transaction count for a wallet.

{% tabs %}
{% tab title="Python" %}
Function Name

```python
get_transaction_count
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  wallet_address (str): The address to get the transaction count for.
  ```
* Example Code

  ```python
  from crypto_com_developer_platform_client import Transaction

  count = Transaction.get_transaction_count('example-wallet')
  print(count)
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  The transaction count for the wallet address.
  ```
* Errors

  ```python
  ValueError: If the Transaction class is not initialized with a Client instance.
  ```
* Example Return

  ```python
  {'status': 'Success', 'data': {'count': example-count}}
  ```

{% endtab %}
{% endtabs %}
{% endtab %}

{% tab title="TypeScript" %}
Function Name

```typescript
getTransactionCount
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```typescript
  {string} walletAddress: Wallet address.
  ```
* Example Code

  ```typescript
  import { Transaction } from '@crypto.com/developer-platform-client';

  const count = await Transaction.getTransactionCount('example-address');
  console.log(count);
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```typescript
  {Promise<ApiResponse<TransactionCount>>}: A promise that resolves to the transaction count.
  ```
* Example Return

  ```typescript
  { status: 'Success', data: { count: example-number } }
  ```

{% endtab %}
{% endtabs %}
{% endtab %}
{% endtabs %}

#### 3.4 Get Gas Price

Fetches current gas price.

{% tabs %}
{% tab title="Python" %}
Function Name

```python
get_gas_price
```

{% tabs %}
{% tab title="Query" %}

* Example Code

  ```python
  from crypto_com_developer_platform_client import Transaction

  price = Transaction.get_gas_price()
  print(price)
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  The current gas price.
  ```
* Errors

  ```python
  ValueError: If the Transaction class is not initialized with a Client instance.
  ```
* Example Return

  ```python
  {'status': 'Success', 'data': {'gasPrice': 'example-gas-price'}}
  ```

{% endtab %}
{% endtabs %}
{% endtab %}

{% tab title="TypeScript" %}
Function Name

```typescript
getGasPrice
```

{% tabs %}
{% tab title="Query" %}

* Example Code

  ```typescript
  import { Transaction } from '@crypto.com/developer-platform-client';

  const gasPrice = await Transaction.getGasPrice();
  console.log(gasPrice);
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```typescript
  {Promise<ApiResponse<GasPrice>>}: A promise that resolves to the gas price.
  ```
* Example Return

  ```typescript
  { status: 'Success', data: { gasPrice: 'example-gas-price' } }
  ```

{% endtab %}
{% endtabs %}
{% endtab %}
{% endtabs %}

#### 3.5 Get Fee Data

Fetches current fee data.

{% tabs %}
{% tab title="Python" %}
Function Name

```python
get_fee_data
```

{% tabs %}
{% tab title="Query" %}

* Example Code

  ```python
  from crypto_com_developer_platform_client import Transaction

  data = Transaction.get_fee_data()
  print(data)
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  The current fee data.
  ```
* Errors

  ```python
  ValueError: If the Transaction class is not initialized with a Client instance.
  ```
* Example Return

  ```python
  {'status': 'Success', 'data': {'feeData': {'_type': 'FeeData', 'gasPrice': 'example-gas-price', 'maxFeePerGas': 'example-fee', 'maxPriorityFeePerGas': 'example-fee'}}}
  ```

{% endtab %}
{% endtabs %}
{% endtab %}

{% tab title="TypeScript" %}
Function Name

```typescript
getFeeData
```

{% tabs %}
{% tab title="Query" %}

* Example Code

  ```typescript
  import { Transaction } from '@crypto.com/developer-platform-client';

  const feeData = await Transaction.getFeeData();
  console.log(feeData);
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```typescript
  {Promise<ApiResponse<FeeData>>}: A promise that resolves to the fee data.
  ```
* Example Return

  ```typescript
  {
    status: 'Success',
    data: {
      feeData: {
        _type: 'FeeData',
        gasPrice: 'example-gas-price',
        maxFeePerGas: 'example-fee',
        maxPriorityFeePerGas: 'example-fee'
      }
    }
  }
  ```

{% endtab %}
{% endtabs %}
{% endtab %}
{% endtabs %}

#### 3.6 Estimate Gas

Estimates gas for a transaction.

{% tabs %}
{% tab title="Python" %}
Function Name

```python
estimate_gas
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  payload (dict): The payload for gas estimation, including fields like `from`, `to`, `value`, `gasLimit`, `gasPrice`, `data`.
  ```
* Example Code

  ```python
  from crypto_com_developer_platform_client import Transaction

  gas = Transaction.estimate_gas({'from': 'example-from', 'to': 'example-to', 'value': 'example-value', 'gasLimit': 'example-gas-limit', 'gasPrice': 'example-gas-price', 'data': 'example-data'})
  print(gas)
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  The estimated gas information.
  ```
* Errors

  ```python
  ValueError: If the Transaction class is not initialized with a Client instance.
  ```
* Example Return

  ```python
  {'status': 'Success', 'data': {'gasLimit': 'example-gas-limit'}}
  ```

{% endtab %}
{% endtabs %}
{% endtab %}

{% tab title="TypeScript" %}
Function Name

```typescript
estimateGas
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```typescript
  {object} payload: Transaction payload (from, to, value, gasLimit, gasPrice, data).
  ```
* Example Code

  ```typescript
  import { Transaction } from '@crypto.com/developer-platform-client';

  const estimation = await Transaction.estimateGas({from: 'example-from', to: 'example-to', value: 'example-value', gasLimit: 'example-gas-limit', gasPrice: 'example-gas-price', data: 'example-data'});
  console.log(estimation);
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```typescript
  {Promise<ApiResponse<EstimateGasData>>}: A promise that resolves to the estimate gas data.
  ```
* Example Return

  ```typescript
  { status: 'Success', data: { gasLimit: 'example-gas-limit' } }
  ```

{% endtab %}
{% endtabs %}
{% endtab %}
{% endtabs %}


# Block Module

Block module for accessing blockchain block data.

To learn more about how to use the AI Agent SDK to interact with the wallet module, please visit [AI Agent SDK Block Information](/crypto.com-ai-agent-sdk/core-concepts-overview/blockchain-functions/block-information).

#### 4.1 Get Current Block

Get the current latest block.

{% tabs %}
{% tab title="Python" %}
Function Name

```python
get_current
```

{% tabs %}
{% tab title="Query" %}

* Example Code

  ```python
  from crypto_com_developer_platform_client import Block

  block = Block.get_current()
  print(block)
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  The latest block data.
  ```
* Errors

  ```python
  ValueError: If the Block class is not initialized with a Client instance.
  ```
* Example Return

  ```python
  {'status': 'Success', 'data': {'blockNumber': example-block-number}}
  ```

{% endtab %}
{% endtabs %}
{% endtab %}

{% tab title="TypeScript" %}
Function Name

```typescript
getCurrentBlock
```

{% tabs %}
{% tab title="Query" %}

* Example Code

  ```typescript
  import { Block } from '@crypto.com/developer-platform-client';

  const block = await Block.getCurrentBlock();
  console.log(block);
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```typescript
  Promise<ApiResponse<BlockNumber>>: A promise that resolves to the current block data.
  ```
* Example Return

  ```typescript
  { status: 'Success', data: { blockNumber: example-number } }
  ```

{% endtab %}
{% endtabs %}
{% endtab %}
{% endtabs %}

#### 4.2 Get Block By Tag

Get a block by tag or block number.

{% tabs %}
{% tab title="Python" %}
Function Name

```python
get_by_tag
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  tag (str): Integer of a block number in hex, or the string "earliest", "latest" or "pending", as in https://ethereum.org/en/developers/docs/apis/json-rpc/#default-block
  tx_detail (str): If true it returns the full transaction objects, if false only the hashes of the transactions.
  ```
* Example Code

  ```python
  from crypto_com_developer_platform_client import Block

  block = Block.get_by_tag("latest", "true")
  print(block)
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  The block data.
  ```
* Errors

  ```python
  ValueError: If the Block class is not initialized with a Client instance.
  ```
* Example Return

  ```python
  {'status': 'Success', 'data': {'block': {'_type': 'Block', 'baseFeePerGas': 'example-fee', 'difficulty': 'example-difficulty', 'extraData': 'example-data', 'gasLimit': 'example-gas-limit', 'gasUsed': 'example-gas-used', 'blobGasUsed': 'example-blob-gas-used', 'excessBlobGas': 'example-gas', 'hash': 'example-hash', 'miner': 'example-address', 'prevRandao': 'example-randao', 'nonce': 'example-nonce', 'number': example-number, 'parentHash': 'example-hash', 'timestamp': example-timestamp, 'parentBeaconBlockRoot': 'example-hash', 'stateRoot': 'example-hash', 'receiptsRoot': 'example-hash', 'transactions': ['example-transactions']}}}
  ```

{% endtab %}
{% endtabs %}
{% endtab %}

{% tab title="TypeScript" %}
Function Name

```typescript
getBlockByTag
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```typescript
  (string} blockTag: Block identifier ('latest', 'pending', or block number in hex).
  {string} txDetail: Whether to include transaction details ('true' or 'false').
  ```
* Example Code

  ```typescript
  import { Block } from '@crypto.com/developer-platform-client';

  const block = await Block.getBlockByTag('latest', 'true');
  console.log(block);
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```typescript
  Promise<ApiResponse<BlockData>>: A promise that resolves to the block data.
  ```
* Example Return

  ```typescript
  {
    status: 'Success',
    data: {
      block: {
        _type: 'Block',
        baseFeePerGas: 'example-fee',
        difficulty: 'example-difficulty',
        extraData: 'example-data',
        gasLimit: 'example-gas-limit',
        gasUsed: 'example-gas-used',
        blobGasUsed: example-gas,
        excessBlobGas: example-gas,
        hash: 'example-hash',
        miner: 'example-hash',
        prevRandao: 'example-hash',
        nonce: 'example-nonce',
        number: example-number,
        parentHash: 'example-hash',
        timestamp: example-timestamp,
        parentBeaconBlockRoot: example-block-root,
        stateRoot: 'example-hash',
        receiptsRoot: 'example-hash',
        transactions: [example-transaction-array]
      }
    }
  }



  ```

{% endtab %}
{% endtabs %}
{% endtab %}
{% endtabs %}


# Contract Module

Contract module handles interactions related to smart contracts, such as fetching contract ABI and bytecode.

#### 5.1 Get Contract Code

Fetches the bytecode of a smart contract.

{% tabs %}
{% tab title="Python" %}
Function Name

```python
get_contract_code
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  contract_address (str): The address of the smart contract.
  ```
* Example Code

  ```python
  from crypto_com_developer_platform_client import Contract

  code = Contract.get_contract_code('example-contract')
  print(code)
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  The bytecode of the smart contract.
  ```
* Errors

  ```python
  ValueError: If the Contract class is not initialized with a Client instance.
  ```
* Example Return

  ```python
  {'status': 'Success', 'data': {'code': 'example-code'}}
  ```

{% endtab %}
{% endtabs %}
{% endtab %}

{% tab title="TypeScript" %}
Function Name

```typescript
getContractCode
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```typescript
  {string} {string} contractAddress: The smart contract address.
  ```
* Example Code

  ```typescript
  import { Contract } from '@crypto.com/developer-platform-client';

  try {
    const bytecode = await Contract.getContractCode('example-address');
    console.log(bytecode);
  }
    catch(err) {
    console.log(err);
  }
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```typescript
  {Promise<ApiResponse<ContractCode>>}: A promise that resolves to the bytecode of the contract.
  ```
* Errors

  ```typescript
  {Error} If the bytecode retrieval fails.
  ```
* Example Return

  ```typescript
  {
    status: 'Success',
    data: {
      code: 'example-byte-code'
    }
  }
  ```

{% endtab %}
{% endtabs %}
{% endtab %}
{% endtabs %}


# CronosID Module

CronosID module manages the conversion between CronosIDs and standard addresses.

{% hint style="info" %}
Note: CronosId is not supported on Cronos ZK EVM Mainnet.
{% endhint %}

To learn more about how to use the AI Agent SDK to interact with the wallet module, please visit [AI Agent SDK CronosId Operations](/crypto.com-ai-agent-sdk/core-concepts-overview/blockchain-functions/cronosid-operations).

#### 6.1 Is CronosId

Checks if a given string is a valid CronosId, which is a string ending with '.cro' and not empty. Example: 'alice.cro' is a valid CronosId, but 'alice' is not.

{% tabs %}
{% tab title="TypeScript" %}
Function Name

```typescript
isCronosId
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```typescript
  {string} name: The string to check for CronosId validity.
  ```
* Example Code

  ```typescript
  import { CronosId } from '@crypto.com/developer-platform-client';

  const result = CronosId.isCronosId('example-cronos-id');
  console.log(result);
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```typescript
  {boolean}: True if the string is a valid CronosId, false otherwise.
  ```
* Example Return

  ```typescript
  example-boolean
  ```

{% endtab %}
{% endtabs %}
{% endtab %}
{% endtabs %}

#### 6.2 Resolve CronosId

Resolves a CronosId to a wallet address.

{% tabs %}
{% tab title="Python" %}
Function Name

```python
resolve_name
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  name (str): The CronosId name to resolve (CronosIds with the `.cro` suffix are supported, e.g. `xyz.cro`)
  ```
* Example Code

  ```python
  from crypto_com_developer_platform_client import CronosId

  address = CronosId.resolve_name('example-cronos-id')
  print(address)
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  Response containing the resolved blockchain address.
  ```
* Errors

  ```python
  ValueError: If the CronosId class is not initialized with a Client instance.
  ```
* Example Return

  ```python
  {'status': 'Success', 'data': 'example-address'}
  ```

{% endtab %}
{% endtabs %}
{% endtab %}

{% tab title="TypeScript" %}
Function Name

```typescript
forwardResolve
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```typescript
  {string} cronosId: The CronosId to resolve.
  ```
* Example Code

  ```typescript
  import { CronosId } from '@crypto.com/developer-platform-client';

  try {
    const address = wait CronosId.forwardResolve('alice.cro');
    console.log(address);
  }
    catch(err) {
    console.log(err);
  }
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```typescript
  {Promise<string>}: A promise that resolves to the resolved address.
  ```
* Errors

  ```typescript
  {Error}: Throws an error if the CronosId is not valid or if the resolution fails.
  ```
* Example Return

  ```typescript
  {
    status: 'Success',
    data: 'example-address'
  }
  ```

{% endtab %}
{% endtabs %}
{% endtab %}
{% endtabs %}

#### 6.3 Reverse Resolve Address

Resolves a wallet address to a CronosId if it has one.

{% tabs %}
{% tab title="Python" %}
Function Name

```python
lookup_address
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  address (str): The blockchain address to lookup
  ```
* Example Code

  ```python
  from crypto_com_developer_platform_client import CronosId

  cronosId = CronosId.lookup_address('example-address')
  print(cronosId)
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  Response containing the CronosId name.
  ```
* Errors

  ```python
  ValueError: If the CronosId class is not initialized with a Client instance.
  ```
* Example Return

  ```python
  {'status': 'Success', 'data': 'example-cronos-id'}
  ```

{% endtab %}
{% endtabs %}
{% endtab %}

{% tab title="TypeScript" %}
Function Name

```typescript
reverseResolve
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```typescript
  {string} address: The wallet address to resolve.
  ```
* Example Code

  ```typescript
  import { CronosId } from '@crypto.com/developer-platform-client';

  try {
    const cronosId = await CronosId.reverseResolve('example-address');
    console.log(cronosId);
  }
    catch(err) {
    console.log(err);
  }
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```typescript
  {Promise<string>}: A promise that resolves to the resolved CronosId.
  ```
* Errors

  ```typescript
  {Error}: Throws an error if the address is not valid or if the resolution fails.
  ```
* Example Return

  ```typescript
  {
    status: 'Success',
    data: 'example-cronos-id'
  }
  ```

{% endtab %}
{% endtabs %}
{% endtab %}
{% endtabs %}


# Defi Module

Defi module handles operations related to DeFi protocols, including farms and whitelisted tokens.

To learn more about how to use the AI Agent SDK to interact with the wallet module, please visit [AI Agent SDK Defi Operations](/crypto.com-ai-agent-sdk/core-concepts-overview/blockchain-functions/defi-operations).

#### 7.1 Get Whitelisted Tokens

Fetches whitelisted tokens for a specific DeFi protocol.

{% tabs %}
{% tab title="Python" %}
Function Name

```python
get_whitelisted_tokens
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  protocol (DefiProtocol): The DeFi protocol (e.g., DefiProtocol.H2, DefiProtocol.VVS)
  ```
* Example Code

  ```python
  from crypto_com_developer_platform_client import Defi, DefiProtocol

  tokens = Defi.get_whitelisted_tokens(DefiProtocol.H2)
  print(tokens)
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  List of whitelisted tokens for the project.
  ```
* Example Return

  ```python
  {'status': 'Success', 'data': [{'id': example-id, 'name': 'example-name', 'symbol': 'example-symbol', 'address': 'example-address', 'decimal': example-decimal, 'link': 'example-link', 'isSwappable': example-boolean, 'logoImagePngUrl': 'example-url', 'logoImageSvgUrl': 'example-url', 'chain': 'example-chain-name', 'chainId': example-chain-id}, ... ]}
  ```

{% endtab %}
{% endtabs %}
{% endtab %}

{% tab title="TypeScript" %}
Function Name

```typescript
getWhitelistedTokens
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```typescript
  {DefiProtocol} protocol: The DeFi protocol to fetch tokens for.
  ```
* Example Code

  ```typescript
  import { Defi, DefiProtocol } from '@crypto.com/developer-platform-client';

  try {
    const tokens = await Defi.getWhitelistedTokens(DefiProtocol.H2);
    console.log(tokens);
  }
    catch(err) {
    console.log(err);
  }
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```typescript
  {Promise<ApiResponse<WhitelistedToken[]>>}: A promise that resolves to the whitelisted tokens.
  ```
* Errors

  ```typescript
  {Error}: Throws an error if the request fails.
  ```
* Example Return

  ```typescript
  {
    status: 'Success',
    data: [
      {
        id: example-id,
        name: example-name,
        symbol: 'example-symbol,
        address: example-address,
        decimal: example-decimal,
        link: example-link,
        isSwappable: example-boolean,
        logoImagePngUrl: example-url,
        logoImageSvgUrl: example-url,
        chain: example-chain-name,
        chainId: example-chain-id
      }
      ...
    ]
  }
  ```

{% endtab %}
{% endtabs %}
{% endtab %}
{% endtabs %}

#### 7.2 Get All Farms

Fetches all farms for a specific DeFi protocol.

{% tabs %}
{% tab title="Python" %}
Function Name

```python
get_all_farms
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  protocol (DefiProtocol): The DeFi protocol (e.g., DefiProtocol.H2, DefiProtocol.VVS)
  ```
* Example Code

  ```python
  from crypto_com_developer_platform_client import Defi, DefiProtocol

  farms = Defi.get_all_farms(DefiProtocol.VVS)
  print(farms)
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  List of all farms for the project.
  ```
* Example Return

  ```python
  {'status': 'Success', 'data': [{'id': exmaple-id, 'pid': exmaple-pid, 'lpSymbol': 'exmaple-lp-symbol', 'lpAddress': 'exmaple-lp-address', 'token': {'id': exmaple-id, 'symbol': 'exmaple-symbol', 'address': 'exmaple-address'}, 'quoteToken': {'id': exmaple-id, 'symbol': 'exmaple-symbol', 'address': 'exmaple-address'}, 'version': 'exmaple-version', 'suffix': 'exmaple-suffix', 'rewardStartAt': 'exmaple-start-time', 'rewardEndAt': 'exmaple-end-time', 'isFinished': exmaple-boolean, 'isMigrated': exmaple-boolean, 'isBoostEnable': exmaple-boolean, 'isBoostFarmExpired': exmaple-boolean, 'isAutoHarvestEnabled': exmaple-boolean, 'rewarders': [{'address': 'exmaple-address', 'token': {'id': exmaple-id, 'symbol': 'exmaple-symbol', 'address': 'exmaple-addrss'}, 'isFinished': exmaple-boolean}], 'chain': 'exmaple-chain-name', 'chainId': exmaple-chain-id, 'baseApr': exmaple-base-apr, 'baseApy': exmaple-base-apy, 'lpApr': exmaple-lp-apr, 'lpApy': exmaple-lp-apy}, ... ]}
  ```

{% endtab %}
{% endtabs %}
{% endtab %}

{% tab title="TypeScript" %}
Function Name

```typescript
getAllFarms
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```typescript
  {DefiProtocol} protocol: The DeFi protocol to fetch farms for.
  ```
* Example Code

  ```typescript
  import { Defi, DefiProtocol } from '@crypto.com/developer-platform-client';

  try {
    const farms = await Defi.getAllFarms(DefiProtocol.VVS);
    console.log(farms);
  }
    catch(err) {
    console.log(err);
  }
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```typescript
  {Promise<ApiResponse<Farm[]>>}: A promise that resolves to the farms.
  ```
* Errors

  ```typescript
  {Error}: Throws an error if the request fails.
  ```
* Example Return

  ```typescript
  {
    status: 'Success',
    data: [
      {
        id: example-id,
        pid: example-pid,
        lpSymbol: example-symbol,
        lpAddress: example-address,
        token: example-token,
        quoteToken: example-token,
        version: example-version,
        suffix: example-suffix,
        rewardStartAt: example-start-time,
        rewardEndAt: example-end-time,
        isFinished: example-boolean,
        isMigrated: example-boolean,
        isBoostEnable: example-boolean,
        isBoostFarmExpired: example-boolean,
        isAutoHarvestEnabled: example-boolean,
        rewarders: example-array,
        chain: example-chain-name,
        chainId: example-chain-id,
        baseApr: example-base-apr,
        baseApy: example-base-apy,
        lpApr: example-lp-apr,
        lpApy: example-lp-apy
      }
      ...
    ]
  }
  ```

{% endtab %}
{% endtabs %}
{% endtab %}
{% endtabs %}

#### 7.3 Get Farm By Symbol

Fetches a specific farm by its symbol for a DeFi protocol.

{% tabs %}
{% tab title="Python" %}
Function Name

```python
get_farm_by_symbol
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  protocol (DefiProtocol): The DeFi protocol (e.g., DefiProtocol.H2, DefiProtocol.VVS)
  symbol (str): The farm symbol (e.g., 'zkCRO-MOON', 'CRO-GOLD')
  ```
* Example Code

  ```python
  from crypto_com_developer_platform_client import Defi, DefiProtocol

  farm = Defi.get_farm_by_symbol(DefiProtocol.H2, 'zkCRO-MOON')
  print(farm)
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  Information about the specific farm
  ```
* Example Return

  ```python
  {'status': 'Success', 'data': {'id': example-id, 'pid': example-pid, 'lpSymbol': 'example-lp-symbol', 'lpAddress': 'example-lp-address', 'token': {'id': example-id, 'symbol': 'example-symbol', 'address': 'example-address'}, 'quoteToken': {'id': example-id, 'symbol': 'example-symbol', 'address': 'example-address'}, 'version': 'example-version', 'suffix': 'example-suffix', 'rewardStartAt': 'example-start-time', 'rewardEndAt': 'example-end-time', 'isFinished': example-boolean, 'isMigrated': example-boolean, 'isBoostEnable': example-boolean, 'isBoostFarmExpired': example-boolean, 'isAutoHarvestEnabled': example-boolean, 'rewarders': [{'address': 'example-address', 'token': {'id': example-id, 'symbol': 'example-symbol', 'address': 'example-address'}, 'isFinished': example-boolean}], 'chain': 'example-chain-name', 'chainId': example-chain-id, 'baseApr': example-baser-apr, 'baseApy': example-base-apy, 'lpApr': example-lp-apr, 'lpApy': example-lp-apy, 'rewarderAprs': [{'address': 'example-address', 'tokenAddress': 'example-addrss', 'tokenSymbol': 'example-symbol', 'apr': example-apr, 'apy': example-apy}]}}
  ```

{% endtab %}
{% endtabs %}
{% endtab %}

{% tab title="TypeScript" %}
Function Name

```typescript
getFarmBySymbol
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```typescript
  {DefiProtocol} protocol: The DeFi protocol to fetch the farm from.
  {string} symbol: The symbol of the farm to fetch.
  ```
* Example Code

  ```typescript
  import { Defi, DefiProtocol } from '@crypto.com/developer-platform-client';

  try {
    const farm = await Defi.getFarmBySymbol(DefiProtocol.H2, 'zkCRO-MOON');
    console.log(farm);
  }
    catch(err) {
    console.log(err);
  }
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```typescript
  {Promise<ApiResponse<Farm>>} - A promise that resolves to the farm details.
  ```
* Errors

  ```typescript
  {Error}: Throws an error if the request fails.
  ```
* Example Return

  ```typescript
  {
    status: 'Success',
    data: {
      id: example-id,
      pid: example-pid,
      lpSymbol: example-lp-symbol,
      lpAddress: example-lp-address,
      token: {
        id: example-id,
        symbol: example-symbol,
        address: example-address
      },
      quoteToken: {
        id: example-id,
        symbol: example-symbol,
        address: example-address
      },
      version: example-version,
      suffix: example-suffix,
      rewardStartAt: example-start-time,
      rewardEndAt: example-end-time,
      isFinished: example-boolean,
      isMigrated: example-boolean,
      isBoostEnable: example-boolean,
      isBoostFarmExpired: example-boolean,
      isAutoHarvestEnabled: example-boolean,
      rewarders: example-array,
      chain: example-chain-name,
      chainId: example-chain-id,
      baseApr: example-base-apr,
      baseApy: example-base-apy,
      lpApr: example-lp-apr,
      lpApy: example-lp-apy,
      rewarderAprs: example-array
    }
  }
  ```

{% endtab %}
{% endtabs %}
{% endtab %}
{% endtabs %}


# Exchange Module

Exchange module handles operations related to exchange data retrieval.

To learn more about how to use the AI Agent SDK to interact with the wallet module, please visit [AI Agent SDK Crypto.com Exchange](/crypto.com-ai-agent-sdk/core-concepts-overview/blockchain-functions/crypto.com-exchange).

#### 8.1 Get All Tickers

Retrieves all available tickers from the Crypto.com Exchange (Chain agnostic).

{% tabs %}
{% tab title="Python" %}
Function Name

```python
get_all_tickers
```

{% tabs %}
{% tab title="Query" %}

* Example Code

  ```python
  from crypto_com_developer_platform_client import Exchange

  tickers = Exchange.get_all_tickers()
  print(tickers)
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  A list of all available tickers and their information.
  ```
* Errors

  ```python
  ValueError: If the Exchange class is not initialized with a Client instance.
  ```
* Example Return

  ```python
  {'status': 'Success', 'data': [{'instrumentName': 'example-intrument-name', 'high': example-high, 'low': example-low, 'lastPrice': example-last-price, 'volume': example-volume, 'volumeValue': example-volume-value, 'priceChange': example-price-change, 'bestBid': example-best-bid, 'bestAsk': example-best-ask, 'openInterest': example-open-interest, 'timestamp': example-timestamp}, ...]}
  ```

{% endtab %}
{% endtabs %}
{% endtab %}

{% tab title="TypeScript" %}
Function Name

```typescript
getAllTickers
```

{% tabs %}
{% tab title="Query" %}

* Example Code

  ```typescript
  import { Exchange } from '@crypto.com/developer-platform-client';

  try {
    const tickers = await Exchange.getAllTickers();
    console.log(tickers);
  }
    catch(err) {
    console.log(err);
  }
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```typescript
  {Promise<ApiResponse<TickerResponse>>}: A promise that resolves to all available tickers.
  ```
* Errors

  ```typescript
  {Error}: Throws an error if the request fails.
  ```
* Example Return

  ```typescript
  {
    status: 'Success',
    data: [
      {
        instrumentName: example-name,
        high: example-high,
        low: example-low,
        lastPrice: example-last-price,
        volume: example-volume,
        volumeValue: example-volume-value,
        priceChange: example-price-change,
        bestBid: example-best-bit,
        bestAsk: example-best-ask,
        openInterest: example-open-interest,
        timestamp: example-timestamp
      }
      ...
    ]
  }
  ```

{% endtab %}
{% endtabs %}
{% endtab %}
{% endtabs %}

#### 8.2 Get Ticker By Instrument

Retrieves ticker information for a specific trading instrument from the Crypto.com Exchange (Chain agnostic).

{% tabs %}
{% tab title="Python" %}
Function Name

```python
get_ticker_by_instrument
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  instrument_name (str): The name of the instrument to get ticker information for.
  ```
* Example Code

  ```python
  from crypto_com_developer_platform_client import Exchange

  ticker = Exchange.get_ticker_by_instrument('example-instrument')
  print(ticker)
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  Ticker information for the specified instrument.
  ```
* Errors

  ```python
  ValueError: If instrument_name is None or empty.
  ```
* Example Return

  ```python
  {'status': 'Success', 'data': {'instrumentName': 'example-intrument-name', 'high': example-high, 'low': example-low, 'lastPrice': example-last-price, 'volume': example-volume, 'volumeValue': example-volume-value, 'priceChange': example-price-change, 'bestBid': example-best-bid, 'bestAsk': example-best-ask, 'openInterest': example-open-interest, 'timestamp': example-timestamp}}
  ```

{% endtab %}
{% endtabs %}
{% endtab %}

{% tab title="TypeScript" %}
Function Name

```typescript
getTickerByInstrument
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```typescript
  {string} instrumentName: The name of the trading instrument (e.g., 'BTC_USDT')
  ```
* Example Code

  ```typescript
  import { Exchange } from '@crypto.com/developer-platform-client';

  try {
    const btcTicker = await Exchange.getTickerByInstrument('BTC_USDT');
    console.log(btcTicker);
  }
    catch(err) {
    console.log(err);
  }
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```typescript
  {Promise<ApiResponse<TickerData>>}: A promise that resolves to the ticker information.
  ```
* Errors

  ```typescript
  {Error}: Throws an error if the request fails.
  ```
* Example Return

  ```typescript
  {
    status: 'Success',
    data: {
      instrumentName: example-name,
      high: example-high,
      low: example-low,
      lastPrice: example-last-price,
      volume: example-volume,
      volumeValue: example-volume-value,
      priceChange: example-price-change,
      bestBid: example-best-bid,
      bestAsk: example-best-ask,
      openInterest: example-open-interest,
      timestamp: example-timestamp
    }
  }
  ```

{% endtab %}
{% endtabs %}
{% endtab %}
{% endtabs %}


# Event Module

Event module fetches event logs.

### 9.1 Get Logs

Get the emitted events of a smart contract.

{% tabs %}
{% tab title="Python" %}
Function Name

```python
get_logs
```

{% tabs %}
{% tab title="Query" %}

* Arguments

  ```python
  address (str): The address of the smart contract.
  ```
* Example Code

  ```python
  from crypto_com_developer_platform_client import Event

  logs = Event.get_logs('0x596A29345b8CAA702544B9167590c648efedB7B0')
  print(logs)
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  A list of decoded contract events.
  ```
* Errors

  ```python
  ValueError: If the Event class is not initialized with a Client instance.
  ```
* Example Return

  ```python
  {'status': 'Success', 'data': {'logs': [{'_type': 'log', 'address': 'example-address', 'blockHash': 'example-hash', 'blockNumber': example-block-number, 'data': 'example-data', 'index': example-index, 'removed': example-boolean, 'topics': ['example-hash', 'example-hash'], 'transactionHash': 'example-hash', 'transactionIndex': example-index}, ...]}}
  ```

{% endtab %}
{% endtabs %}
{% endtab %}
{% endtabs %}


# Network Module

Network module handles blockchain network metadata accessing.

#### 10.1 Info

Get general network info.

{% tabs %}
{% tab title="Python" %}
Function Name

```python
info
```

{% tabs %}
{% tab title="Query" %}

* Example Code

  ```python
  from crypto_com_developer_platform_client import Network

  data = Network.info()
  print(data)
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  Network metadata.
  ```
* Errors

  ```python
  ValueError: If the Network class is not initialized with a Client instance.
  ```
* Example Return

  ```python
  {'status': 'Success', 'data': {'name': 'example-name', 'chainId': 'example-chain-id'}}
  ```

{% endtab %}
{% endtabs %}
{% endtab %}
{% endtabs %}

#### 10.2 Chain ID

Get the current chain ID.

{% tabs %}
{% tab title="Python" %}
Function Name

```python
chain_id
```

{% tabs %}
{% tab title="Query" %}

* Example Code

  ```python
  from crypto_com_developer_platform_client import Network

  chainId = Network.chain_id()
  print(chainId)
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  Chain ID value.
  ```
* Errors

  ```python
  ValueError: If the Network class is not initialized with a Client instance.
  ```
* Example Return

  ```python
  {'status': 'Success', 'data': {'chainId': 'example-chain-id'}}
  ```

{% endtab %}
{% endtabs %}
{% endtab %}
{% endtabs %}

10.3 Client Version

Get the connected node's client version.

{% tabs %}
{% tab title="Python" %}
Function Name

```python
client_version
```

{% tabs %}
{% tab title="Query" %}

* Example Code

  ```python
  from crypto_com_developer_platform_client import Network

  version = Network.client_version()
  print(version)
  ```

{% endtab %}

{% tab title="Response" %}

* Returns

  ```python
  Client version string.
  ```
* Errors

  ```python
  ValueError: If the Network class is not initialized with a Client instance.
  ```
* Example Return

  ```python
  {'status': 'Success', 'data': {'version': 'example-version'}}
  ```

{% endtab %}
{% endtabs %}
{% endtab %}
{% endtabs %}


# Developer Platform Client SDK Examples

This page provides examples and demonstrations of how the AI Agent SDK interacts with the blockchain to perform on-chain actions:

1. The Cronos BigQuery Integration example uses Google BigQuery to fetch and count the number of unique active wallets (UAW) that have interacted with one or more smart contracts on a blockchain over configurable time windows (daily, weekly, monthly, yearly).

{% content-ref url="/pages/Ppz2DkvxJdIN4QDQGEe3" %}
[Cronos BigQuery Integration](/crypto.com-developer-platform/developer-platform-client-sdk-examples/cronos-bigquery-integration)
{% endcontent-ref %}

2. The Wallet Playground example demonstrates the front-end interface for Crypto.com Wallet Playground, built using React, Vite, and TypeScript. It provides a simple UI to create wallets using the official Crypto.com Developer Platform SDK.

{% content-ref url="/pages/JJHAjaUqVwURefGDdbqV" %}
[Wallet Playground](/crypto.com-developer-platform/developer-platform-client-sdk-examples/wallet-playground)
{% endcontent-ref %}

3. The Transaction Example demonstrates how to use the `@crypto.com/developer-platform-client` Transaction module to interact with blockchain transactions.

{% content-ref url="/pages/2Yh4bXo1AZZXc0iZnSo0" %}
[Transaction Example](/crypto.com-developer-platform/developer-platform-client-sdk-examples/transaction-example)
{% endcontent-ref %}

4. The Token Example demonstrates how to use the `@crypto.com/developer-platform-client` Token module to interact with blockchain tokens.

{% content-ref url="/pages/pMoMI7eCUtFkg9z2VVb1" %}
[Token Example](/crypto.com-developer-platform/developer-platform-client-sdk-examples/token-example)
{% endcontent-ref %}

\
Stay tuned for more examples on our [Crypto.com AI Agent SDK Updates](https://x.com/cryptocom_agent).&#x20;


# Cronos BigQuery Integration

This service uses **Google BigQuery** to fetch and count the number of **unique active wallets (UAW)** that have interacted with one or more smart contracts on a blockchain over configurable time windows (daily, weekly, monthly, yearly).

### Features

* Supports multiple smart contract addresses
* Queries 1-day, 7-day, 30-day, and 365-day windows
* Built on Node.js + TypeScript
* Uses the official `@google-cloud/bigquery` SDK
* Fully typed and documented with JSDoc

### Project Structure

```markdown
.
├── src/
│   ├── bigquery.api.ts        # BigQueryService class
│   ├── bigquery.constants.ts  # Field constants (column names)
│   ├── bigquery.helpers.ts    # SQL query builder
│   ├── bigquery.interface.ts  # Types and enums
│   └── index.ts               # Main CLI entry point
├── .env                       # Environment variables
├── README.md
├── tsconfig.json
└── package.json
```

### Getting Started

#### 1. Clone the repository

```bash
git clone https://github.com/crypto-com/developer-platform-sdk-examples.git
cd developer-platform-sdk-examples/integrations/bigquery
```

#### 2. Install dependencies

```bash
npm install
```

#### 3. Create a `.env` file

```bash
GCP_PROJECT_ID=your-gcp-project-id
BIGQUERY_DATASET=your_dataset
BIGQUERY_TABLE=your_table
GOOGLE_APPLICATION_CREDENTIALS=./gcpkey.json
```

{% hint style="info" %}
Ensure that your BigQuery dataset and table contain transaction data with `from_address`, `to_address`, and `block_timestamp`.
{% endhint %}

#### 4. Authentication

To run this example, you need access to BigQuery via a Google Cloud service account.

1. Create a service account with `BigQuery Data Viewer` and `BigQuery Job User` roles.
2. Download the JSON key and set the `GOOGLE_APPLICATION_CREDENTIALS` environment variable in `.env`.

#### 5. Run the script

```bash
npm run dev
```

You should see output like:

```bash
{
  "status": "success",
  "data": { "daily": 0, "weekly": 5, "monthly": 13, "yearly": 616 }
}
```

### How It Works

The core logic is in `BigQueryService`, which:

* Builds a SQL query that selects `DISTINCT from_address` where `to_address` matches one of the provided smart contract addresses.
* Filters records by `block_timestamp` within the time window (1, 7, 30, 365 days).
* Returns the number of distinct wallet addresses for each time window.

### Scripts

| Script          | Description                   |
| --------------- | ----------------------------- |
| `npm run start` | Runs the main `index.ts` file |
| `npm run dev`   | Runs in dev mode              |

### Requirements

* Node.js `>=18.x`
* TypeScript `^5.x`

### License

MIT — Crypto.com Developer Platform Team


# Wallet Playground

This example is the front-end interface for the Crypto.com Wallet Playground, built using React, Vite, and TypeScript. It provides a simple UI to create wallets using the official Crypto.com Developer Platform SDK.

### Features

* Simple wallet creation using the Crypto.com Developer SDK
* Displays:
  * Wallet address
  * Private key
  * Mnemonic phrase
* Clean, dark-themed UI with styled components

<div data-full-width="false"><figure><img src="/files/88oPzv9zk9Jz4O9CA2QQ" alt=""><figcaption></figcaption></figure></div>

### Installation

Navigate to the app folder and install dependencies:

```sh
cd developer-platform-sdk-examples/sdk-examples/categories/wallet
npm install
```

### Environment Variables

This example uses a client-side SDK and may require an API key. You can initialize the SDK inside your app (`src/app/Wallet/index.tsx`) code like so:

```typescript
import { Client } from '@crypto.com/developer-platform-client';

Client.init({
  apiKey: 'your-crypto.com-developer-platform-api-key',
});
```

{% hint style="info" %}
For Crypto.com Developer Platform API Key, [click here to learn how to obtain your Crypto.com Developer Platform API key](/crypto.com-developer-platform/developer-platform-dashboard).
{% endhint %}

{% hint style="info" %}
**Note:** Never expose real or production API keys in a public or client-side app.
{% endhint %}

### Usage

To run the app in development mode:

```sh
npm run dev
```

Open your browser at `http://localhost:5173`.

### Build

To generate a production-ready build:

```sh
npm run build
```

To preview the build:

```sh
npm run preview
```

### Demo Video

{% embed url="<https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FktUMyU5bBece2vVjrTg7%2Fuploads%2FAmHjrKmmYJ8L4begeTLe%2FWalletDemo.mp4?alt=media&token=5efe87b7-83e7-4a1e-a5f5-ae66b747644c>" %}


# Transaction Example

This example demonstrates how to use the `@crypto.com/developer-platform-client`  **Transaction** **module** to interact with blockchain transactions.

<figure><img src="/files/uWNKG9J8VD1h0MO4zHMQ" alt=""><figcaption></figcaption></figure>

### Installation

#### 1. Clone the repository

```sh
git clone https://github.com/crypto-com/developer-platform-sdk-examples.git
```

#### 2. Install dependencies

```sh
cd developer-platform-sdk-examples/sdk-examples/categories/transaction
npm install
```

### Environment Variables

This example uses a client-side SDK and may require an API key. You can initialize the SDK inside your app (`src/app/Transaction/index.tsx`) code like so:

```typescript
import { Client } from "@crypto.com/developer-platform-client";

Client.init({
  apiKey: "your-crypto.com-developer-platform-api-key",
});
```

{% hint style="info" %}
For Crypto.com Developer Platform API Key, [click here to learn how to obtain your Crypto.com Developer Platform API key](/crypto.com-developer-platform/developer-platform-dashboard).
{% endhint %}

{% hint style="info" %}
**Note:** Never expose real or production API keys in a public or client-side app.
{% endhint %}

### Features

This example showcases the following **Transaction** **module** functions:

* **getTransactionByHash**: Fetch a transaction by its hash
* **getTransactionStatus**: Check transaction status by hash

*Other functions provided by the `@crypto.com/developer-platform-client`*  ***Transaction module** can also be integrated into the app:*

* **getTransactionsByAddress**: Fetch transactions for a specific wallet address
* **getTransactionCount**: Get transaction count for a wallet
* **getGasPrice**: Fetch current gas price
* **getFeeData**: Get current fee data
* **estimateGas**: Estimate gas for a transaction

### Usage

To run the app in development mode:

```sh
npm run dev
```

Open your browser and navigate to the provided local URL (typically `http://localhost:5173`).

The application provides a user interface to test Transaction module functions. You can:

* Enter transaction hashes to fetch detailed transaction information
* Check the current status of any transaction
* View formatted JSON responses with transaction data

### Build

To generate a production-ready build:

```sh
npm run build
```

To preview the build:

```sh
npm run preview
```

### Development

* `npm run dev` - Start development server
* `npm run build` - Build for production
* `npm run lint` - Run ESLint
* `npm run preview` - Preview production build

### API Key Requirements

Some functions may require valid API credentials. Make sure to provide valid credentials when testing blockchain transaction features.

### Demo Video

{% embed url="<https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FktUMyU5bBece2vVjrTg7%2Fuploads%2FArD2YqJgRURcl88qY2dv%2FTransactionExampleDemo.mp4?alt=media&token=89cc0f84-930e-49c9-a301-ae814a592b94>" %}


# Token Example

This example demonstrates how to use the `@crypto.com/developer-platform-client`  **Token** **module** to interact with blockchain tokens.

<figure><img src="/files/wJ0AboGojSpe21NMzaAS" alt=""><figcaption></figcaption></figure>

### Installation

#### 1. Clone the repository

```sh
git clone https://github.com/crypto-com/developer-platform-sdk-examples.git
```

#### 2. Install dependencies

```sh
cd developer-platform-sdk-examples/sdk-examples/categories/token
npm install
```

### Environment Variables

This example uses a client-side SDK and may require an API key. You can initialize the SDK inside your app (`src/app/Token/index.tsx`) code like so:

```typescript
import { Client } from "@crypto.com/developer-platform-client";

Client.init({
  apiKey: "your-crypto.com-developer-platform-api-key",
});
```

{% hint style="info" %}
For Crypto.com Developer Platform API Key, [click here to learn how to obtain your Crypto.com Developer Platform API key](/crypto.com-developer-platform/developer-platform-dashboard).
{% endhint %}

{% hint style="info" %}
**Note:** Never expose real or production API keys in a public or client-side app.
{% endhint %}

### Features

This example showcases the following **Token module** functions:

* **getNativeTokenBalance**: Retrieve the native token balance for a given wallet address (supports `.cro` addresses)
* **getERC20TokenBalance**: Retrieve the ERC20 token balance for a wallet and contract address
* **getERC721TokenBalance**: Retrieve the ERC721 token balance for a wallet and contract address
* **getTokenOwner**: Get the owner of a specific ERC721 token ID
* **getTokenUri**: Get the token URI for a specific ERC721 token ID
* **getERC20Metadata**: Fetch metadata (name, symbol, decimals) for an ERC20 token
* **getERC721Metadata**: Fetch metadata for an ERC721 token contract

*Other functions provided by the `@crypto.com/developer-platform-client`*  ***Token*** ***module** can also be integrated into the app:*

* **transferToken**: Initiate a native or ERC20 token transfer transaction
* **wrapToken**: Wrap native tokens into wrapped tokens
* **swapToken**: Swap tokens between ERC20 contracts

### Usage

To run the app in development mode:

```sh
npm run dev
```

Open your browser and navigate to the provided local URL (typically `http://localhost:5173`).

The application provides a user interface to test Token module functions. You can:

* Enter a wallet address to fetch native, ERC20, or ERC721 token balances
* View token metadata (name, symbol, decimals) for ERC20 and ERC721 contracts
* Fetch ERC721 token owner and token URI information
* View formatted JSON responses with token data

### Build

To generate a production-ready build:

```sh
npm run build
```

To preview the build:

```sh
npm run preview
```

### Development

* `npm run dev` - Start development server
* `npm run build` - Build for production
* `npm run lint` - Run ESLint
* `npm run preview` - Preview production build

### API Key Requirements

Some functions may require valid API credentials. Make sure to provide valid credentials when testing blockchain transaction features.

### Demo Video

{% embed url="<https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FktUMyU5bBece2vVjrTg7%2Fuploads%2F5oa20vWVAU2YFHl9y9IO%2FTokenExampleDemo.mp4?alt=media&token=34b8f4af-2d1d-4e6e-b56f-0775bca4a41a>" %}


# Resources for Developers

## Developer Support Channel&#x20;

Developers are welcome to join the [Telegram channel](<https://t.me/cryptocom_agent >) for technical support.

## Cronos Networks and resources

### Explorer API keys

Explorer API keys for Cronos Chains are required to query block chain data, kindly follow the following instruction to obtain the API key for:&#x20;

{% tabs %}
{% tab title="Cronos zkEVM" %}
To get started with the Cronos zkEVM developer API, simply register an account on the [Account Registration page](https://developers.zkevm.cronos.org/register) in Cronos zkEVM developer portal, where you can access a pair of mainnet and testnet API keys on the user dashboard. You can then access the developer API service and use it to retrieve data from the available endpoints.
{% endtab %}

{% tab title="Cronos EVM" %}
Kindly follow the [instructions](https://docs.cronos.org/block-explorers/block-explorer-and-api-keys) to obtain the API key for Cronos EVM
{% endtab %}
{% endtabs %}

### Documentation

For detailed documentation of Cronos Chain, kindly visit:

* Cronos zkEVM - <https://docs-zkevm.cronos.com/>
* Cronos EVM - <https://docs.cronos.com/>

### Cronos zkEVM Mainnet URLs <a href="#cronos-zkevm-mainnet-urls" id="cronos-zkevm-mainnet-urls"></a>

* Chain ID: `388`
* Token: zkCRO ("Cronos zkEVM CRO")
* JSON RPC API (rate limited): [https://mainnet.zkevm.cronos.org](https://mainnet.zkevm.cronos.org/)
* WebSocket (rate limited): `wss://ws.zkevm.cronos.org`
* Blockchain explorer: <https://explorer.zkevm.cronos.org/>
* Gas price: ⚠️ The gas price is currently fixed at 1250 `gwei`
  * This is subject to change and is expected to be dynamic in the next major release to be announced.
* Developer portal: <https://developers.zkevm.cronos.org/>
* Contract verification interface: <https://explorer.zkevm.cronos.org/verifyContract>
* Bridge for ERC-20 tokens (Ethereum <=> Cronos zkEVM): <https://zkevm.cronos.org/bridge>

***

### Cronos zkEVM Sepolia Testnet URLs <a href="#cronos-zkevm-sepolia-testnet-urls" id="cronos-zkevm-sepolia-testnet-urls"></a>

* Chain ID: `240`
* Token: zkTCRO
* JSON RPC API (rate limited): [https://testnet.zkevm.cronos.org](https://testnet.zkevm.cronos.org/)
* WebSocket (rate limited): `wss://ws.testnet.zkevm.cronos.org`
* Blockchain explorer: <https://explorer.zkevm.cronos.org/testnet>
* Gas price: ⚠️ The gas price of is currently fixed at 1250`gwei`
  * This is subject to change and is expected to be dynamic in the next major release to be announced.
* Developer portal: <https://developers.zkevm.cronos.org/>
* Contract verification interface: <https://explorer.zkevm.cronos.org/testnet/verifyContract>
* zkTCRO faucet: <https://zkevm.cronos.org/faucet>
* [Demo project repository](https://github.com/kentimsit/cronos-zkevm-hardhat-boilerplate) for smart contract developers
* Testnet bridge for ERC-20 tokens (zkEVM testnet <=> Ethereum Sepolia): <https://zkevm.cronos.org/bridge/testnet>

***

### Cronos EVM Mainnet URLs <a href="#cronos-zkevm-sepolia-testnet-urls" id="cronos-zkevm-sepolia-testnet-urls"></a>

* Chain ID: `25`
* JSON RPC AP&#x49;**:** [https://evm.cronos.com](https://evm.cronos.com/)
* Block explore&#x72;**:** <https://explorer.cronos.com/>

***

### Cronos EVM Testnet URLs <a href="#cronos-zkevm-sepolia-testnet-urls" id="cronos-zkevm-sepolia-testnet-urls"></a>

* Chain ID: `338`
* JSON RPC API: <https://evm-t3.cronos.com/>
* Block explore&#x72;**:** <https://explorer.cronos.com/testnet>

***


