# Welcome to AgentiPy

## AgentiPy: Your AI Agent Toolkit for Blockchain Applications

AgentiPy is a Python toolkit designed to empower AI agents to interact seamlessly with blockchain applications, focusing on Solana and Base. It simplifies the development of decentralized applications (dApps) by providing tools for token management, NFT handling, and more. With a focus on ease of use and powerful functionality, AgentiPy allows developers to create robust and sophisticated blockchain-based solutions, leveraging AI-driven workflows.

[![GitHub Stars](https://img.shields.io/github/stars/niceberginc/agentipy?style=social)](https://github.com/niceberginc/agentipy)[![GitHub Forks](https://img.shields.io/github/forks/niceberginc/agentipy?style=social)](https://github.com/niceberginc/agentipy)[![Total Downloads](https://static.pepy.tech/personalized-badge/agentipy?period=total\&units=international_system\&left_color=grey\&right_color=blue\&left_text=Downloads)](https://pypi.org/project/agentipy/)[![PyPI Version](https://img.shields.io/pypi/v/agentipy.svg)](https://pypi.org/project/agentipy/)[![Open Issues](https://img.shields.io/github/issues/niceberginc/agentipy)](https://github.com/niceberginc/agentipy/issues)[![Python Version](https://img.shields.io/badge/python-3.8%2B-blue)](https://pypi.org/project/agentipy/)[![License](https://img.shields.io/badge/License-MIT-blue.svg)](https://github.com/niceberginc/agentipy/blob/main/LICENSE)

Welcome to the official documentation for AgentiPy!

Use the navigation on the left to explore the toolkit's features, installation process, supported protocols, guides, API reference, and more.

**Ready to dive in?**

* Learn about the project in the Introduction.
* Get started by following the Installation and Setup guide.
* Explore the Supported Protocols and Tools.
* Find practical examples in the Examples section.


# Get Started

This section guides you through understanding what AgentiPy is, how to install it, and verify your setup.

## Getting Started with AgentiPy

Welcome aboard! This section is your essential guide to setting up AgentiPy and making your first interactions with the blockchain. We'll walk you through the prerequisites, installation, and verification process.

### Your First Steps

1. **Understand AgentiPy's Vision:** Get a feel for what AgentiPy is and what it enables by reading the [AgentiPy](https://agentipy.fun/).
2. **Set Up Your Environment:** Follow the **Installation and Setup** guide below to get AgentiPy installed.&#x20;
3. **Verify the Installation:** Ensure AgentiPy is ready to use.

***


# Installation and Setup

This section guides you through the essential steps to get AgentiPy up and running in your development environment.

#### Prerequisites

Before you begin, ensure you have the following in place:

1. **Python 3.8+:** AgentiPy requires a modern Python version. Verify your installation by running:

Generated bash

```bash
python --version
# or
python3 --version
```

If you need to install or upgrade Python, please refer to the [official Python documentation](https://www.google.com/url?sa=E\&q=https%3A%2F%2Fwww.python.org%2Fdownloads%2F).

2. **Create a Virtual Environment (Highly Recommended):**\
   This isolates your project's dependencies from your system's global Python environment, preventing conflicts.

```bash
python -m venv venv
```

3. **Activate the Virtual Environment:**\
   The command to activate depends on your operating system:

* **Linux / macOS:**

  ```bash
  source venv/bin/activate
  ```
* **Windows:**

  ```bash
  venv\Scripts\activate
  ```

You'll see (venv) prepended to your terminal prompt, indicating the environment is active.

4. **Install AgentiPy:**\
   With your virtual environment activated, install AgentiPy using pip:

<pre class="language-bash"><code class="lang-bash"><strong>pip install agentipy
</strong></code></pre>

This command downloads and installs the latest stable version of AgentiPy and its dependencies.

5. **Langchain (Optional, for AI Integration):** If your project involves integrating AgentiPy with AI agent frameworks like Langchain, you'll need to install it separately:

```bash
pip install langchain
```

**Wallet with Private Keys:** To authorize and send transactions on the blockchain, you will need access to a wallet with its private keys. **Security is paramount:** never hardcode your private keys directly into your scripts. It is strongly recommended to use environment variables or a secure key management system.

***

###


# Verify Installation

After completing the installation, it's crucial to confirm that AgentiPy has been installed correctly and is accessible within your Python environment.

Follow these simple steps:

1. **Launch a Python Interpreter:**\
   Ensure your virtual environment (venv) is activated. Then, start an interactive Python session:

   ```python
   python
   # or
   python3
   ```
2. **Import AgentiPy and Check Version:**\
   Once the Python interpreter loads, execute the following commands:

   ```
   import agentipy
   print(agentipy.__version__)
   ```

Upon successful installation, you should see an output displaying the installed AgentiPy version (e.g., 2.0.2). If you encounter any ModuleNotFoundError or other errors, please revisit the **Installation and Setup** section to ensure all prerequisites were met and the installation com


# Key Features

AgentiPy is built with a focus on empowering AI agents with robust, easy-to-use tools for blockchain interaction. Below are some of its core features:

* Broad Protocol Support
* Asynchronous Operations
* Easy Integration
* Comprehensive Toolset
* Extensible Design

It also includes features like **Coingecko Integration** for market data and **Streamlined Development Utilities** for common tasks like price fetching, balance checks, and transaction confirmation.


# Broad Protocol Support

AgentiPy offers out-of-the-box support for a wide array of popular protocols and tools primarily on the Solana blockchain, with planned expansion to Base and other networks.

This broad support allows your AI agents to interact with various aspects of the decentralized ecosystem, including:

* Decentralized Exchanges (DEXs) for token swaps and liquidity management.
* NFT marketplaces and minting platforms.
* DeFi lending, borrowing, and perpetual trading protocols.
* Data providers for real-time market information.
* Utilities for tasks like domain resolution, airdrops, and more.

Refer to the Table of Supported Protocols for a detailed list of supported protocols and their available actions.


# Asynchronous Operations

## Asynchronous Operations

AgentiPy leverages Python's `asyncio` for handling blockchain interactions. This allows for efficient, non-blocking operations, which is crucial when dealing with potentially slow or unpredictable network requests common in blockchain environments.

Using asynchronous programming enables your AI agent to perform multiple tasks concurrently, improving performance and responsiveness when interacting with different protocols or checking multiple pieces of information simultaneously.


# Easy Integration

Designed with AI agents and dApps in mind, AgentiPy provides a simple and intuitive API that makes integration into existing projects seamless. Whether you're using a framework like Langchain, LlamaIndex, or building a custom agent, AgentiPy's tools and functions are easy to incorporate.

The toolkit provides Langchain-compatible tools, allowing you to directly connect blockchain functionalities to your AI agent's reasoning and action capabilities.

**New: Agentipy MCP Server for Claude Desktop**\
The Agentipy MCP Server implements the Model Context Protocol (MCP) to expose on-chain functionality directly to Claude AI via a standardized interface. Written in Python and released under the MIT license, this MCP server enables AI agents to:

* Interact with the Solana blockchain (send transactions, query accounts, manage wallets)
* Fetch price predictions and real-time data from Pyth Network
* Trade and stake tokens, deploy new tokens, and bridge assets cross-chain via deBridge
* Pull comprehensive token information—from CoinGecko’s market data to trending tokens and pool analytics

By adhering to the MCP specification, Claude Desktop can now orchestrate complex DeFi workflows and on-chain analytics seamlessly—without bespoke RPC plumbing in your agent code.

### Overview of the Agentipy MCP Server

The Agentipy MCP Server for Claude Desktop is a Python implementation of the Model Context Protocol (MCP) that provides a standardized, AI-friendly interface to the Solana blockchain. With this server, Claude AI gains the ability to perform on-chain operations—ranging from simple balance checks to complex DeFi trades—directly within its reasoning loop.

#### Features

* **Standardized MCP Interface**\
  Implements the MCP specification so Claude Desktop can discover and invoke blockchain tools via a consistent API surface.
* **Comprehensive Toolset**
  * **Transactions & Wallets:** Create, sign, and send transactions; import and manage keypairs.
  * **Account Querying:** Fetch balances, token accounts, staking positions, and NFT holdings.
  * **DeFi Actions:** Trade tokens, provide liquidity, stake/unstake, bridge assets.
  * **Market Data:** Real-time price feeds from Pyth Network; historical price queries via CoinGecko.
  * **Analytics & Trends:** Retrieve trending tokens, top gainers, pool activity, and on-chain events.
* **Easy Deployment**
  * Install via `pip install agentipy-mcp`
  * Configure endpoints and API keys in a `.env` or YAML file
  * Run the server with `agentipy-mcp serve` to expose a local HTTP MCP endpoint

#### Prerequisites

* **Python 3.8+**
* **Solana CLI** (for local keypair management)
* **API Keys** (optional but recommended for CoinGecko, Pyth, deBridge, etc.)
* **Claude Desktop** configured to point at your local MCP endpoint

```yaml
# Example .env or config.yaml
MCP_HOST: 0.0.0.0
MCP_PORT: 8080
SOLANA_RPC_URL: https://api.mainnet-beta.solana.com
COINGECKO_API_KEY: your_key_here
PTH_NETWORK_WS: wss://api.pyth.network
DEBRIDGE_API_URL: https://api.debridge.io
```


# Extensible Design

While AgentiPy supports many protocols out-of-the-box, its design is modular and extensible. Developers can easily build and integrate custom tools or protocols not currently included.

This allows you to tailor AgentiPy to specific use cases, interact with niche protocols, or implement custom logic that goes beyond the standard toolset, ensuring the toolkit can grow with your project's needs.


# Core Concepts


# MCP Integration (Model Context Protocol)

AgentiPy integrates with the Model Context Protocol (MCP) to standardize how AI agents interact with blockchain functionalities. MCP provides a structured way for AI models, like large language models (LLMs), to discover and utilize available tools, including those for on-chain actions.

## What is MCP in AgentiPy?

In the context of AgentiPy, MCP serves as an interface that exposes various blockchain operations (like checking balances, transferring tokens, or interacting with DeFi protocols) as "tools" that AI agents can use. This allows developers to build AI-driven applications where the AI can understand a user's intent and then select and execute the appropriate blockchain actions through AgentiPy's MCP-enabled tools.

## AgentiPy's MCP Features

AgentiPy offers robust MCP integration through the following:

### Built-in MCP Module

AgentiPy includes a built-in MCP module (`agentipy/mcp`) that allows you to easily expose on-chain actions. This module defines various actions related to core Solana operations, as well as integrations with protocols like Allora and Jupiter.

* **`ALL_ACTIONS`**: A dictionary that aggregates all available MCP actions from different modules.

  ```python
  # agentipy/mcp/all_actions.py
  from agentipy.mcp.allora import ALLORA_ACTIONS
  from agentipy.mcp.core import SOLANA_ACTIONS
  from agentipy.mcp.jupiter import JUPITER_ACTIONS

  ALL_ACTIONS = {
      **SOLANA_ACTIONS,
      **ALLORA_ACTIONS,
      **JUPITER_ACTIONS,
  }
  ```
* **Core Solana Actions**: Includes functionalities like `GET_BALANCE`, `TRANSFER`, and `DEPLOY_TOKEN`.
* **Allora Actions**: Provides tools for interacting with the Allora protocol, such as `GET_ALL_TOPICS` and `GET_PRICE_PREDICTION`.
* **Jupiter Actions**: Offers actions for Jupiter exchange, like `STAKE_WITH_JUP` and `TRADE_WITH_JUP`.

### MCP Server

AgentiPy provides an MCP server (`agentipy/mcp/mcp_server.py`) that can be run to expose these tools over a network interface. This server automatically registers the tools defined in `ALL_ACTIONS`.

```python
# agentipy/mcp/mcp_server.py
from mcp.server.fastmcp import FastMCP, Context
from mcp.types import Tool, TextContent
from agentipy.agent import SolanaAgentKit
from agentipy.mcp.all_actions import ALL_ACTIONS

# Initialize server with Solana tools
mcp = FastMCP(
    "agentipy-mcp",
    instructions="Solana tools: Get balance, transfer SOL, price prediction, etc.",
    dependencies=["pydantic", "httpx", "solana"],
)
# ... server setup and run functions ...
```

You can start this server with your `SolanaAgentKit` instance:

```python
from agentipy.agent import SolanaAgentKit
from agentipy.mcp.mcp_server import start_mcp_server

# Ensure your SolanaAgentKit is initialized
# PRIVATE_KEY = "YOUR_SECURE_PRIVATE_KEY"
# RPC_URL = "YOUR_SOLANA_RPC_URL"
# agent = SolanaAgentKit(private_key=PRIVATE_KEY, rpc_url=RPC_URL)

# start_mcp_server(agent) # This would start the server
```

*(Note: The above server start is commented out for documentation purposes.)*

### Agentipy MCP Server for Claude Desktop

For users of Claude AI, especially with Claude Desktop, AgentiPy offers a dedicated MCP server: [**Agentipy MCP Server for Claude Desktop**](https://github.com/niceberginc/agentipy-mcp).

This server is specifically designed to integrate with Claude Desktop, allowing Claude to leverage AgentiPy's blockchain tools through the MCP interface.

**Example Claude Desktop Configuration:**

```json
// Claude Desktop Configuration
{
  "mcpServers": {
    "agentipy": {
      "command": "./run_mcp.sh", // Script to run the AgentiPy MCP server
      "autoApprove": ["GET_BALANCE", "PRICE_PREDICTION"] // Actions that can be auto-approved
    }
  }
}
```

This integration enables Claude to perform a variety of on-chain tasks, including:

* Checking wallet balances
* Executing cross-chain swaps (e.g., via deBridge)
* Fetching real-time price feeds (e.g., from Pyth Network)
* Accessing market analytics (e.g., from CoinGecko)
* Performing AI-driven trading operations

By using MCP, AgentiPy makes complex blockchain interactions accessible to AI agents in a standardized and developer-friendly manner.


# SolanaAgentKit

The `SolanaAgentKit` is a fundamental component of AgentiPy, providing the necessary tools and configurations for AI agents to interact with the Solana blockchain. It encapsulates the connection to a Solana RPC endpoint and manages the wallet (private key) required for signing transactions.

## Purpose

* **Blockchain Connection:** Establishes and maintains the connection to a Solana RPC node, enabling communication with the Solana network.
* **Wallet Management:** Securely handles the private key associated with a Solana wallet, which is essential for authorizing transactions and interacting with on-chain programs.
* **Transaction Signing:** Provides methods for signing transactions before they are submitted to the Solana network.
* **Context Provider:** Acts as a central context object that is passed to various AgentiPy tools, giving them access to the blockchain connection and wallet information.

## Usage

To use `SolanaAgentKit`, you need to initialize it with your Solana wallet's private key and the URL of a Solana RPC endpoint.

### Initialization Example

```python
from agentipy.agent import SolanaAgentKit

# !! IMPORTANT SECURITY WARNING !!
# NEVER hardcode your private key directly into your code, ESPECIALLY for Mainnet.
# This is for demonstration purposes ONLY.
# In a real application, use environment variables, secure key vaults, or other
# secure key management practices. Compromising your private key can lead to
# loss of funds.

PRIVATE_KEY = "YOUR_PRIVATE_KEY_HERE"  # ⚠️ REPLACE THIS SECURELY! ⚠️
RPC_URL = "https://api.mainnet-beta.solana.com"  # Mainnet RPC endpoint, change to devnet or testnet as needed

# Initialize the SolanaAgentKit
agent = SolanaAgentKit(
    private_key=PRIVATE_KEY,
    rpc_url=RPC_URL
)

print(f"SolanaAgentKit initialized. Using RPC: {agent.rpc_url}")
# You can now pass this 'agent' object to other AgentiPy tools.
```

**Security Note:** Always handle private keys with extreme care. For production environments, use secure methods like environment variables or dedicated secret management services instead of hardcoding them.


# Tools

AgentiPy offers a rich set of tools covering fundamental blockchain interactions. This includes functionalities for:

* **Token Management:** Buying, selling, swapping, and transferring tokens.
* **NFT Handling:** Minting, deploying collections, and managing metadata.
* **DeFi Interactions:** Lending, borrowing, managing liquidity, and perpetual trading.
* **Data Fetching:** Retrieving token prices, account balances, transaction histories, and market data.
* **Utility Functions:** Transaction confirmation, address validation, and more.

This comprehensive suite means you often won't need to piece together multiple libraries for common dApp functionalities.


# Supported Protocols and Tools

Below is a Table of Supported Protocols and Tools offering a quick overview. More detailed documentation for each specific tool can be found in the Tools section.

This table lists the protocols and tools currently supported by AgentiPy, along with their primary blockchain focus and typical actions.

| Protocol                  | Blockchain | Actions                                                                              | GitHub Tool Link                                                                                                        |
| ------------------------- | ---------- | ------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------- |
| Jupiter                   | Solana     | Stake SOL with JUP LST                                                               | [Jupiter Stake Tool](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/stake_with_jup.py)                |
| Jupiter                   | Solana     | Token swaps using Jupiter aggregator                                                 | [Jupiter Swap Tool](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/trade.py)                          |
| PumpFun                   | Solana     | Buy/sell tokens on Pump.fun, retrieve pump curve states                              | [PumpFun Interaction Tool](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_pumpfun.py)             |
| PumpFun                   | Solana     | Launch new tokens on Pump.fun                                                        | [PumpFun Launch Tool](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/launch_pumpfun_token.py)         |
| Raydium                   | Solana     | Buy/sell tokens, provide liquidity on Raydium                                        | [Raydium Trade Tool](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_raydium.py)                   |
| Metaplex                  | Solana     | NFT minting, collection deployment, metadata/royalty management via proxy            | [Metaplex Tools](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_metaplex.py)                      |
| DexScreener / Token Data  | Solana     | Get token data by ticker/address (primarily via DexScreener)                         | [Token Data Tool (DexScreener)](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/get_token_data.py)     |
| Helius                    | Solana     | Fetch balances, NFT mint lists, events, webhooks via Helius API                      | [Helius Tools](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_helius.py)                          |
| MoonShot                  | Solana     | Buy/sell with collateral on Moonshot bonding curves, slippage options                | [MoonShot Trade Tool](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_moonshot.py)                 |
| SNS (Solana Name Service) | Solana     | Resolve .sol domains, register domains, manage favorite domains                      | [SNS Tools](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_sns.py)                                |
| Cybers                    | Solana     | Authenticate wallet, create coin using Cybers API                                    | [Cybers Tools](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_cybers.py)                          |
| Adrena                    | Solana     | Open/close perpetual trades (long/short) on Adrena via proxy                         | [Adrena Trade Tool](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_adrena.py)                     |
| Drift                     | Solana     | Manage user accounts, deposit/withdraw, perp trades, account info on Drift via proxy | [Drift Protocol Tools](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_drift.py)                   |
| Flash                     | Solana     | Open/close leveraged trades on Flash platform via proxy                              | [Flash Trade Tool](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_flash.py)                       |
| Jito                      | Solana     | Manage tip accounts, get bundles, send transactions/bundles via Jito API             | [Jito Bundles/Tips Tool](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_jito.py)                  |
| Lulo / Flexlend           | Solana     | Lend assets to earn interest, withdraw tokens on Lulo via API                        | [Lulo Lend/Withdraw Tool](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_lulo.py)                 |
| RugCheck.xyz              | Solana     | Fetch detailed/summary token reports from RugCheck.xyz API                           | [RugCheck Report Tool](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/rugcheck.py)                    |
| AllDomains / SNS          | Solana     | Resolve domains, get owned domains (often SNS-based) via proxy                       | [AllDomains Resolve Tool](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_alldomains.py)           |
| Orca                      | Solana     | Manage Orca CLMM (Whirlpool) liquidity pools and positions via proxy                 | [Orca CLMM Tools](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_orca.py)                         |
| Backpack Exchange         | Solana     | Manage account balances, settings, orders on Backpack Exchange via API               | [Backpack Exchange Tools](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_backpack.py)             |
| OpenBook                  | Solana     | Create markets on OpenBook DEX via proxy                                             | [OpenBook Market Tool](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_openpook.py)                |
| Light Protocol            | Solana     | Send compressed airdrops, shield/unshield SOL using Light Protocol via proxy         | [Light Protocol Airdrop Tool](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_lightprotocol.py)    |
| Pyth Network              | Solana     | Fetch token prices from Pyth Network on-chain oracles                                | [Pyth Price Fetch Tool](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_pyth.py)                   |
| Manifest                  | Solana     | Create markets, place/cancel orders on Manifest DEX via proxy                        | [Manifest DEX Tools](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_manifest.py)                  |
| Stork                     | Solana     | Get real-time token price feed from Stork API                                        | [Stork Price Feed Tool](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_stork.py)                  |
| Gibwork                   | Solana     | Create tasks with token rewards using Gibwork API                                    | [Gibwork Task Tool](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/create_gibwork.py)                 |
| Meteora                   | Solana     | Create DLMM pools with configurations on Meteora                                     | [Meteora DLMM Pool Tool](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/create_meteora_dlmm_pool.py)  |
| ThreeLand                 | Solana     | ThreeLand NFT mint and deploy collection via proxy                                   | [ThreeLand NFT Tool](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_3land.py)                     |
| Elfa AI                   | Solana     | Get trending tokens, mentions, smart account stats from Elfa AI API                  | [Elfa AI Analytics Tool](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_elfa_ai.py)               |
| FluxBeam                  | Solana     | Create a new liquidity pool on FluxBeam via API                                      | [FluxBeam Pool Tool](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_fluxbeam.py)                  |
| Solana SPL Token          | Solana     | Burn SPL tokens and close the associated token account                               | [Burn & Close Account Tool](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/burn_and_close_account.py) |
| Image Generation (OpenAI) | Solana     | Generate images using OpenAI's DALL-E API                                            | [DALL-E Image Generation Tool](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/create_image.py)        |
| Solana SPL Token          | Solana     | Deploy a new SPL token (create mint, metadata, token accounts)                       | [SPL Token Deployment Tool](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/deploy_token.py)           |
| Price Fetching (Jupiter)  | Solana     | Fetch token prices, often using Jupiter's Price API                                  | [Jupiter Price API Tool](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/fetch_price.py)               |
| Solana Wallet             | Solana     | Get SOL and SPL token balances for a wallet                                          | [Wallet Balance Tool](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/get_balance.py)                  |
| Solana Network            | Solana     | Get current Solana network TPS (Transactions Per Second) and track performance       | [Solana TPS Tool](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/get_tps.py)                          |
| Solana Faucet             | Solana     | Request SOL funds from a faucet on Devnet or Testnet                                 | [Solana Faucet Tool](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/request_faucet_funds.py)          |
| Sendarcade                | Solana     | Play Rock Paper Scissors game on Sendarcade API, involving SOL transactions          | [Sendarcade Game Tool](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_sendarcade.py)              |
| Solayer                   | Solana     | Stake SOL for sSOL (Solayer liquid staking token) via Solayer API                    | [Solayer Staking Tool](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_solayer.py)                 |
| SolutioFi                 | Solana     | Token management (close accounts, burn, merge, spread) via SolutioFi API & proxy     | [SolutioFi Token Management](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_solutiofi.py)         |
| Squads (Multisig/DAO)     | Solana     | Create multisigs, manage proposals, deposit/transfer from treasury via proxy         | [Squads Multisig/DAO Tools](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_squads.py)             |
| Switchboard (Oracle)      | Solana     | Simulate Switchboard oracle feeds via proxy                                          | [Switchboard Oracle Tool](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_switchboard.py)          |
| Tensor (NFT Marketplace)  | Solana     | List NFTs, manage listings on Tensor via proxy                                       | [Tensor NFT Tools](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_tensor.py)                      |
| TipLink                   | Solana     | Create TipLinks for sending SOL or SPL tokens via proxy                              | [TipLink Creation Tool](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_tiplink.py)                |
| Voltr (DeFi)              | Solana     | Deposit/withdraw from Voltr DeFi strategies, get position values via proxy           | [Voltr DeFi Tools](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_voltr.py)                       |
| Solana SPL Token/SOL      | Solana     | Transfer SOL or SPL tokens                                                           | [Token/SOL Transfer Tool](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/transfer.py)                 |
| Allora                    | Solana     | Get AI model inferences, price predictions (e.g., BTC, ETH) from Allora API          | [Allora AI Inferences Tool](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_allora.py)             |
| CoinGecko                 | Solana     | Fetch token prices, market data, trending tokens from CoinGecko API                  | [CoinGecko Data Tool](https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_coingecko.py)                |
| Agentipy MCP              | Solana     | Extensible Solana toolset via a Model Context Protocol server                        | [Agentipy MCP Tool](https://github.com/niceberginc/agentipy/tree/main/agentipy/mcp)                                     |


# Burn and Close Account

The `Burn and Close Account` tool is part of AgentiPy, allowing users to burn remaining SPL tokens in an account and then close the token account itself on the Solana blockchain. This is useful for cleaning up token accounts that are no longer needed and reclaiming the SOL locked for rent.

## Functionality

This tool is primarily implemented in the `BurnManager` class.

### Key Methods:

* `burn_and_close_account(agent: SolanaAgentKit, token_account: str)`:
  * Checks the balance of the specified `token_account`.
  * If the balance is greater than zero, it creates and adds a `burn` instruction to a transaction.
  * It then adds a `close_account` instruction to the transaction.
  * The transaction also includes compute unit adjustments.
  * Finally, it signs and sends the transaction.
* `process_multiple_accounts(agent: SolanaAgentKit, token_accounts: list)`:
  * Iterates through a list of `token_accounts` (strings).
  * Calls `burn_and_close_account` for each account to process them individually.

**Note:** This tool directly interacts with the Solana blockchain and modifies account states. It requires the agent's wallet to be the owner of the token account or have the necessary authority. Always test thoroughly on a devnet or testnet before using on mainnet.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/burn_and_close_account.py>


# Create Gibwork Task

The `Create Gibwork Task` tool is part of AgentiPy, used for creating tasks on the Gibwork platform (api2.gib.work). These tasks are initiated on the Solana blockchain and can involve token rewards for completion.

## Functionality

This tool is implemented in the `GibworkManager` class.

### Key Methods:

* `create_gibwork_task(agent: SolanaAgentKit, title: str, content: str, requirements: str, tags: list[str], token_mint_address: PublicKey, token_amount: int) -> GibworkCreateTaskResponse`:
  * Constructs a payload with task details: `title`, `content` (description of the task), `requirements`, `tags` (list of keywords), `payer` (agent's wallet address), and `token` information (mint address and amount for rewards).
  * Makes a POST request to the Gibwork API (`https://api2.gib.work/tasks/public/transaction`) to get a serialized transaction.
  * Deserializes the transaction, signs it with the agent's wallet.
  * Sends and confirms the transaction on the Solana network.
  * Returns a `GibworkCreateTaskResponse` containing the status, task ID, and transaction signature.

**Note:** This tool interacts with an external API (Gibwork) and the Solana blockchain. It requires a valid `SolanaAgentKit` setup with a funded wallet. The `token_mint_address` and `token_amount` must correspond to tokens held by the agent's wallet.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/create_gibwork.py>


# Create Image

The `Create Image` tool is part of AgentiPy. Based on its name and implementation, it is used for generating images using OpenAI's DALL·E models. The tool requires an OpenAI API key to be configured within the `SolanaAgentKit`.

## Functionality

This tool is implemented in the `ImageGenerator` class.

### Key Methods:

* `create_image(agent: SolanaAgentKit, prompt: str, size: str = "1024x1024", n: int = 1)`:
  * Takes a `SolanaAgentKit` instance (which should have `openai_api_key` set), a text `prompt` for the image generation, the desired `size` (defaulting to "1024x1024"), and the number of images `n` to generate (defaulting to 1).
  * Checks if the `openai_api_key` is present in the agent's configuration.
  * Uses the `openai.Image.create` method (from the `openai` library) to request image generation based on the provided parameters.
  * Returns a dictionary containing a list of URLs for the generated images.

##

**Note:** This tool interacts with the OpenAI API and requires a valid API key. Ensure that the `openai` library is installed and that your API key has the necessary permissions and quota for image generation.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/create_image.py>


# Create Meteora DLMM Pool

The `Create Meteora DLMM Pool` tool, part of AgentiPy, is designed for creating Dynamic Liquidity Market Maker (DLMM) pools on the Meteora platform, which operates on the Solana blockchain. It allows for the setup of customizable, permissionless liquidity pools.

## Functionality

This tool is implemented in the `MeteoraManager` class.

### Key Methods:

* `create_meteora_dlmm_pool(agent: SolanaAgentKit, bin_step: int, token_a_mint: PublicKey, token_b_mint: PublicKey, initial_price: float, price_rounding_up: bool, fee_bps: int, activation_type: ActivationType, has_alpha_vault: bool, activation_point: Optional[int]) -> str`:
  * Takes `SolanaAgentKit` instance, pool configuration parameters like `bin_step`, mint addresses for `token_a_mint` and `token_b_mint`, `initial_price` for the pool, `fee_bps` (basis points), `activation_type` (Timestamp or Slot), and other Meteora-specific parameters.
  * It fetches mint information for both tokens to determine decimals.
  * Calculates the initial price per lamport and the activation bin ID based on the inputs.
  * Uses `DLMM.create_customizable_permissionless_lb_pair` from AgentiPy's Meteora DLMM utilities to construct the transaction for creating the pool.
  * Sends and confirms the transaction using the agent's wallet.
  * Returns the transaction signature as a string.

##

**Note:** This tool is for advanced users familiar with DeFi concepts, liquidity pools, and the Meteora DLMM protocol. Incorrect parameters can lead to pool misconfiguration or loss of funds. Always test extensively on a devnet environment first. Refer to the official Meteora documentation for details on parameters like `bin_step`, `fee_bps`, and activation conditions.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/create_meteora_dlmm_pool.py>


# Deploy Token

The `Deploy Token` tool is part of AgentiPy, used for deploying new SPL (Solana Program Library) tokens on the Solana blockchain. This involves creating a new token mint, initializing it, and minting an initial supply to the creator's associated token account.

## Functionality

This tool is implemented in the `TokenDeploymentManager` class.

### Key Methods:

* `deploy_token(agent: SolanaAgentKit, decimals: int = 9) -> Dict[str, Any]`:
  * Takes a `SolanaAgentKit` instance and an optional `decimals` parameter for the new token (defaulting to 9).
  * Generates a new `Keypair` for the token mint.
  * Constructs a transaction that includes instructions for:
    1. Creating a new account for the mint, owned by the SPL Token Program.
    2. Initializing the mint with the specified `decimals`, mint authority, and freeze authority (set to the agent's wallet).
    3. Creating an associated token account (ATA) for the agent's wallet to receive the initial supply.
    4. Minting an initial supply (hardcoded to 1,000,000,000 tokens adjusted by 10^8, which seems like a potential point of confusion as decimals are also a parameter) to the creator's ATA.
  * Signs the transaction with both the new mint's keypair and the agent's wallet.
  * Sends and confirms the transaction.
  * Returns a dictionary containing the new `mint` address (as a string) and the transaction `signature`.

##

**Note:** This tool creates a new SPL token on the Solana blockchain. The agent's wallet will be the mint and freeze authority for the token and will receive the initial minted supply. The amount of tokens minted initially is hardcoded in the script.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/deploy_token.py>


# Fetch Price

The `Fetch Price` tool, part of AgentiPy, allows users to fetch the price of a given token in USDC by querying the Jupiter API (`https://api.jup.ag/price/v2`). It's a simple way to get current price data for a specific token mint address on Solana.

## Functionality

This tool is implemented in the `TokenPriceFetcher` class.

### Key Methods:

* `fetch_price(token_id: str) -> str`:
  * Takes a `token_id` (the token mint address as a string) as input.
  * Constructs a URL to query the Jupiter API.
  * Uses `aiohttp` to make an asynchronous GET request to the API.
  * Parses the JSON response to extract the price of the token in USDC.
  * Returns the price as a string.
  * Raises an exception if the API request fails, the response status is not 200, or if price data for the token is not available in the response.

##

**Note:** This tool relies on the public Jupiter API. Availability and rate limits of the API are determined by Jupiter Aggregator. The returned price is typically in USDC.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/fetch_price.py>


# Get Balance

The `Get Balance` tool, part of AgentiPy, allows users to fetch the SOL balance or a specific SPL token balance for the agent's wallet on the Solana blockchain.

## Functionality

This tool is implemented in the `BalanceFetcher` class.

### Key Methods:

* `get_balance(agent: SolanaAgentKit, token_address: Optional[Pubkey] = None) -> Optional[float]`:
  * Takes a `SolanaAgentKit` instance and an optional SPL token mint `token_address` (as a `solders.pubkey.Pubkey` object).
  * If `token_address` is not provided, it fetches the native SOL balance of the agent's wallet and returns it in SOL units (float).
  * If `token_address` is provided, it determines the associated token account (ATA) for the agent's wallet and the given mint. It then fetches the balance of this ATA and returns it in its UI amount (float, adjusted for token decimals).
  * Returns `None` if a token account does not exist or has no balance information in the response.
  * Raises an exception if the balance check fails for other reasons.

##

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/get_balance.py>


# Get Token Data

The `Get Token Data` tool, part of AgentiPy, allows users to retrieve information about SPL tokens on the Solana blockchain. It can fetch token details using either the token's mint address (from Jupiter's token list) or its ticker symbol (from DexScreener).

## Functionality

This tool is implemented in the `TokenDataManager` class.

### Key Methods:

* `get_token_data_by_address(mint: Pubkey) -> Optional[JupiterTokenData]`:
  * Takes a token `mint` address (`solders.pubkey.Pubkey` object).
  * Fetches a list of verified tokens from Jupiter's token API (`https://tokens.jup.ag/tokens?tags=verified`).
  * Searches for the token with the matching mint address in the list.
  * Returns a `JupiterTokenData` object (containing address, symbol, name) if found, otherwise `None`.
* `get_token_address_from_ticker(ticker: str) -> Optional[str]`:
  * Takes a token `ticker` symbol (e.g., "SOL", "USDC").
  * Queries the DexScreener API (`https://api.dexscreener.com/latest/dex/search`) for pairs matching the ticker.
  * Filters for Solana pairs and sorts them, prioritizing those with higher Fully Diluted Valuation (FDV).
  * Returns the base token's mint address (string) for the best matching Solana pair if found, otherwise `None`.
* `get_token_data_by_ticker(ticker: str) -> Optional[JupiterTokenData]`:
  * First calls `get_token_address_from_ticker` to resolve the ticker to a mint address.
  * If an address is found, it then calls `get_token_data_by_address` with that address.
  * Returns a `JupiterTokenData` object or `None`.

##

**Note:** This tool relies on external APIs (Jupiter and DexScreener). Their availability and rate limits apply.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/get_token_data.py>


# Get TPS (Transactions Per Second)

The `Get TPS` tool, part of AgentiPy, is used to fetch and analyze Transactions Per Second (TPS) data from the Solana blockchain. It can retrieve current TPS and also track performance metrics over time.

## Functionality

The tool consists of a standalone function `fetch_performance_samples` and a class `SolanaPerformanceTracker`.

### Key Functions/Classes:

* `fetch_performance_samples(agent: SolanaAgentKit, sample_count: int = 1) -> List[NetworkPerformanceMetrics]`:
  * Asynchronously fetches a specified number of recent performance samples from the Solana network using `agent.connection.get_recent_performance_samples()`.
  * Each sample contains data like the number of transactions and the sample period.
  * Converts these samples into a list of `NetworkPerformanceMetrics` objects, which include calculated TPS, total transactions, sampling period, and current slot.
* `SolanaPerformanceTracker`:
  * **`__init__(self, agent: SolanaAgentKit)`**: Initializes the tracker with a `SolanaAgentKit` instance.
  * **`record_latest_metrics(self) -> NetworkPerformanceMetrics`**: Fetches the single latest performance sample using `fetch_performance_samples` and stores it in an internal `metrics_history`.
  * **`calculate_average_tps(self) -> Optional[float]`**: Calculates the average TPS from all metrics stored in `metrics_history`.
  * **`find_maximum_tps(self) -> Optional[float]`**: Finds the maximum TPS from the `metrics_history`.
  * **`reset_metrics_history(self) -> None`**: Clears the `metrics_history`.
  * **`fetch_current_tps(agent: SolanaAgentKit) -> float`** (static method): A static method to quickly fetch the current TPS based on the latest single performance sample. This is likely the most commonly used function for a quick TPS check.

##

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/get_tps.py>


# Launch Pump.fun Token

The `Launch Pump.fun Token` tool, part of AgentiPy, enables users to launch new tokens on the Pump.fun platform on the Solana blockchain. Pump.fun is known for facilitating the creation and trading of new tokens with initial liquidity. This tool automates the process of metadata upload and transaction creation for launching a token.

## Functionality

This tool is implemented in the `PumpfunTokenManager` class.

### Key Methods:

* `_upload_metadata(session: aiohttp.ClientSession, token_name: str, token_ticker: str, description: str, image_url: str, options: Optional[PumpfunTokenOptions] = None) -> Dict[str, Any]`:
  * (Internal method) Uploads token metadata (name, symbol, description, image, and optional social links like Twitter, Telegram, website) to IPFS via Pump.fun's API. Requires an `aiohttp.ClientSession`.
* `_create_token_transaction(session: aiohttp.ClientSession, agent: SolanaAgentKit, mint_keypair: Keypair, metadata_response: Dict[str, Any], options: Optional[PumpfunTokenOptions] = None) -> VersionedTransaction`:
  * (Internal method) Creates the token launch transaction by making a request to Pump.fun's API (`https://pumpportal.fun/api/trade-local`).
  * The payload includes the agent's public key, metadata URI from the upload, mint address, initial liquidity amount in SOL, slippage, and priority fee.
  * Returns a `VersionedTransaction` object.
* `launch_pumpfun_token(agent: SolanaAgentKit, token_name: str, token_ticker: str, description: str, image_url: str, options: Optional[PumpfunTokenOptions] = None) -> TokenLaunchResult`:
  * The main public method to launch a token.
  * Generates a new `Keypair` for the token mint.
  * Calls `_upload_metadata` to upload all token details and image.
  * Calls `_create_token_transaction` to get the transaction from Pump.fun.
  * Signs the transaction with the new mint's keypair and the agent's wallet.
  * Sends the transaction to the Solana network.
  * Returns a `TokenLaunchResult` containing the transaction `signature`, `mint` address, and `metadata_uri`.

### `PumpfunTokenOptions`

This is likely a Pydantic model or TypedDict (defined in `agentipy.types`) that includes fields such as:

* `twitter: Optional[str]`
* `telegram: Optional[str]`
* `website: Optional[str]`
* `initial_liquidity_sol: float` (Amount of SOL for initial liquidity)
* `slippage_bps: int` (Slippage in basis points)
* `priority_fee: float` (Priority fee in SOL)

##

**Critical Note:** Launching tokens on Pump.fun involves real financial transactions on the Solana Mainnet. This tool directly interacts with Pump.fun's APIs and the Solana blockchain. **Use with extreme caution.** Ensure you understand the costs, risks, and implications. It is highly recommended to use a fresh wallet (burner wallet) with only the necessary amount of SOL for the launch. Test image URLs and metadata thoroughly.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/launch_pumpfun_token.py>


# Request Faucet Funds

The `Request Faucet Funds` tool, part of AgentiPy, is used to request test SOL tokens from a Solana faucet. This functionality is typically available on **Devnet or Testnet** and is essential for developers to obtain tokens for testing applications without using real assets.

## Functionality

This tool is implemented in the `FaucetManager` class.

### Key Methods:

* `request_faucet_funds(agent: SolanaAgentKit) -> str`:
  * Takes a `SolanaAgentKit` instance, which provides the wallet address (`agent.wallet_address`) to receive the airdrop and the connection (`agent.connection`) to the Solana cluster.
  * Requests an airdrop of 5 SOL (hardcoded as `5 * LAMPORTS_PER_SOL`) to the agent's wallet address.
  * Confirms the transaction using the latest blockhash.
  * Returns the transaction signature as a string upon successful completion.
  * Raises an exception if the airdrop request fails, times out, or if the response does not contain a transaction signature.

##

**Note:** This tool is only effective on Solana networks that have an active faucet (primarily Devnet, sometimes Testnet). It will not work on Mainnet. Faucet availability and airdrop amounts can vary.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/request_faucet_funds.py>


# RugCheck

The `RugCheck` tool, part of AgentiPy, is used to fetch information about Solana tokens from the RugCheck.xyz API (`https://api.rugcheck.xyz/v1`). It provides various endpoints to get token reports (summary and detailed), domain information, leaderboards, new/trending tokens, and LP locker details. This data can help assess the potential risks and community standing of a token.

## Functionality

This tool is implemented in the `RugCheckManager` class.

### Key Features:

* Initializes with an optional API key for authenticated requests.
* Provides methods to fetch:
  * **Token Reports**: `fetch_token_report_summary(mint: str)` and `fetch_token_detailed_report(mint: str)` return `TokenCheck` objects with risk assessments and details.
  * **Domain Information**: `fetch_all_domains()`, `fetch_domains_csv()`, `lookup_domain(domain_id: str)`, `fetch_domain_records(domain_id: str)`.
  * **Leaderboards & Stats**: `fetch_leaderboard()`, `fetch_new_tokens()`, `fetch_most_viewed_tokens()`, `fetch_trending_tokens()`, `fetch_recently_verified_tokens()`. These return lists of tokens or statistics.
  * **LP Lockers**: `fetch_token_lp_lockers(token_id: str)` and `fetch_token_flux_lp_lockers(token_id: str)` return `TokenLockers` data.
  * **Token Votes**: `fetch_token_votes(mint: str)`.
* Uses `aiohttp` for asynchronous API requests.
* Handles API key authentication if provided.

The `TokenCheck` type likely includes fields such as risk scores, social information, market data, holder analysis, and contract details. `TokenLockers` would detail liquidity locks.

##

**Note:** This tool relies on the external RugCheck.xyz API. The availability of data, rate limits, and the need for an API key are determined by RugCheck.xyz. The information provided by RugCheck is for informational purposes and should not be considered financial advice.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/rugcheck.py>


# Stake with Jupiter (JUP)

The `Stake with Jup` tool, part of AgentiPy, allows users to stake SOL tokens with the JUP validator via a Jupiter API endpoint. This process typically involves swapping SOL for jupSOL (a liquid staking token representing staked SOL with Jupiter's validator) or directly staking SOL into Jupiter's LST pool.

## Functionality

This tool is implemented in the `StakeManager` class.

### Key Methods:

* `stake_with_jup(agent: SolanaAgentKit, amount: float) -> str`:
  * Takes a `SolanaAgentKit` instance (which provides the wallet and connection) and the `amount` of SOL to stake.
  * Constructs a URL to interact with Jupiter's worker API (`https://worker.jup.ag/blinks/swap/...`) to get a transaction for staking SOL (specifically, it seems to target a swap/stake into `jupSoLaHXQiZZTSfEWMTRRgpnyFm8f6sZdosWBjx93v`, which is jupSOL).
  * The agent's wallet address is sent as the account in the payload.
  * Retrieves the serialized transaction from the API response.
  * Signs the transaction with the agent's wallet.
  * Sends and confirms the transaction on the Solana network.
  * Returns the transaction signature as a string.

##

**Important Note:** This tool performs on-chain transactions that will spend SOL from the agent's wallet. Staking mechanisms can have associated risks, including smart contract vulnerabilities or changes in staking reward rates. Always ensure you understand the specifics of the JUP staking program before using this tool with significant funds.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/stake_with_jup.py>


# Trade (Token Swap)

The `Trade` tool, part of AgentiPy, provides functionalities for executing token swaps on the Solana blockchain using the Jupiter Aggregator. It allows users to swap one SPL token (or SOL) for another by fetching optimal routes and transaction details from Jupiter's API.

## Functionality

This tool is implemented in the `TradeManager` class.

### Key Methods:

* `trade(agent: SolanaAgentKit, output_mint: Pubkey, input_amount: float, input_mint: Pubkey = TOKENS["USDC"], slippage_bps: int = DEFAULT_OPTIONS["SLIPPAGE_BPS"]) -> str`:
  * Takes a `SolanaAgentKit` instance, the `output_mint` (Pubkey of the token to receive), `input_amount` (amount of the input token to swap, in UI units like SOL or USDC quantity), `input_mint` (Pubkey of the token to send, defaults to USDC), and `slippage_bps` (slippage tolerance in basis points, default is 300 = 3%).
  * Fetches a swap quote from the Jupiter API (`/quote`) based on the input parameters. This quote provides the best route and expected output amount.
  * Requests the serialized swap transaction from the Jupiter API (`/swap`) using the obtained quote and the agent's wallet address.
  * Signs the received `VersionedTransaction` with the agent's wallet.
  * Sends and confirms the transaction on the Solana network.
  * Returns the transaction signature as a string.

##

**Important Note:** This tool performs on-chain financial transactions. Using it with real assets carries risk, including potential loss of funds due to market volatility, slippage, or smart contract interactions. Always test thoroughly on Devnet with small amounts if possible, and understand the tokens and protocols you are interacting with.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/trade.py>


# Transfer Tokens

The `Transfer Tokens` tool, part of AgentiPy, allows users to send SOL (native Solana) or SPL (Solana Program Library) tokens from the agent's wallet to a specified recipient address on the Solana blockchain.

## Functionality

This tool is implemented in the `TokenTransferManager` class.

### Key Methods:

* `transfer(agent: SolanaAgentKit, to: str, amount: float, mint: str = None) -> str`:
  * Takes a `SolanaAgentKit` instance, the recipient's public key as a string (`to`), the `amount` to transfer (in UI units, e.g., SOL amount or number of SPL tokens), and an optional `mint` address (string) for SPL tokens.
  * If `mint` is `None`, it performs a native SOL transfer. The `amount` is converted to lamports.
  * If `mint` is provided, it performs an SPL token transfer.
    * It determines the Associated Token Account (ATA) for both the sender (agent's wallet) and the recipient for the given `mint`.
    * It fetches the SPL token's mint information to get the `decimals` for correct amount conversion.
    * It constructs an SPL token transfer instruction.
  * The transaction is signed with the agent's wallet.
  * The raw transaction is sent to the network.
  * Returns the transaction signature as a string.

##

**Note:** This tool performs on-chain transactions that will move SOL or SPL tokens from the agent's wallet. Always double-check the recipient address, amount, and network (Devnet/Mainnet) before executing transfers. For SPL token transfers, the sender must have a sufficient balance of the token, and the recipient must have an Associated Token Account (ATA) for that token (though some transfer functions might implicitly create it if needed, this tool's `transfer_checked` implies the ATA should exist or be creatable by the sender if they are also the payer).

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/transfer.py>


# Use 3Land

The `Use 3Land` tool, part of AgentiPy, provides functionalities for interacting with the 3Land protocol on the Solana blockchain. This allows users to create and manage NFT collections and mint individual NFTs, leveraging an Agentipy proxy service for these operations.

## Functionality

This tool is implemented in the `ThreeLandManager` class. It appears to interact with a proprietary Agentipy proxy service (`agent.base_proxy_url`) which then calls the 3Land protocol. The agent's private key is encrypted and sent to this proxy.

### Key Methods:

* `create_3land_collection(agent: SolanaAgentKit, collection_symbol: str, collection_name: str, collection_description: str, main_image_url: Optional[str] = None, cover_image_url: Optional[str] = None, is_devnet: Optional[bool] = False) -> Optional[Dict[str, Any]]`:
  * Creates a new NFT collection on 3Land.
  * Parameters include `collection_symbol`, `collection_name`, `collection_description`, optional image URLs, and an `is_devnet` flag.
  * Returns a dictionary with the transaction details or an error.
* `create_3land_nft(agent: SolanaAgentKit, item_name: str, seller_fee: float, item_amount: int, item_symbol: str, item_description: str, traits: Any, price: Optional[float] = None, main_image_url: Optional[str] = None, cover_image_url: Optional[str] = None, spl_hash: Optional[str] = None, pool_name: Optional[str] = None, is_devnet: Optional[bool] = False, with_pool: Optional[bool] = False) -> Optional[Dict[str, Any]]`:
  * Mints a new NFT within the 3Land ecosystem.
  * Requires parameters like `item_name`, `seller_fee` (for royalties), `item_amount` (number to mint), `item_symbol`, `item_description`, and `traits` (metadata).
  * Optional parameters include `price`, image URLs, `spl_hash` (possibly for token-gated mints), `pool_name`, `is_devnet` flag, and `with_pool` flag.
  * Returns a dictionary with the transaction details or an error.

##

**Important Considerations:**

* **Proxy Service:** This tool relies on an Agentipy proxy service. The availability, authentication, and terms of use for this proxy are critical.
* **On-Chain Costs:** Creating NFT collections and minting NFTs are on-chain transactions that incur SOL fees.
* **API Keys:** The use of `agent.openai_api_key` in the payload to the proxy suggests it might be used for some purpose by the proxy service, even if not directly for OpenAI functionality in this specific tool.
* **Devnet/Mainnet:** Carefully manage the `is_devnet` flag to ensure operations are performed on the intended network.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_3land.py>


# Use Adrena

The `Use Adrena` tool, part of AgentiPy, allows users to interact with the Adrena perpetual trading protocol on the Solana blockchain. It facilitates opening and closing long and short perpetual positions through an Agentipy proxy service.

## Functionality

This tool is implemented in the `AdrenaTradeManager` class. Operations are routed via an Agentipy proxy service (`agent.base_proxy_url`), which requires the agent's private key to be encrypted and sent with each request. An OpenAI API key also seems to be part of the payload to the proxy.

### Key Methods:

* `open_perp_trade_long(agent: SolanaAgentKit, price: float, collateral_amount: float, collateral_mint: Optional[str] = None, leverage: Optional[float] = None, trade_mint: Optional[str] = None, slippage: Optional[float] = None) -> Optional[Dict[str, Any]]`:
  * Opens a long perpetual position on Adrena.
  * Requires `price` (entry price) and `collateral_amount`.
  * Optional parameters include `collateral_mint` (e.g., USDC mint address), `leverage`, `trade_mint` (the asset being traded, e.g., SOL mint address), and `slippage`.
  * Returns a dictionary with the transaction details or an error.
* `open_perp_trade_short(agent: SolanaAgentKit, price: float, collateral_amount: float, collateral_mint: Optional[str] = None, leverage: Optional[float] = None, trade_mint: Optional[str] = None, slippage: Optional[float] = None) -> Optional[Dict[str, Any]]`:
  * Opens a short perpetual position on Adrena.
  * Parameters are similar to `open_perp_trade_long`.
  * Returns a dictionary with the transaction details or an error.
* `close_perp_trade_long(agent: SolanaAgentKit, price: float, trade_mint: str) -> Optional[Dict[str, Any]]`:
  * Closes an existing long perpetual position.
  * Requires `price` (closing price) and `trade_mint` (the asset of the position).
  * Returns a dictionary with the transaction details or an error.
* `close_perp_trade_short(agent: SolanaAgentKit, price: float, trade_mint: str) -> Optional[Dict[str, Any]]`:
  * Closes an existing short perpetual position.
  * Requires `price` (closing price) and `trade_mint`.
  * Returns a dictionary with the transaction details or an error.

##

**Important Considerations:**

* **Proxy Service:** Relies on an Agentipy proxy service. Understand its terms and ensure it's configured in `SolanaAgentKit`.
* **Financial Risk:** Perpetual trading is highly risky and can lead to rapid loss of funds, including liquidation of collateral. This tool should be used with extreme caution and a thorough understanding of Adrena's mechanics and market risks.
* **API Keys:** An OpenAI API key is passed to the proxy; its purpose in this context should be clarified by the proxy documentation.
* **On-Chain Costs:** All trading operations are on-chain transactions incurring SOL fees and requiring sufficient collateral.
* **Market Parameters:** Correct `trade_mint`, `collateral_mint`, `price`, and `leverage` are crucial and specific to the Adrena markets.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_adrena.py>


# Use All Domains

The `Use All Domains` tool, part of AgentiPy, provides functionalities for interacting with various Solana domain name services. It allows users to resolve domain names to wallet addresses, find domains owned by a particular wallet, and discover available Top-Level Domains (TLDs). These operations are routed through an Agentipy proxy service.

## Functionality

This tool is implemented in the `AllDomainsManager` class. It uses an Agentipy proxy service (`agent.base_proxy_url`) for its operations, sending encrypted private keys with requests. An OpenAI API key also seems to be part of the payload to the proxy.

### Key Methods:

* `resolve_all_domains(agent: SolanaAgentKit, domain: str) -> Optional[str]`:
  * Resolves a given `domain` name (e.g., "user.sol", "user.bonk") to its underlying wallet address or other relevant record. The exact type of resolution might depend on the domain service.
  * Returns the resolved address or identifier as a string, or `None` if resolution fails.
* `get_owned_domains_for_tld(agent: SolanaAgentKit, tld: str) -> Optional[List[str]]`:
  * Retrieves a list of domain names owned by the agent's wallet for a specific Top-Level Domain `tld` (e.g., "sol", "abc").
  * Returns a list of domain strings or `None`.
* `get_all_domains_tlds(agent: SolanaAgentKit) -> Optional[List[str]]`:
  * Fetches a list of all available TLDs that the AllDomains service supports.
  * Returns a list of TLD strings or `None`.
* `get_owned_all_domains(agent: SolanaAgentKit, owner: str) -> Optional[List[str]]`:
  * Retrieves all domain names across various TLDs owned by a specific `owner` public key.
  * Returns a list of domain strings or `None`.

##

**Important Considerations:**

* **Proxy Service:** This tool relies on an Agentipy proxy service. The availability, authentication, and terms of use for this proxy are critical.
* **Domain Service Coverage:** The range of supported TLDs and domain services depends on the capabilities of the AllDomains service integrated with the proxy.
* **API Keys:** The use of `agent.openai_api_key` in the payload to the proxy suggests it might be used for some purpose by the proxy service.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_alldomains.py>


# Use Allora

The `Use Allora` tool, part of AgentiPy, allows users to interact with the Allora Network, a decentralized AI network. It enables fetching AI-generated price predictions for crypto assets (BTC, ETH) and retrieving information about inference topics. This tool uses the `allora-sdk` and requires an Allora API key to be configured in the `SolanaAgentKit`.

## Functionality

This tool is implemented in the `AlloraManager` class.

### Key Methods:

* `__init__(self, agent: SolanaAgentKit, base_api_url: Optional[str] = "https://api.upshot.xyz/v2", chain: ChainSlug = ChainSlug.TESTNET)`:
  * Initializes the `AlloraAPIClient` from the `allora-sdk` using the `allora_api_key` from the `agent` and specifies the target `chain` (Testnet or Mainnet).
* `get_price_prediction(self, asset: PriceInferenceToken, timeframe: PriceInferenceTimeframe, signature_format: SignatureFormat = SignatureFormat.ETHEREUM_SEPOLIA)`:
  * Fetches a future price prediction for a given `asset` (e.g., `PriceInferenceToken.BTC`) and `timeframe` (e.g., `PriceInferenceTimeframe.FIVE_MIN`).
  * Returns a dictionary with `price_prediction`, `confidence_interval`, and `status`.
* `get_all_topics(self)`:
  * Fetches all available inference topics from the Allora Network.
  * Returns a dictionary containing a list of `AlloraTopic` objects.
* `get_inference_by_topic_id(self, topic_id: int)`:
  * Fetches inference data (prediction and confidence) for a specific `topic_id`.
  * Returns a dictionary with `inference_data` and `confidence_interval`.

##

**Note:** This tool requires an API key from Allora. The `SolanaAgentKit` is used to pass this API key (`agent.allora_api_key`) to the `AlloraManager`. Ensure the API key is correctly set in your environment or agent configuration.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_allora.py>


# Use Backpack

The `Use Backpack` tool, part of AgentiPy, provides functionalities for interacting with the Backpack Exchange. It allows users to manage their account, including fetching balances, requesting withdrawals, getting deposit history, executing orders, and accessing market data. This tool uses the `backpack-exchange-sdk`.

## Functionality

This tool is implemented in the `BackpackManager` class, which wraps both authenticated and public client functionalities of the Backpack Exchange SDK.

### Key Methods:

**Authenticated (require API key and secret in `SolanaAgentKit`):**

* `__init__(self, agent: SolanaAgentKit)`: Initializes `AuthenticationClient` using `agent.backpack_api_key` and `agent.backpack_api_secret`.
* `get_account_balances() -> dict`: Retrieves current account balances.
* `request_withdrawal(address: str, blockchain: str, quantity: str, symbol: str, ...)`: Initiates a withdrawal request.
* `get_account_settings() -> dict`: Fetches current account settings.
* `update_account_settings(...)`: Modifies account settings like auto-borrow or leverage limits.
* `get_borrow_lend_positions() -> dict`: Retrieves open borrow/lend positions.
* `execute_borrow_lend(quantity: str, side: str, symbol: str)`: Executes a borrow or lend operation.
* `get_account_deposits(fromTimestamp: int = None, ...)`: Fetches deposit history.
* `get_fill_history(order_id: str = None, ...)`: Retrieves historical trade fills.
* `execute_order(order_type: str, side: str, symbol: str, ...)`: Places an order on the exchange.
* `cancel_open_order(symbol: str, order_id: str = None, ...)`: Cancels an open order.
* And many more for fetching order history, open orders, PNL history, etc.

**Public (do not require authentication):**

* `get_supported_assets() -> dict`: Lists all assets supported by the exchange.
* `get_ticker_information(symbol: str) -> dict`: Gets ticker statistics for a specific market symbol.
* `get_markets() -> dict`: Retrieves details for all supported markets.
* `get_depth(symbol: str) -> dict`: Fetches order book depth for a market.
* `get_klines(symbol: str, interval: str, start_time: int, ...)`: Gets K-line (candlestick) data.
* And more for mark price, open interest, system status, etc.

##

**Note:** This tool interacts with the Backpack Exchange.

* Public methods can be used without an API key.
* Authenticated methods (for account management, trading, withdrawals) require a valid Backpack API key and secret to be set in the `SolanaAgentKit` instance (`agent.backpack_api_key`, `agent.backpack_api_secret`).
* Ensure your API keys have the appropriate permissions for the actions you intend to perform. Handle API keys securely.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_backpack.py>


# Use CoinGecko

The `Use CoinGecko` tool, part of AgentiPy, allows users to fetch various cryptocurrency market data from CoinGecko's API. This includes trending tokens, trending liquidity pools on Solana, top gainer/loser tokens, token price information, and detailed token info. Some endpoints are free, while others require a CoinGecko Pro API key.

## Functionality

This tool is implemented in the `CoingeckoManager` class.

### Key Methods:

* `get_trending_tokens(agent: SolanaAgentKit) -> dict`:
  * Fetches trending search terms/tokens on CoinGecko. Uses a free CoinGecko endpoint.
  * Can optionally use a demo API key if provided in `agent.coingecko_demo_api_key` and no pro key is set.
* `get_trending_pools(agent: SolanaAgentKit, duration: str = "24h") -> dict`:
  * Fetches trending liquidity pools on the Solana network.
  * **Requires a CoinGecko Pro API key** set in `agent.coingecko_api_key`.
  * `duration` can be "5m", "1h", "6h", "24h".
* `get_top_gainers(agent: SolanaAgentKit, duration: str = "24h", top_coins: int | str = "all") -> dict`:
  * Fetches top gainer (and loser) tokens.
  * **Requires a CoinGecko Pro API key**.
  * `duration` can be "1h", "24h", "7d", etc. `top_coins` can be 300, 500, 1000, or "all".
* `get_token_price_data(agent: SolanaAgentKit, token_addresses: list[str]) -> dict`:
  * Fetches price data for a list of Solana token contract addresses (e.g., USD price, market cap, 24h volume, 24h change). Uses a free CoinGecko endpoint.
  * Can optionally use a demo API key.
* `get_token_info(agent: SolanaAgentKit, token_address: str) -> dict`:
  * Fetches detailed information for a specific Solana token contract address.
  * **Requires a CoinGecko Pro API key**.
* `get_latest_pools(agent: SolanaAgentKit) -> dict`:
  * Fetches the latest liquidity pools created on the Solana network.
  * **Requires a CoinGecko Pro API key**.

### CoinGecko Manager Tool

The `CoingeckoManager` class (located in `agentipy/tools/use_coingecko.py`) serves as your interface for fetching a variety of market data from the **CoinGecko API**. This data is invaluable for AI agents requiring up-to-date information on token prices, market trends, and new opportunities on supported networks like Solana.

**Purpose:** To provide easy and structured access to CoinGecko's comprehensive market data API, enabling AI agents to make informed decisions based on real-time and historical cryptocurrency metrics.

**Under the Hood:**\
The `CoingeckoManager` methods make asynchronous HTTP requests to the official CoinGecko API endpoints (both free public endpoints and professional API endpoints). It parses the JSON responses and returns the data as Python dictionaries.

**API Keys:**\
Access to most of the powerful methods within this tool, especially those fetching detailed or real-time data like trending pools, top gainers, latest pools, and detailed token info, **requires a CoinGecko Pro API key**. Some basic methods (like `get_trending_tokens` and `get_token_price_data`) might work with a CoinGecko Demo API key or the standard free API tier, but these are subject to much stricter rate limits and may not be suitable for frequent querying by an agent.

It is **highly recommended** to obtain a CoinGecko Pro API key for reliable and extensive market data access. You must provide your CoinGecko API keys (both Pro and Demo, if you have them) when initializing your `SolanaAgentKit` instance, as the `CoingeckoManager` methods access them via the passed `agent` object:

```python
import os # Recommended for secure key loading
from solders.keypair import Keypair # Assuming you load your keypair securely
from agentipy.agent import SolanaAgentKit

# Example: Securely load your wallet keypair (replace with your actual method)
# wallet_keypair = Keypair.from_bytes(base58.b58decode(os.environ.get("SOLANA_PRIVATE_KEY")))

agent = SolanaAgentKit(
    wallet_keypair=wallet_keypair, # Your loaded Keypair
    rpc_url="YOUR_SOLANA_RPC_URL", # Your Solana RPC endpoint
    # Add your CoinGecko API keys here:
    coingecko_api_key=os.environ.get("COINGECKO_PRO_API_KEY"),      # <--- Your PRO key (recommended)
    coingecko_demo_api_key=os.environ.get("COINGECKO_DEMO_API_KEY") # <--- Your DEMO key (optional fallback)
)
```

The agent instance is a required parameter for all CoingeckoManager methods so they can access these configured API keys and potentially other agent settings.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_coingecko.py>


# Using the CoinGecko Manager Tool

All methods in the CoingeckoManager are static asynchronous methods. You call them directly from the CoingeckoManager class and must use await.

#### 1. get\_trending\_tokens

Description: Fetches the current list of cryptocurrencies that are trending on CoinGecko. This is often based on recent search popularity.

Endpoint: Uses CoinGecko's public /search/trending endpoint. May use the demo API key if available and no Pro key is set.

**Method Signature:**

```python
async def get_trending_tokens(agent: SolanaAgentKit) -> dict:
```

Parameters:

* agent (SolanaAgentKit): Required. The initialized agent instance.
* Returns:
  * A dict containing the trending tokens data. The exact structure is determined by the CoinGecko API response, but typically includes a coins key which is a list of trending coin objects, each with details like id, coin\_id, name, symbol, market\_cap\_rank, etc.

Example:

```python
import asyncio
from agentipy.agent import SolanaAgentKit
from agentipy.tools.use_coingecko import CoingeckoManager
# Assuming 'agent' is your initialized SolanaAgentKit instance

async def fetch_trending():
    try:
        trending_data = await CoingeckoManager.get_trending_tokens(agent)
        print("Currently Trending Tokens:")
        for coin in trending_data.get('coins', []):
            item = coin.get('item', {})
            print(f"- {item.get('symbol', 'N/A')} ({item.get('name', 'N/A')}): Rank {item.get('market_cap_rank', 'N/A')}")
    except Exception as e:
        print(f"Error fetching trending tokens: {e}")

# asyncio.run(fetch_trending()) # Example of how to run
```

#### 2. get\_trending\_pools

**Description:** Fetches liquidity pools that are currently trending on CoinGecko, filtered specifically for the Solana network. This endpoint is valuable for identifying pools with high recent trading volume or activity.

* Endpoint: Uses CoinGecko's Pro API endpoint /onchain/networks/solana/trending\_pools.

**Method Signature:**

```python
async def get_trending_pools(agent: SolanaAgentKit, duration: str = "24h") -> dict:
```

Parameters:

* agent (SolanaAgentKit): Required. The initialized agent instance with a CoinGecko Pro API key configured.
* duration (str): Optional. The time window to consider for trending activity. Defaults to "24h". Allowed values based on the code: "5m", "1h", "6h", "24h".
* Returns:
  * A dict containing the trending pools data. The structure includes a data key which is a list of pool objects, with details about the pool address, network, base/quote tokens, volume, etc.

Example:

```python
import asyncio
from agentipy.agent import SolanaAgentKit
from agentipy.tools.use_coingecko import CoingeckoManager
# Assuming 'agent' is initialized with a PRO CoinGecko key

async def fetch_trending_pools():
    try:
        print("Fetching trending Solana pools for the last hour...")
        trending_pools = await CoingeckoManager.get_trending_pools(agent, duration="1h")
        print("Trending Pools:")
        for pool in trending_pools.get('data', []):
            base_token = pool.get('base_token', {})
            network = pool.get('network', {})
            print(f"- {base_token.get('symbol', 'N/A')} Pool on {network.get('name', 'N/A')}: Address {pool.get('address', 'N/A')}")
    except Exception as e:
        print(f"Error fetching trending pools: {e}")
        print("Hint: This endpoint requires a CoinGecko Pro API Key configured in your agent.")

# asyncio.run(fetch_trending_pools()) # Example of how to run
```

#### 3. get\_top\_gainers

* Description: Retrieves a list of top-performing tokens by percentage change over a specified duration, including both gainers and losers.
* Endpoint: Uses CoinGecko's Pro API endpoint /coins/top\_gainers\_losers.

**Method Signature:**

```python
async def get_top_gainers(
    agent: SolanaAgentKit,
    duration: str = "24h",  # Allowed values: "1h", "24h", "7d", "14d", "30d", "60d", "1y"
    top_coins: int | str = "all"  # Allowed values: 300, 500, 1000, or "all"
) -> dict:
```

**Parameters:**

* agent (SolanaAgentKit): Required. The initialized agent instance with a CoinGecko Pro API key configured.
* duration (str): Optional. The time window for calculating price changes. Defaults to "24h". Supports various periods like "1h", "7d", "30d", etc.
* top\_coins (int | str): Optional. Limits the scope to tokens within the top N market capitalization ranks. Defaults to "all". Can be specific integers (300, 500, 1000) or "all".
* Returns:
  * A dict containing top\_gainers and top\_losers keys, each holding a list of token objects with relevant performance data.

Example:

```python
import asyncio
from agentipy.agent import SolanaAgentKit
from agentipy.tools.use_coingecko import CoingeckoManager
# Assuming 'agent' is initialized with a PRO CoinGecko key

async def fetch_top_performers():
    try:
        print("Fetching top 5 gainers/losers over the last 7 days...")
        performers = await CoingeckoManager.get_top_gainers(agent, duration="7d", top_coins=500)

        print("\nTop 5 Gainers (7d):")
        for token in performers.get('top_gainers', [])[:5]:
            print(f"- {token.get('symbol', 'N/A')}: {token.get('price_change_percentage', 0):.2f}%")

        print("\nTop 5 Losers (7d):")
        for token in performers.get('top_losers', [])[:5]:
            print(f"- {token.get('symbol', 'N/A')}: {token.get('price_change_percentage', 0):.2f}%")

    except Exception as e:
        print(f"Error fetching top performers: {e}")
        print("Hint: This endpoint requires a CoinGecko Pro API Key configured in your agent.")

# asyncio.run(fetch_top_performers()) # Example of how to run
```

#### 4. get\_token\_price\_data

Description: Fetches current price (vs. USD), market cap, 24h volume, and 24h price change for a list of specific token addresses on the Solana network.

Endpoint: Uses CoinGecko's public /simple/token\_price/{network\_id} endpoint (with network\_id=solana). May use the demo API key if available and no Pro key is set.

**Method Signature:**

```python
async def get_token_price_data(agent: SolanaAgentKit, token_addresses: list[str]) -> dict:
```

**Parameters:**

* agent (SolanaAgentKit): Required. The initialized agent instance. Accesses API keys if available.
* token\_addresses (list\[str]): Required. A list of token contract addresses on the Solana network, provided as strings.
* Returns:
  * A dict where the keys are the requested token addresses (strings) and the values are dictionaries containing the price and market data (e.g., usd, usd\_market\_cap, usd\_24h\_vol, usd\_24h\_change, last\_updated\_at).

Example:

```python
import asyncio
from agentipy.agent import SolanaAgentKit
from agentipy.tools.use_coingecko import CoingeckoManager
# Assuming 'agent' is your initialized SolanaAgentKit instance

async def fetch_prices():
    # Example SOL and USDC addresses on Mainnet-beta
    sol_address = "So11111111111111111111111111111111111111112"
    usdc_address = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"
    token_list = [sol_address, usdc_address]

    try:
        print(f"Fetching price data for: {token_list}...")
        price_info = await CoingeckoManager.get_token_price_data(agent, token_list)

        for address, data in price_info.items():
            print(f"\nData for {address}:")
            print(f"- Price (USD): ${data.get('usd', 0):.4f}")
            print(f"- 24h Change (%): {data.get('usd_24h_change', 0):.2f}%")
            print(f"- Last Updated: {data.get('last_updated_at', 'N/A')}")

    except Exception as e:
        print(f"Error fetching token price data: {e}")

# asyncio.run(fetch_prices()) # Example of how to run
```

#### 5. get\_token\_info

* Description: Fetches detailed information for a single token address on the Solana network. This can include links (website, explorer, social media), descriptions, and other metadata.
* Endpoint: Uses CoinGecko's Pro API endpoint /onchain/networks/solana/tokens/{token\_address}/info.

**Method Signature:**

```python
async def get_token_info(agent: SolanaAgentKit, token_address: str) -> dict:
```

**Parameters:**

* agent (SolanaAgentKit): Required. The initialized agent instance with a CoinGecko Pro API key configured.
* token\_address (str): Required. The contract address of the token (as a string).
* Returns:
  * A dict containing detailed information about the specified token.

Example:

```python
import asyncio
from agentipy.agent import SolanaAgentKit
from agentipy.tools.use_coingecko import CoingeckoManager
# Assuming 'agent' is initialized with a PRO CoinGecko key

async def fetch_token_details():
    usdc_address = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" # USDC Mainnet-beta address
    try:
        print(f"Fetching detailed info for {usdc_address} (USDC)...")
        token_info = await CoingeckoManager.get_token_info(agent, usdc_address)
        print("Token Info:")
        print(f"- Name: {token_info.get('name', 'N/A')}")
        print(f"- Symbol: {token_info.get('symbol', 'N/A')}")
        print(f"- Description (partial): {token_info.get('description', '')[:150]}...")
        # Access links: token_info.get('links', {})
    except Exception as e:
        print(f"Error fetching token info: {e}")
        print("Hint: This endpoint requires a CoinGecko Pro API Key configured in your agent.")

# asyncio.run(fetch_token_details()) # Example of how to run
```

#### 6. get\_latest\_pools

* Description: Fetches the most recently created liquidity pools on the Solana network. This is useful for agents looking for new trading opportunities as soon as they arise.
* Endpoint: Uses CoinGecko's Pro API endpoint /onchain/networks/solana/new\_pools.

**Method Signature:**

```python
async def get_latest_pools(agent: SolanaAgentKit) -> dict:
```

**Parameters:**

* agent (SolanaAgentKit): Required. The initialized agent instance with a CoinGecko Pro API key configured.
* Returns:
  * A dict containing the latest pools data, typically under a data key, which is a list of pool objects similar in structure to trending pools.

Example:

```python
import asyncio
from agentipy.agent import SolanaAgentKit
from agentipy.tools.use_coingecko import CoingeckoManager
# Assuming 'agent' is initialized with a PRO CoinGecko key

async def fetch_latest_pools():
    try:
        print("Fetching the latest Solana pools...")
        latest_pools = await CoingeckoManager.get_latest_pools(agent)
        print(f"Found {len(latest_pools.get('data', []))} latest pools:")
        for pool in latest_pools.get('data', [])[:5]: # Print data for the first 5
            base_token = pool.get('base_token', {})
            network = pool.get('network', {})
            print(f"- {base_token.get('symbol', 'N/A')} Pool on {network.get('name', 'N/A')}: Address {pool.get('address', 'N/A')}")
    except Exception as e:
        print(f"Error fetching latest pools: {e}")
        print("Hint: This endpoint requires a CoinGecko Pro API Key configured in your agent.")

# asyncio.run(fetch_latest_pools()) 
```


# Use Cybers

The `Use Cybers` tool, part of AgentiPy, allows users to interact with the Cybers API (`https://api.cybers.app/v1`). It provides functionalities to authenticate a Solana wallet and create new coins (tokens) on the Cybers platform.

## Functionality

This tool is implemented in the `CybersManager` class.

### Key Methods:

* `_sign_message(keypair: Keypair, message: str) -> str`:
  * (Internal static method) Signs a UTF-8 encoded `message` using the provided Solana `keypair`.
  * Returns a base58-encoded signature.
* `authenticate_wallet(agent: SolanaAgentKit) -> Optional[str]`:
  * (Static method) Authenticates the agent's wallet with the Cybers API.
  * It signs a predefined message ("Sign in to Cyber") using the agent's wallet.
  * Sends the wallet address, signature, and message to the Cybers `/auth/verify-signature` endpoint.
  * Returns a JWT token as a string if authentication is successful, otherwise `None` or raises an exception.
* `create_coin(agent: SolanaAgentKit, name: str, symbol: str, image_path: str, tweet_author_id: str, tweet_author_username: str) -> dict`:
  * (Static method) Creates a new coin on the Cybers platform.
  * First, it calls `authenticate_wallet` to get a JWT token.
  * It then prepares a multipart form data payload including the token `name` (max 64 chars), `symbol` (max 10 chars), `description` (auto-generated), `personality`, `instruction`, `knowledge`, social links (auto-generated from symbol), `creatorTwitterUserId`, `creatorTwitterUsername`, and an image file read from `image_path`.
  * Sends this data to the Cybers `/coin/create` endpoint with the JWT token for authorization.
  * Returns a dictionary with the API response, which should include the mint address if successful.

##

**Important Considerations:**

* **External API:** This tool relies heavily on the external Cybers API. Its functionality is subject to the API's availability, terms of service, and potential costs.
* **Authentication:** Wallet authentication is required, involving signing a message. The JWT token obtained is used for subsequent API calls like coin creation.
* **Image Handling:** The `create_coin` method requires a path to an image file, which it reads and uploads.
* **On-Chain Action:** Creating a coin results in a new token being minted on the Solana blockchain, which is an on-chain transaction likely initiated by the Cybers backend after API validation.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_cybers.py>


# Use deBridge

The `Use deBridge` tool, part of AgentiPy, enables users to perform cross-chain swaps and interact with the deBridge protocol. It allows for creating and executing transactions that bridge assets between different blockchains supported by deBridge, using their Liquidity Network API.

## Functionality

This tool is implemented in the `DeBridgeManager` class.

### Key Methods:

* `create_debridge_transaction(src_chain_id: str, src_chain_token_in: str, src_chain_token_in_amount: str, dst_chain_id: str, dst_chain_token_out: str, dst_chain_token_out_recipient: str, src_chain_order_authority_address: str, dst_chain_order_authority_address: str, ... ) -> dict`:
  * (Static method) Constructs the parameters for a deBridge cross-chain transaction.
  * Requires source and destination chain IDs, token addresses (in and out), amounts, recipient address, and order authority addresses on both chains.
  * Optional parameters include affiliate fees and whether to prepend operating expenses.
  * Makes a GET request to the deBridge API (`https://api.dln.trade/v1.0/dln/create-tx`) to get the transaction details.
  * Returns a dictionary containing the API response, which includes the serialized transaction data if successful.
* `execute_debridge_transaction(agent: SolanaAgentKit, transaction_data: dict) -> str`:
  * (Static async method) Takes the `transaction_data` (typically from `create_debridge_transaction`) and an `agent` (SolanaAgentKit).
  * This method is specifically for executing transactions where the source chain is Solana.
  * Decodes the base64 serialized transaction from `transaction_data["data"]`.
  * Signs the `VersionedTransaction` with the agent's wallet.
  * Sends and confirms the transaction on the Solana network.
  * Returns the Solana transaction signature (ID) as a string.
* `check_transaction_status(tx_hash: str) -> list[dict]`:
  * (Static async method) Checks the status of a deBridge transaction using its source transaction `tx_hash`.
  * First, it queries the deBridge API to get order IDs associated with the `tx_hash`.
  * Then, for each order ID, it queries the status.
  * Returns a list of status dictionaries for each order, including a link to view the order on the deBridge app.

##

**Important Considerations:**

* **External API:** This tool relies on the deBridge API. Its functionality is subject to the API's availability, terms, supported chains/tokens, and potential fees.
* **On-Chain Transactions:** Executing a deBridge transaction involves actual on-chain transactions on the source blockchain (e.g., Solana), which will spend tokens and incur gas fees.
* **Cross-Chain Complexity:** Bridging assets across chains has inherent risks, including smart contract vulnerabilities on either chain or the bridge protocol itself, and potential delays in finality.
* **Parameter Accuracy:** Correct chain IDs, token contract addresses, amounts, and recipient addresses are crucial for the transaction to succeed and for funds to arrive at the intended destination. Always verify these from official deBridge documentation or interfaces.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_debridge.py>


# Use Drift Protocol

The `Use Drift Protocol` tool, part of AgentiPy, allows users to interact with the Drift Protocol, a decentralized exchange for perpetuals, spot trading, borrowing/lending, and staking on Solana. This tool communicates with an Agentipy proxy service to perform various actions on Drift.

## Functionality

This tool is implemented in the `DriftManager` class. All its methods interact with an Agentipy proxy service (`agent.base_proxy_url`), sending encrypted private keys and potentially an OpenAI API key with each request.

### Key Methods:

The `DriftManager` class offers a comprehensive suite of methods, including but not limited to:

**Account Management:**

* `create_drift_user_account(agent: SolanaAgentKit, deposit_amount: float, deposit_symbol: str)`: Creates a new Drift user account with an initial deposit.
* `deposit_to_drift_user_account(agent: SolanaAgentKit, amount: float, symbol: str, ...)`: Deposits funds into an existing Drift account.
* `withdraw_from_drift_user_account(agent: SolanaAgentKit, amount: float, symbol: str, ...)`: Withdraws funds from a Drift account.
* `check_if_drift_account_exists(agent: SolanaAgentKit)`: Checks if the agent's wallet has a Drift account.
* `drift_user_account_info(agent: SolanaAgentKit)`: Fetches information about the user's Drift account.

**Trading:**

* `trade_using_drift_perp_account(agent: SolanaAgentKit, amount: float, symbol: str, action: str, trade_type: str, price: Optional[float] = None)`: Places a perpetual trade (long/short, market/limit).
* `drift_swap_spot_token(agent: SolanaAgentKit, from_symbol: str, to_symbol: str, ...)`: Swaps spot tokens.
* `get_drift_entry_quote_of_perp_trade(agent: SolanaAgentKit, amount: float, symbol: str, action: str)`: Gets a quote for a perpetual trade.

**Market & Protocol Info:**

* `get_available_drift_markets(agent: SolanaAgentKit)`: Retrieves available markets on Drift.
* `get_drift_perp_market_funding_rate(agent: SolanaAgentKit, symbol: str, ...)`: Gets the funding rate for a perpetual market.
* `get_drift_lend_borrow_apy(agent: SolanaAgentKit, symbol: str)`: Gets lending/borrowing APYs for a spot market.

**Staking & Insurance Fund:**

* `stake_to_drift_insurance_fund(agent: SolanaAgentKit, amount: float, symbol: str)`: Stakes tokens to Drift's insurance fund.
* `request_unstake_from_drift_insurance_fund(...)` and `unstake_from_drift_insurance_fund(...)`.

**Drift Vaults (Advanced):**

* `create_drift_vault(agent: SolanaAgentKit, name: str, ...)`: Creates a new Drift vault.
* `update_drift_vault_delegate(...)`, `update_drift_vault(...)`, `get_drift_vault_info(...)`.
* `deposit_into_drift_vault(...)`, `request_withdrawal_from_drift_vault(...)`, `withdraw_from_drift_vault(...)`.
* `derive_drift_vault_address(...)`.
* `trade_using_delegated_drift_vault(...)`: Executes trades using a delegated vault.

Each method typically returns a dictionary indicating success/failure and transaction details or requested data.

##

**Important Considerations:**

* **Proxy Service:** This tool relies on an Agentipy proxy service. The availability, authentication, and terms of use for this proxy are critical.
* **Financial Risk:** Trading perpetual contracts and interacting with DeFi protocols like Drift involves substantial financial risk, including market volatility, leverage risks (liquidation), and smart contract vulnerabilities. Use with extreme caution.
* **API Keys & Configuration:** An OpenAI API key is passed to the proxy; its role should be clear from proxy documentation. Correct RPC URL, `base_proxy_url`, and `api_version` in the `SolanaAgentKit` are essential.
* **On-Chain Costs:** All actions that modify state (creating accounts, depositing, trading, staking) are on-chain transactions that incur SOL fees and require the necessary collateral or tokens.
* **Drift Protocol Knowledge:** Users should have a good understanding of how Drift Protocol works, including its market structure, account system, margin requirements, and fee schedules, before using these tools with real assets.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_drift.py>


# Use Elfa AI

The `Use Elfa AI` tool, part of AgentiPy, allows users to leverage the Elfa AI platform (`https://api.elfa.ai`) for insights related to the Solana blockchain and crypto markets. It can fetch data such as token mentions, trending tokens, and Twitter account statistics. This tool requires an Elfa AI API key.

## Functionality

This tool is implemented in the `ElfaAiManager` class and interacts directly with the Elfa AI API using `aiohttp`. The API key is passed via headers, which are prepared by `agentipy.utils.elfa_ai.get_headers(agent)`.

### Key Methods:

* `ping_elfa_ai_api(agent: SolanaAgentKit) -> dict`: Pings the Elfa AI API to check connectivity.
* `get_elfa_ai_api_key_status(agent: SolanaAgentKit) -> dict`: Checks the status of the provided Elfa AI API key.
* `get_smart_mentions(agent: SolanaAgentKit, limit: int = 100, offset: int = 0) -> dict`: Retrieves "smart mentions" (curated or important mentions) from Elfa AI.
* `get_top_mentions_by_ticker(agent: SolanaAgentKit, ticker: str, time_window: str = "1h", page: int = 1, page_size: int = 10, include_account_details: bool = False) -> dict`: Fetches top mentions for a specific token `ticker` within a `time_window`.
* `search_mentions_by_keywords(agent: SolanaAgentKit, keywords: str, from_timestamp: int, to_timestamp: int, limit: int = 20, cursor: str = None) -> dict`: Searches for mentions based on `keywords` within a given timestamp range.
* `get_trending_tokens_using_elfa_ai(agent: SolanaAgentKit, time_window: str = "24h", page: int = 1, page_size: int = 50, min_mentions: int = 5) -> dict`: Gets a list of trending tokens based on mention activity.
* `get_smart_twitter_account_stats(agent: SolanaAgentKit, username: str) -> dict`: Retrieves statistics for a given Twitter `username`.

##

**Important Considerations:**

* **API Key:** An Elfa AI API key is mandatory for using this tool. It should be set in the `SolanaAgentKit` instance as `agent.elfa_ai_api_key`.
* **External API:** The tool's functionality is entirely dependent on the Elfa AI API. Check Elfa AI's documentation for rate limits, data structure details, and terms of service.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_elfa_ai.py>


# Use Flash

The `Use Flash` tool, part of AgentiPy, provides functionalities for opening and closing trades on what appears to be a specific trading platform integrated via an Agentipy proxy service. The "Flash" name suggests these might be leveraged or quick trades.

## Functionality

This tool is implemented in the `FlashTradeManager` class. It interacts with an Agentipy proxy service (`agent.base_proxy_url`) to perform trading operations. The agent's private key is encrypted and sent to this proxy, and an OpenAI API key (`agent.openai_api_key`) also seems to be part of the payload sent to the proxy.

### Key Methods:

* `flash_open_trade(agent: SolanaAgentKit, token: str, side: str, collateral_usd: float, leverage: float) -> Optional[Dict[str, Any]]`:
  * Opens a trade on the Flash platform.
  * Parameters:
    * `agent`: The `SolanaAgentKit` instance.
    * `token`: The trading token (e.g., "SOL", "BTC" - specific format depends on the proxy/Flash platform).
    * `side`: The trade direction, likely "buy" (long) or "sell" (short).
    * `collateral_usd`: The collateral amount in USD.
    * `leverage`: The leverage multiplier for the trade.
  * Returns a dictionary with the transaction details from the proxy or an error.
* `flash_close_trade(agent: SolanaAgentKit, token: str, side: str) -> Optional[Dict[str, Any]]`:
  * Closes an existing trade on the Flash platform.
  * Parameters:
    * `agent`: The `SolanaAgentKit` instance.
    * `token`: The trading token of the position to close.
    * `side`: The side of the position to close (likely corresponding to the opening side).
  * Returns a dictionary with the transaction details from the proxy or an error.

##

**Important Considerations:**

* **Proxy Service:** This tool relies on an Agentipy proxy service. The availability, authentication (including the role of the OpenAI API key), and terms of use for this proxy are critical.
* **Financial Risk:** Leveraged trading, as suggested by the parameters, is extremely risky and can lead to rapid and significant financial losses. Users must understand these risks thoroughly.
* **On-Chain Actions:** Trades executed via this tool are likely on-chain transactions on Solana, incurring fees and requiring sufficient collateral in the user's wallet or trading account.
* **Platform Specifics:** The exact behavior, supported tokens, and trading rules are dictated by the underlying "Flash" platform integrated through the proxy.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_flash.py>


# Use FluxBeam

The `Use FluxBeam` tool, part of AgentiPy, allows users to interact with the FluxBeam decentralized exchange on the Solana blockchain. Specifically, this tool provides functionality to create new liquidity pools on FluxBeam.

## Functionality

This tool is implemented in the `FluxBeamManager` class. It interacts directly with the FluxBeam API (`https://api.fluxbeam.xyz`) to request a transaction for creating a pool, and then signs and sends this transaction to the Solana network using the agent's wallet.

### Key Methods:

* `fluxbeam_create_pool(agent: SolanaAgentKit, token_a: Pubkey, token_a_amount: float, token_b: Pubkey, token_b_amount: float) -> str`:
  * Creates a new liquidity pool on FluxBeam with the specified assets.
  * Parameters:
    * `agent`: The `SolanaAgentKit` instance, providing the wallet and connection.
    * `token_a`: `solders.pubkey.Pubkey` of the first token in the pool.
    * `token_a_amount`: The initial amount of token A to deposit (in UI units, e.g., 10.5 tokens).
    * `token_b`: `solders.pubkey.Pubkey` of the second token in the pool.
    * `token_b_amount`: The initial amount of token B to deposit (in UI units).
  * It fetches the decimals for `token_a` and `token_b` (handles SOL as native with 9 decimals).
  * Scales the input amounts to their respective lamport/smallest unit values.
  * Makes a POST request to the FluxBeam API (`/token_pools`) with the payer address (agent's wallet), token mints, and scaled amounts.
  * Receives a serialized transaction from the FluxBeam API.
  * Signs this transaction with the agent's wallet.
  * Sends and confirms the transaction on the Solana network.
  * Returns the transaction signature as a string.

##

**Important Considerations:**

* **Direct API Interaction:** This tool interacts directly with the FluxBeam API to get the transaction details and then submits it to the Solana blockchain. It does not appear to use the Agentipy proxy service.
* **On-Chain Action:** Creating a liquidity pool is a significant on-chain transaction. It will lock up the specified amounts of `token_a` and `token_b` from the agent's wallet into the new pool.
* **Financial Risks:** Providing liquidity has risks, such as impermanent loss. Users should understand these risks before creating pools.
* **Token Decimals:** The tool correctly handles fetching token decimals to convert UI amounts to the required lamport/smallest unit amounts for the transaction.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_fluxbeam.py>


# Use Helius

The `Use Helius` tool, part of AgentiPy, provides functionalities for interacting with the Helius APIs on Solana. Helius offers a suite of developer tools for reading parsed transaction data, NFT events, balances, mintlists, and managing webhooks for real-time notifications. This tool requires a Helius API key.

## Functionality

This tool is implemented in the `HeliusManager` class. All methods are static and make direct requests to Helius API endpoints. The Helius API key and RPC URL are sourced from the `SolanaAgentKit` instance (`agent.helius_api_key`, `agent.helius_rpc_url`).

### Key Methods:

* `get_balances(agent: SolanaAgentKit, address: str)`: Fetches native SOL and SPL token balances for a given `address`.
* `get_address_name(agent: SolanaAgentKit, address: str)`: Retrieves known names associated with an `address` (e.g., from domain services or exchanges).
* `get_nft_events(agent: SolanaAgentKit, accounts: List[str], types: List[str] = None, ...)`: Queries NFT event history for specified `accounts`, filterable by event `types`, `sources`, slot/time ranges, and collection details. Supports pagination.
* `get_mintlists(agent: SolanaAgentKit, first_verified_creators: List[str], ...)`: Retrieves mintlists based on first verified creators or verified collection addresses. Supports pagination.
* `get_nft_fingerprint(agent: SolanaAgentKit, mints: List[str])`: Gets the Helius fingerprint for a list of NFT `mints`.
* `get_active_listings(agent: SolanaAgentKit, first_verified_creators: List[str], ...)`: Fetches active NFT listings from various marketplaces, filterable by creators or collections.
* `get_nft_metadata(agent: SolanaAgentKit, mint_accounts: List[str])`: Retrieves metadata for a list of SPL token/NFT `mint_accounts`.
* `get_raw_transactions(agent: SolanaAgentKit, accounts: List[str], ...)`: Fetches raw (unparsed) transaction history for specified `accounts`.
* `get_parsed_transactions(agent: SolanaAgentKit, transactions: List[str], commitment: str = None)`: Fetches and parses specific transactions by their signatures.
* `get_parsed_transaction_history(agent: SolanaAgentKit, address: str, ...)`: Retrieves parsed transaction history for a given `address`, filterable by various criteria.
* `create_webhook(agent: SolanaAgentKit, webhook_url: str, transaction_types: list, account_addresses: list, webhook_type: str, ...)`: Creates a new Helius webhook to receive real-time notifications.
* `get_all_webhooks(agent: SolanaAgentKit)`: Lists all existing webhooks for the API key.
* `get_webhook(agent: SolanaAgentKit, webhook_id: str)`: Retrieves details for a specific `webhook_id`.
* `edit_webhook(agent: SolanaAgentKit, webhook_id: str, ...)`: Modifies an existing webhook.
* `delete_webhook(agent: SolanaAgentKit, webhook_id: str)`: Deletes a webhook.

(Helper functions `_make_get_request`, `_make_post_request`, etc. are used internally to interact with the Helius API.)

##

**Important Considerations:**

* **API Key:** A Helius API key is required and must be configured in `SolanaAgentKit` as `agent.helius_api_key`. The Helius RPC URL must also be set as `agent.helius_rpc_url`.
* **Direct API Interaction:** This tool interacts directly with Helius APIs. It does not use the Agentipy proxy service.
* **Rate Limits:** Be mindful of Helius API rate limits associated with your API key tier.
* **Data Richness:** Helius provides parsed and enriched Solana data, which can be very detailed and useful for analytics, event tracking, and more.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_helius.py>


# Use Jito

The `Use Jito` tool, part of AgentiPy, allows users to interact with Jito Labs' services on Solana. Jito is known for its MEV (Maximal Extractable Value) infrastructure, including block engines and relayer services, which allow for sending transaction bundles and accessing Jito-specific endpoints. This tool appears to wrap Jito's JSON-RPC API.

## Functionality

This tool is implemented in the `JitoManager` class. It uses a helper function `__send_request` (from `agentipy.utils.jito`) to make requests to Jito's API endpoints. The agent's Jito UUID (`agent.jito_uuid`) can be used for certain requests if provided.

### Key Methods:

* `get_tip_accounts(agent: SolanaAgentKit)`: Fetches a list of Jito tip accounts that can be used for sending transactions/bundles.
* `get_random_tip_account()`: (Static method) Calls `get_tip_accounts()` and returns a randomly selected tip account from the list.
* `get_bundle_statuses(agent: SolanaAgentKit, bundle_uuids)`: Retrieves the status of one or more transaction bundles using their UUIDs.
* `send_bundle(agent: SolanaAgentKit, params=None)`: Sends a pre-constructed bundle of transactions to Jito's block engine. The `params` argument should contain the serialized transactions and other necessary bundle information.
* `get_inflight_bundle_statuses(agent: SolanaAgentKit, bundle_uuids)`: Gets the status of bundles that are currently in-flight or being processed.
* `send_txn(agent: SolanaAgentKit, params=None, bundleOnly=False)`: Sends a single transaction, potentially to be included in a Jito bundle. The `params` would contain the serialized transaction. The `bundleOnly` flag might indicate if it should only be processed as part of a bundle.

##

**Important Considerations:**

* **Direct API Interaction:** This tool interacts directly with Jito's API endpoints. It does not appear to use the Agentipy proxy service.
* **Jito UUID:** Some Jito API methods might behave differently or provide enhanced features if a `jito_uuid` is provided via the `SolanaAgentKit`.
* **Bundle Complexity:** Sending bundles (`send_bundle`) is an advanced operation. It requires creating, signing, and serializing multiple transactions correctly. Bundles are often used for MEV extraction or ensuring atomic execution of several operations.
* **On-Chain Actions:** Sending bundles or transactions via `send_txn` results in on-chain activity and will incur SOL fees and state changes.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_jito.py>


# Use Light Protocol

The `Use Light Protocol` tool, part of AgentiPy, allows users to interact with Light Protocol on Solana, focusing on sending compressed airdrops. Light Protocol is known for its solutions enabling private and cost-efficient transactions, including shielded transfers and compressed NFTs/tokens. This tool appears to use an Agentipy proxy service for its operations.

## Functionality

This tool is implemented in the `LightProtocolManager` class. It interacts with an Agentipy proxy service (`agent.base_proxy_url`) to perform actions related to Light Protocol. The agent's private key is encrypted and sent to this proxy, and an OpenAI API key (`agent.openai_api_key`) also seems to be part of the payload.

### Key Methods:

* `send_compressed_airdrop(agent: SolanaAgentKit, mint_address: str, amount: float, decimals: int, recipients: List[str], priority_fee_in_lamports: int, should_log: Optional[bool] = False) -> Optional[Dict[str, Any]]`:
  * Sends a compressed airdrop of an SPL token to multiple `recipients`.
  * Parameters:
    * `agent`: The `SolanaAgentKit` instance.
    * `mint_address`: The mint address of the token to be airdropped.
    * `amount`: The amount of tokens to send to each recipient (in UI units, e.g., 10.5 tokens).
    * `decimals`: The number of decimals for the token.
    * `recipients`: A list of recipient wallet addresses (strings).
    * `priority_fee_in_lamports`: The priority fee to be paid for the transaction(s) in lamports.
    * `should_log`: Optional boolean to indicate if the transaction should be logged by the proxy service.
  * Returns a dictionary containing the transaction signatures (likely one or more if the airdrop is batched) or error details from the proxy.

**Note:** While the class is named `LightProtocolManager`, the provided script only contains the `send_compressed_airdrop` method. Other Light Protocol functionalities like shielding SOL/SPLs, private transfers, or unshielding are not exposed in this particular script.

##

**Important Considerations:**

* **Proxy Service:** This tool relies on an Agentipy proxy service for its operations. The functionality is dependent on this proxy's correct implementation and interaction with Light Protocol.
* **On-Chain Action:** Sending an airdrop is an on-chain action that will transfer tokens from the sender's (agent's) wallet and incur SOL transaction fees.
* **Compressed Airdrops:** This specific function is for "compressed" airdrops, which usually means it's optimized for sending tokens to many recipients efficiently, possibly using Light Protocol's specific mechanisms for compression or privacy.
* **Token Ownership & Fees:** The agent's wallet must own a sufficient amount of the specified SPL token for the airdrop and enough SOL to cover transaction fees, including any priority fees.
* **API Keys:** The use of `agent.openai_api_key` in the payload to the proxy suggests it might be used for some purpose by the proxy service.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_lightprotocol.py>


# Use Lulo

The `Use Lulo` tool, part of AgentiPy, allows users to interact with the Lulo Finance lending and borrowing protocol on Solana. It provides methods to lend assets (specifically USDC in one method, and any SPL token in another) to earn yield, and to withdraw previously lent assets. This tool interacts directly with the Lulo API (which seems to be also referred to as Flexlend).

## Functionality

This tool is implemented in the `LuloManager` class.

### Key Methods:

* `lend_asset(agent: SolanaAgentKit, amount: float) -> str`:
  * Lends a specified `amount` of USDC to Lulo. This method seems to use a Lulo Blink (Solana Action) URL: `https://blink.lulo.fi/actions`.
  * It constructs a payload with the agent's wallet address and makes a POST request.
  * The response contains a serialized transaction which is then signed by the agent's wallet and sent to the Solana network.
  * Returns the transaction signature.
* `lulo_lend(agent: SolanaAgentKit, mint_address: Pubkey, amount: float) -> str`:
  * Lends a specified `amount` of an SPL token (identified by `mint_address`) to Lulo.
  * This method uses the Flexlend API endpoint (`https://api.flexlend.fi/api/v1/deposit`) and requires a Flexlend API key (`agent.FLEXLEND_API_KEY` or `agent.flexland_api_key` - note the typo in the script for the latter).
  * The payload includes the owner's address, mint address, and deposit amount.
  * Similar to `lend_asset`, it processes the transaction returned by the API.
  * Returns the transaction signature.
* `lulo_withdraw(agent: SolanaAgentKit, mint_address: Pubkey, amount: float) -> str`:
  * Withdraws a specified `amount` of a previously lent SPL token (identified by `mint_address`) from Lulo.
  * Uses the Flexlend API endpoint (`https://api.flexlend.fi/api/v1/withdraw`) and requires a Flexlend API key.
  * Parameters and transaction handling are similar to `lulo_lend`.
  * Returns the transaction signature.

##

**Important Considerations:**

* **Direct API Interaction & On-Chain:** This tool interacts directly with Lulo/Flexlend APIs to get transaction details, which are then signed by the agent's wallet and submitted to the Solana blockchain. These are on-chain financial transactions.
* **API Key:** The `lulo_lend` and `lulo_withdraw` methods require a Flexlend API key (`agent.FLEXLEND_API_KEY` or `agent.flexland_api_key`). The `lend_asset` method for USDC might use a more open "blink" endpoint that may not require a user-specific API key.
* **Financial Risks:** Lending assets to DeFi protocols involves risks, including smart contract vulnerabilities and impermanent loss (if the protocol also involves liquidity provision aspects).
* **Token Support:** While `lend_asset` is specific to USDC, `lulo_lend` and `lulo_withdraw` can be used for other SPL tokens supported by Lulo/Flexlend.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_lulo.py>


# Use Manifest

The `Use Manifest` tool, part of AgentiPy, allows users to interact with the Manifest protocol on Solana. Manifest appears to be a decentralized exchange or order book protocol. This tool provides functionalities to create markets, place limit orders (individually or in batches), cancel orders, and withdraw assets from markets. These operations are routed through an Agentipy proxy service.

## Functionality

This tool is implemented in the `ManifestManager` class. All its methods interact with an Agentipy proxy service (`agent.base_proxy_url`), sending encrypted private keys and an OpenAI API key with each request.

### Key Methods:

* `create_market(agent: SolanaAgentKit, base_mint: str, quote_mint: str) -> Optional[Dict[str, Any]]`:
  * Creates a new trading market on Manifest for a pair of assets.
  * Parameters: `base_mint` (mint address of the base asset) and `quote_mint` (mint address of the quote asset).
  * Returns a dictionary with the transaction details from the proxy or an error.
* `place_limit_order(agent: SolanaAgentKit, market_id: str, quantity: float, side: str, price: float) -> Optional[Dict[str, Any]]`:
  * Places a single limit order on a specified Manifest `market_id`.
  * Parameters: `quantity` (amount to trade), `side` ("buy" or "sell"), and `price`.
  * Returns a dictionary with the transaction details or an error.
* `place_batch_orders(agent: SolanaAgentKit, market_id: str, orders: List[Dict[str, Any]]) -> Optional[Dict[str, Any]]`:
  * Places multiple limit orders in a batch on a specified `market_id`.
  * `orders` is a list of dictionaries, each specifying `quantity`, `side`, and `price`.
  * Returns a dictionary with the transaction details or an error.
* `cancel_all_orders(agent: SolanaAgentKit, market_id: str) -> Optional[Dict[str, Any]]`:
  * Cancels all open orders for the agent's wallet on a specified `market_id`.
  * Returns a dictionary with the transaction details or an error.
* `withdraw_all(agent: SolanaAgentKit, market_id: str) -> Optional[Dict[str, Any]]`:
  * Withdraws all settled assets for the agent's wallet from a specified `market_id`.
  * Returns a dictionary with the transaction details or an error.

##

**Important Considerations:**

* **Proxy Service:** This tool relies on an Agentipy proxy service. The availability, authentication (including the role of the OpenAI API key), and terms of use for this proxy are critical.
* **On-Chain Financial Transactions:** Creating markets, placing orders, and withdrawing assets are all on-chain actions that involve spending SOL for fees and interacting with valuable tokens. Use with caution, especially on Mainnet.
* **Manifest Protocol:** Understanding the specific rules, fee structures, and market identifiers of the Manifest protocol is essential for correct usage.
* **Market ID:** Operations like placing orders require a `market_id`. This ID is likely obtained when a market is created or by querying existing markets on Manifest.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_manifest.py>


# Use Metaplex

The `Use Metaplex` tool, part of AgentiPy, allows users to interact with the Metaplex protocol on Solana for creating and managing Non-Fungible Tokens (NFTs) and collections. It provides functionalities to deploy new NFT collections, mint NFTs (standard Metaplex and Metaplex Core), and retrieve asset information. These operations are routed through an Agentipy proxy service.

## Functionality

This tool is implemented in the `DeployCollectionManager` class (though it contains methods beyond just deploying collections, suggesting the class name might be historical or a misnomer for its broader Metaplex functionalities). All methods interact with an Agentipy proxy service (`agent.base_proxy_url`), sending encrypted private keys and an OpenAI API key with each request.

### Key Methods:

* `deploy_collection(agent: SolanaAgentKit, name: str, uri: str, royalty_basis_points: int, creator_address: str) -> Optional[Dict[str, Any]]`:
  * Deploys a new Metaplex NFT collection.
  * Parameters: `name` of the collection, metadata `uri` (pointing to JSON with collection details), `royalty_basis_points` (e.g., 500 for 5%), and the `creator_address`.
  * Returns a dictionary with the transaction details from the proxy or an error.
* `mint_metaplex_core_nft(agent: SolanaAgentKit, collectionMint: str, name: str, uri: str, sellerFeeBasisPoints: Optional[int] = None, address: Optional[str] = None, share: Optional[str] = None, recipient: Optional[str] = None) -> Optional[Dict[str, Any]]`:
  * Mints an NFT using the newer Metaplex Core standard.
  * Parameters: `collectionMint` (address of the Core collection), `name` of the NFT, metadata `uri`.
  * Optional: `sellerFeeBasisPoints` (royalties), creator `address` and `share`, and `recipient` of the NFT (defaults to agent's wallet).
  * Returns a dictionary with the transaction details or an error.
* `get_metaplex_asset(agent: SolanaAgentKit, assetId: str) -> Optional[Dict[str, Any]]`:
  * Fetches detailed information about a specific Metaplex asset (NFT) using its `assetId` (mint address).
  * Returns a dictionary with asset details or an error.
* `get_metaplex_assets_by_creator(agent: SolanaAgentKit, creator: str, onlyVerified: bool = False, ... ) -> Optional[Dict[str, Any]]`:
  * Fetches assets created by a specific `creator` address. Supports pagination and sorting.
  * `onlyVerified` flag filters for assets from verified creators.
  * Returns a dictionary with the list of assets or an error.
* `get_metaplex_assets_by_authority(agent: SolanaAgentKit, authority: str, ... ) -> Optional[Dict[str, Any]]`:
  * Fetches assets where the specified `authority` address is the update authority. Supports pagination and sorting.
  * Returns a dictionary with the list of assets or an error.

##

**Important Considerations:**

* **Proxy Service:** This tool relies on an Agentipy proxy service. The availability, authentication (including the role of the OpenAI API key), and terms of use for this proxy are critical.
* **On-Chain Costs:** Deploying collections and minting NFTs are on-chain transactions that incur SOL fees. Metadata often needs to be stored on decentralized storage like Arweave, which also has costs.
* **Metaplex Standards:** Metaplex has different NFT standards (e.g., original Token Metadata, Core). This tool seems to support both deploying standard collections and minting Core NFTs. Ensure you use the correct methods for your desired standard and have valid collection addresses if minting into an existing one.
* **Metadata URIs:** Valid URIs pointing to JSON metadata files (conforming to Metaplex standards) are crucial for both collections and individual NFTs.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_metaplex.py>


# Use MoonShot

The `Use MoonShot` tool, part of AgentiPy, allows users to interact with the Moonshot protocol on Solana. Moonshot appears to be a decentralized exchange (DEX) that uses a bonding curve mechanism. This tool provides functionalities to buy and sell tokens against a collateral asset (likely SOL) on this curve.

## Functionality

This tool is implemented in the `MoonshotManager` class. It interacts directly with the Moonshot on-chain program (`MOONSHOT_PROGRAM`) by constructing and sending Solana transactions.

### Key Methods:

* `buy(agent: SolanaAgentKit, mint_str: str, collateral_amount: float = 0.01, slippage_bps: int = 500)`:
  * Buys tokens from a Moonshot curve.
  * Parameters:
    * `agent`: The `SolanaAgentKit` instance.
    * `mint_str`: The mint address (string) of the token to buy.
    * `collateral_amount`: The amount of collateral (SOL) to spend (default 0.01 SOL).
    * `slippage_bps`: Slippage tolerance in basis points (default 500 = 5%).
  * Calculates the expected token amount using `get_tokens_by_collateral_amount`.
  * Constructs a transaction with instructions to set compute unit price/limit and the swap instruction for the Moonshot program.
  * Handles creation of the Associated Token Account (ATA) for the user if it doesn't exist.
  * Signs and sends the transaction.
* `sell(agent: SolanaAgentKit, mint_str: str, token_balance: float = None, slippage_bps: int = 500)`:
  * Sells tokens to a Moonshot curve.
  * Parameters:
    * `agent`: The `SolanaAgentKit` instance.
    * `mint_str`: The mint address (string) of the token to sell.
    * `token_balance`: The amount of tokens to sell. If `None`, it attempts to fetch the full balance of the token for the agent's wallet.
    * `slippage_bps`: Slippage tolerance in basis points (default 500 = 5%).
  * Calculates the expected collateral amount to receive using `get_collateral_amount_by_tokens`.
  * Constructs and sends the transaction similarly to the `buy` method.

Constants used (from `agentipy.utils.moonshot.constants`):

* `MOONSHOT_PROGRAM`: The on-chain program ID for Moonshot.
* `LAMPORTS_PER_SOL`, `DEX_FEE`, `HELIO_FEE`, `CONFIG_ACCOUNT`, `TOKEN_PROGRAM`, `ASSOC_TOKEN_ACC_PROG`, `SYSTEM_PROGRAM`.
* `UNIT_PRICE`, `UNIT_BUDGET`: Compute unit settings.

##

**Important Considerations:**

* **Direct On-Chain Interaction:** This tool interacts directly with the Solana blockchain by sending transactions to the Moonshot program. It does not use a proxy.
* **Financial Risk:** Trading on DEXs like Moonshot involves financial risks, including price volatility, slippage, and potential smart contract vulnerabilities. Curve-based DEXs can have unique price dynamics.
* **Token Mints:** You need the correct mint address of the token traded on Moonshot.
* **Associated Token Accounts:** The tool handles the creation of Associated Token Accounts (ATAs) if they don't exist for the agent's wallet.
* **Transaction Confirmation:** The script includes a `confirm_txn` utility (not shown in the snippet but present in the file) which should be used to ensure transactions are finalized. The example above simplifies this.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_moonshot.py>


# Use OpenBook

The `Use OpenBook` tool, part of AgentiPy, allows users to interact with the OpenBook decentralized exchange protocol on Solana. The primary function exposed in this manager is the creation of new trading markets. This operation is routed through an Agentipy proxy service. (Note: The filename is `use_openpook.py`, which is likely a typo for OpenBook).

## Functionality

This tool is implemented in the `OpenBookManager` class. It interacts with an Agentipy proxy service (`agent.base_proxy_url`) to perform actions related to OpenBook. The agent's private key is encrypted and sent to this proxy, and an OpenAI API key (`agent.openai_api_key`) also seems to be part of the payload.

### Key Methods:

* `create_market(agent: SolanaAgentKit, base_mint: str, quote_mint: str, lot_size: Optional[float] = 1, tick_size: Optional[float] = 0.01) -> Optional[Dict[str, Any]]`:
  * Creates a new market on the OpenBook DEX.
  * Parameters:
    * `agent`: The `SolanaAgentKit` instance.
    * `base_mint`: The mint address (string) of the base asset for the market (e.g., the token being traded).
    * `quote_mint`: The mint address (string) of the quote asset (e.g., USDC, SOL).
    * `lot_size`: (Optional) The minimum order quantity for the base asset, also known as base lot size (default is 1).
    * `tick_size`: (Optional) The minimum price increment for the market, also known as quote tick size (default is 0.01).
  * Sends a request to the Agentipy proxy endpoint (`/openbook-create-market`).
  * Returns a dictionary with the transaction details from the proxy or an error. The response likely contains the new market ID and transaction signatures.

##

**Important Considerations:**

* **Proxy Service:** This tool relies on an Agentipy proxy service. The availability, authentication (including the role of the OpenAI API key), and terms of use for this proxy are critical.
* **On-Chain Action & Costs:** Creating an OpenBook market is a complex on-chain operation that involves multiple transactions and will incur significant SOL fees (for rent of accounts like event queue, request queue, order books).
* **Market Parameters:** Correctly setting `lot_size` and `tick_size` is crucial for a functional market and depends on the expected price and trading characteristics of the token pair. Incorrect values can lead to an unusable market.
* **OpenBook Program:** Users should be familiar with the OpenBook DEX program and its requirements for market creation.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_openpook.py> (Note the typo in the filename in the repository).


# Use Orca

The `Use Orca` tool, part of AgentiPy, allows users to interact with the Orca decentralized exchange protocol on Solana. It provides functionalities for managing liquidity positions, specifically creating Concentrated Liquidity Market Maker (CLMM) pools, creating single-sided liquidity pools, opening centered and single-sided positions, fetching existing positions, and closing positions. These operations are routed through an Agentipy proxy service.

## Functionality

This tool is implemented in the `OrcaManager` class. All its methods interact with an Agentipy proxy service (`agent.base_proxy_url`), sending encrypted private keys and an OpenAI API key with each request.

### Key Methods:

* `create_clmm(agent: SolanaAgentKit, mint_deploy: str, mint_pair: str, initial_price: float, fee_tier: str) -> Optional[Dict[str, Any]]`:
  * Creates a new CLMM pool on Orca.
  * Parameters: `mint_deploy` (base token), `mint_pair` (quote token), `initial_price`, and `fee_tier`.
* `create_liquidity_pool(agent: SolanaAgentKit, deposit_token_amount: float, deposit_token_mint: str, other_token_mint: str, initial_price: float, max_price: float, fee_tier: str) -> Optional[Dict[str, Any]]`:
  * Creates a single-sided liquidity pool. Parameters define the deposit token, the other token in the pair, and the price range (`initial_price`, `max_price`).
* `open_centered_position(agent: SolanaAgentKit, whirlpool_address: str, price_offset_bps: int, input_token_mint: str, input_amount: float) -> Optional[Dict[str, Any]]`:
  * Opens a liquidity position centered around the current price in an existing Orca Whirlpool (`whirlpool_address`).
  * `price_offset_bps` defines the range width around the current price.
* `open_single_sided_position(agent: SolanaAgentKit, whirlpool_address: str, distance_from_current_price_bps: int, width_bps: int, input_token_mint: str, input_amount: float) -> Optional[Dict[str, Any]]`:
  * Opens a single-sided liquidity position, typically outside the current active price range.
* `fetch_positions(agent: SolanaAgentKit) -> Optional[Dict[str, Any]]`:
  * Fetches all open Orca liquidity positions for the agent's wallet.
* `close_position(agent: SolanaAgentKit, position_mint_address: str) -> Optional[Dict[str, Any]]`:
  * Closes an existing Orca liquidity position identified by its `position_mint_address`.

All methods return a dictionary with the transaction details from the proxy or an error.

##

**Important Considerations:**

* **Proxy Service:** This tool relies on an Agentipy proxy service. The availability, authentication (including the role of the OpenAI API key), and terms of use for this proxy are critical.
* **On-Chain Financial Transactions:** All methods involving creating pools, opening positions, or closing positions are significant on-chain actions that will spend/lock tokens and incur SOL fees.
* **Orca Protocol Knowledge:** Users should have a strong understanding of Orca's Whirlpools (CLMMs), including concepts like fee tiers, price ranges, liquidity provision, and impermanent loss, before using these tools with real assets.
* **Parameter Accuracy:** Correct mint addresses, whirlpool addresses, fee tiers, and price range parameters are crucial for successful and intended operations.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_orca.py>


# Use Pump.fun

The `Use Pump.fun` tool, part of AgentiPy, allows users to interact with the Pump.fun platform on Solana. This includes functionalities to buy and sell tokens listed on Pump.fun, and to get information about a token's bonding curve state and price. Pump.fun is known for facilitating the launch and trading of new tokens, often with high volatility.

## Functionality

This tool is implemented in the `PumpfunManager` class. It interacts directly with the Pump.fun on-chain program (`PUMP_PROGRAM`) by constructing and sending Solana transactions.

### Key Methods:

* `get_pump_curve_state(conn: AsyncClient, curve_address: Pubkey) -> BondingCurveState`:
  * (Static method) Fetches and parses the account data for a given `curve_address` (bonding curve) to determine its current state (e.g., virtual token reserves, virtual SOL reserves).
  * Returns a `BondingCurveState` object.
* `calculate_pump_curve_price(curve_state: BondingCurveState) -> float`:
  * (Static method) Calculates the current price of the token based on the `curve_state`.
  * Returns the price in SOL per token.
* `get_token_balance(conn: AsyncClient, associated_token_account: Pubkey) -> int`:
  * (Static method) Fetches the balance of a given `associated_token_account`.
  * Returns the balance as an integer (in the smallest unit of the token).
* `buy_token(agent: SolanaAgentKit, mint: Pubkey, bonding_curve: Pubkey, associated_bonding_curve: Pubkey, amount: float, slippage: float = 0.01, max_retries=5)`:
  * (Static async method) Buys a token from its Pump.fun bonding curve.
  * Parameters:
    * `agent`: The `SolanaAgentKit` instance.
    * `mint`: The `Pubkey` of the token to buy.
    * `bonding_curve`: The `Pubkey` of the token's bonding curve account.
    * `associated_bonding_curve`: The `Pubkey` of the curve's associated token account.
    * `amount`: The amount of SOL to spend.
    * `slippage`: Allowed slippage (e.g., 0.01 for 1%).
    * `max_retries`: Number of times to retry the transaction if it fails.
  * Calculates the expected token amount and maximum SOL to spend with slippage.
  * Creates the buyer's Associated Token Account (ATA) if it doesn't exist.
  * Constructs and sends a transaction to the Pump.fun program to execute the buy.
  * Returns the transaction signature.
* `sell_token(agent: SolanaAgentKit, mint: Pubkey, bonding_curve: Pubkey, associated_bonding_curve: Pubkey, slippage: float = 0.25, max_retries=5)`:
  * (Static async method) Sells a token back to its Pump.fun bonding curve.
  * Parameters are similar to `buy_token`, but `amount` is not directly passed; instead, it fetches the full token balance from the agent's ATA to sell.
  * Calculates the minimum SOL output to receive based on slippage.
  * Constructs and sends a transaction to the Pump.fun program to execute the sell.
  * Returns the transaction signature.

##

**Important Considerations:**

* **Direct On-Chain Interaction:** This tool interacts directly with the Solana blockchain and the Pump.fun smart contract. It does not use a proxy.
* **Extreme Financial Risk:** Pump.fun is a platform for newly launched tokens which are often extremely volatile and can result in significant or total loss of funds. This is not an endorsement or recommendation to use Pump.fun.
* **Mainnet Operations:** Pump.fun primarily operates on Solana Mainnet. All transactions are real and involve real SOL and tokens.
* **Slippage:** High slippage tolerance is often necessary due to the volatility of tokens on Pump.fun, which further increases risk.
* **Associated Token Accounts:** The tool attempts to create the Associated Token Account (ATA) for the buyer if it doesn't exist.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_pumpfun.py>


# Use Pyth Network

The `Use Pyth Network` tool, part of AgentiPy, enables users to interact with the Pyth Network on Solana. Its primary function is to fetch real-time token price data from Pyth's on-chain oracles.

## Functionality

This tool is implemented in the `PythManager` class. It uses the `pythclient` library to connect to Pyth Network endpoints and retrieve price information.

### Key Methods:

* `get_price(mint_address: str)`:
  * (Static async method) Fetches the current aggregate price data for a given token `mint_address` (string representing the Pyth price account, which might be different from the SPL token mint for a given asset).
  * It initializes a `SolanaClient` from `pythclient` using PythNet's public HTTP/WS endpoints.
  * Creates a `PythPriceAccount` object and calls `update()` to get the latest price.
  * Returns a dictionary containing:
    * `price`: The aggregate price.
    * `confidence_interval`: The confidence interval for the price.
    * `status`: The trading status of the price feed (e.g., "TRADING", "NOT\_TRADING").
    * `message`: An optional message if the status is not "TRADING".
  * Closes the `solana_client` connection after fetching the price.

##

**Important Considerations:**

* **Direct On-Chain/Oracle Interaction:** This tool interacts directly with the Pyth Network's oracle program accounts on Solana via Pyth's defined client endpoints.
* **Pyth Price Accounts:** You must use the correct Pyth price account address for the asset you are interested in. These are specific to Pyth and are not the same as SPL token mint addresses, though they correspond to an underlying asset. Refer to Pyth Network documentation for a list of available price feeds.
* **Price Status:** Always check the `status` field in the response. A status other than "TRADING" (e.g., "UNKNOWN", "HALTED") means the price may not be current or reliable.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_pyth.py>


# Use Raydium

The `Use Raydium` tool, part of AgentiPy, allows users to interact with Raydium's Automated Market Maker (AMM) liquidity pools on the Solana blockchain. It provides functionalities to buy tokens by swapping SOL, and sell tokens for SOL.

## Functionality

This tool is implemented in the `RaydiumManager` class. It interacts directly with Raydium's on-chain programs by constructing and sending Solana transactions. Helper utilities from `agentipy.utils.raydium` are used for fetching pool information, calculating amounts, and creating swap instructions.

### Key Methods:

* `buy_with_raydium(agent: SolanaAgentKit, pair_address: str, sol_in: float = 0.01, slippage: int = 5) -> bool`:
  * Executes a buy order on a Raydium liquidity pool, swapping SOL for a target token.
  * Parameters:
    * `agent`: The `SolanaAgentKit` instance (provides wallet and connection).
    * `pair_address`: The string address of the Raydium AMM pool ID (not the token mint).
    * `sol_in`: The amount of SOL to spend (default 0.01 SOL).
    * `slippage`: Allowed slippage percentage (default 5%).
  * Fetches pool keys for the given `pair_address`.
  * Calculates the minimum amount of the target token to receive based on `sol_in` and `slippage`.
  * Manages creation of WSOL (Wrapped SOL) account and the target token's Associated Token Account (ATA) if they don't exist.
  * Constructs a transaction with instructions for creating/initializing WSOL account, swapping via Raydium, and closing the temporary WSOL account.
  * Signs and sends the transaction, then confirms it.
  * Returns `True` if confirmed, `False` otherwise.
* `sell_with_raydium(agent: SolanaAgentKit, pair_address: str, percentage: int = 100, slippage: int = 5) -> bool`:
  * Executes a sell order on a Raydium liquidity pool, swapping a token for SOL.
  * Parameters:
    * `agent`: The `SolanaAgentKit` instance.
    * `pair_address`: The string address of the Raydium AMM pool ID.
    * `percentage`: The percentage of the user's token balance to sell (default 100%).
    * `slippage`: Allowed slippage percentage (default 5%).
  * Fetches pool keys and the user's balance for the token being sold.
  * Calculates the amount of tokens to sell based on `percentage` and the minimum SOL amount to receive based on `slippage`.
  * Manages creation of a temporary WSOL account to receive the SOL from the swap.
  * Constructs a transaction similar to `buy_with_raydium` but for selling tokens.
  * Optionally closes the token account being sold if 100% of its balance is sold.
  * Signs, sends, and confirms the transaction.
  * Returns `True` if confirmed, `False` otherwise.

##

**Important Considerations:**

* **Direct On-Chain Interaction:** This tool interacts directly with the Solana blockchain and Raydium's smart contracts. It does not use a proxy service.
* **Financial Risk:** Trading on DEXs like Raydium involves financial risks, including price impact, slippage, and potential smart contract vulnerabilities.
* **AMM Pool ID:** You must use the correct Raydium AMM Liquidity Pool ID for the `pair_address` parameter, not a token mint address. These IDs can be found on Raydium's website or through DEX explorers.
* **WSOL Handling:** The tool correctly wraps SOL into WSOL for trading against SPL tokens in Raydium pools and unwraps WSOL back to SOL when selling tokens for SOL. It manages temporary WSOL accounts.
* **Transaction Confirmation:** The methods include a call to `confirm_txn` to wait for transaction finalization.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_raydium.py>


# Use SendArcade

The `Use SendArcade` tool, part of AgentiPy, allows users to interact with the Sendarcade platform (`https://rps.sendarcade.fun`), specifically to play a game of Rock Paper Scissors. The game involves staking an amount of SOL and making a choice ("rock", "paper", or "scissors"). The interaction is handled through a series of API calls to Sendarcade, which provides transaction details that are then signed and submitted to the Solana blockchain.

## Functionality

This tool is implemented in the `SendArcadeManager` class. It interacts directly with the Sendarcade API.

### Key Methods:

* `rock_paper_scissor(agent: SolanaAgentKit, amount: float, choice: str) -> str`:
  * Initiates a Rock Paper Scissors game.
  * Parameters:
    * `agent`: The `SolanaAgentKit` instance (provides wallet and connection).
    * `amount`: The amount of SOL to stake on the game.
    * `choice`: The player's choice ("rock", "paper", or "scissors").
  * Makes a POST request to the Sendarcade API (`/api/actions/bot`) with the game parameters.
  * If the API returns a transaction, it's signed by the agent's wallet and sent to the Solana network.
  * After confirmation, it calls the `outcome` method to get the game result.
  * Returns a game result message (e.g., "You lost...") or a transaction signature if a claim is needed.
* `outcome(agent: SolanaAgentKit, sig: str, href: str) -> str`:
  * (Internal helper, called by `rock_paper_scissor`) Retrieves the outcome of the game using a transaction `sig` (signature) and an API `href` (path) provided by the previous step.
  * If the game was won and a prize can be claimed, it calls `won`.
  * Returns an outcome message.
* `won(agent: SolanaAgentKit, href: str) -> str`:
  * (Internal helper) Handles the transaction process if the player won and needs to claim a prize. Uses an API `href` for claiming.
  * If a claim transaction is provided by the API, it's signed and sent.
  * May call `post_win` for a final step.
  * Returns a success/failure message for the claim.
* `post_win(agent: SolanaAgentKit, href: str) -> str`:
  * (Internal helper) Finalizes the prize claim process using an API `href`.
  * Returns a confirmation message.

##

**Important Considerations:**

* **Direct API Interaction & On-Chain:** This tool interacts directly with the Sendarcade API to get transaction details, which are then signed by the agent's wallet and submitted to the Solana blockchain. These are on-chain financial transactions (staking SOL).
* **Gaming Risk:** Playing games on such platforms involves the risk of losing the staked amount.
* **API Reliance:** The entire game flow and outcome processing depend on the Sendarcade API's responses and availability.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_sendarcade.py>


# Use SNS (Solana Name Service)

The `Use SNS` tool, part of AgentiPy, allows users to interact with the Solana Name Service (SNS). It provides functionalities to resolve `.sol` domain names to their corresponding wallet addresses, get a user's favorite domain, retrieve all domains owned by a wallet, and get the transaction object needed to register a new SNS domain. These operations are performed using a QuickNode RPC URL that supports SNS methods.

## Functionality

This tool is implemented in the `NameServiceManager` class. All methods are static and make direct JSON-RPC requests to a QuickNode RPC endpoint that supports SNS methods (configured in `agent.quicknode_rpc_url`).

### Key Methods:

* `resolve_name_to_address(agent: SolanaAgentKit, domain: str) -> Optional[str]`:
  * Resolves an SNS `domain` (e.g., "bonfida.sol") to the owner's Solana wallet address.
  * Uses the `sns_resolveDomain` RPC method.
  * Returns the wallet address as a string, or `None` if not found or an error occurs.
* `get_favourite_domain(agent: SolanaAgentKit, owner: str) -> Optional[str]`:
  * Retrieves the favorite domain name set by a specific `owner` address.
  * Uses the `sns_getFavouriteDomain` RPC method.
  * Returns the favorite domain name string or `None`.
* `get_all_domains_for_owner(agent: SolanaAgentKit, owner: str) -> Optional[List[str]]`:
  * Fetches all `.sol` domain names owned by a specific `owner` address.
  * Uses the `sns_getAllDomainsForOwner` RPC method.
  * Returns a list of domain name strings or `None`. (The script currently types output as `Optional[str]`, but RPC typically returns a list).
* `get_registration_transaction(agent:SolanaAgentKit, domain: str, buyer: str, buyer_token_account: str, space: int, mint: Optional[str] = None, referrer_key: Optional[str] = None) -> Optional[str]`:
  * Constructs the transaction needed to register a new `.sol` domain name.
  * Parameters:
    * `domain`: The domain name to register (e.g., "newdomain.sol").
    * `buyer`: The Solana public key of the buyer's main wallet (pays for rent and transaction).
    * `buyer_token_account`: The buyer's token account used for payment (typically USDC or BONK, depending on SNS registrar rules).
    * `space`: The number of bytes to allocate for the domain name account.
    * `mint` (Optional): The SPL token mint address used for payment (defaults to USDC if not specified, check SNS documentation for current valid mints).
    * `referrer_key` (Optional): A referrer's public key, if any.
  * Uses the `sns_getRegistrationTransaction` RPC method.
  * Returns a base64-encoded string of the serialized transaction object. This transaction then needs to be signed and sent by the buyer.

##

**Important Considerations:**

* **QuickNode RPC:** This tool specifically requires a QuickNode RPC URL that supports the Solana Name Service methods (e.g., `sns_resolveDomain`, `sns_getRegistrationTransaction`). This should be set in `agent.quicknode_rpc_url`.
* **Direct API Interaction:** It interacts directly with the specified Solana RPC endpoint (QuickNode). It does not use the Agentipy proxy service.
* **Domain Registration:** The `get_registration_transaction` method only returns the serialized transaction. The user (or agent) would then need to decode this, sign it with the buyer's wallet, and submit it to the network to complete the domain registration. This is an on-chain transaction with costs.
* **Payment Mints:** For domain registration, SNS typically uses specific SPL tokens like USDC or BONK for payment. The correct `buyer_token_account` and `mint` (if not default) must be used.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_sns.py>


# Use Solayer

The `Use Solayer` tool, part of AgentiPy, allows users to interact with the Solayer platform (`https://app.solayer.org`), specifically for staking SOL to receive sSOL (Solayer Staked SOL), which is a liquid staking token.

## Functionality

This tool is implemented in the `SolayerManager` class. It interacts directly with the Solayer API to get a transaction for staking, which is then signed by the agent's wallet and submitted to the Solana blockchain.

### Key Methods:

* `stake_with_solayer(agent: SolanaAgentKit, amount: float) -> str`:
  * Stakes a specified `amount` of SOL with Solayer to mint sSOL.
  * Parameters:
    * `agent`: The `SolanaAgentKit` instance (provides wallet and connection).
    * `amount`: The amount of SOL to stake.
  * Makes a POST request to the Solayer API endpoint (`https://app.solayer.org/api/action/restake/ssol`) with the agent's wallet address and the staking amount.
  * The API returns a base64 encoded, serialized `VersionedTransaction`.
  * This transaction is then decoded, signed by the agent's wallet.
  * The signed transaction is sent to the Solana network and confirmed.
  * Returns the transaction signature as a string.

##

**Important Considerations:**

* **Direct API Interaction & On-Chain:** This tool first interacts with the Solayer API to fetch a pre-built transaction. This transaction is then signed locally using the agent's wallet and submitted directly to the Solana blockchain. This is an on-chain financial transaction.
* **Liquid Staking:** When you stake SOL with Solayer, you receive sSOL, a liquid staking token. Understand how sSOL accrues value and the risks associated with liquid staking protocols (e.g., smart contract risk, de-pegging risk if sSOL trades differently from SOL).
* **API Reliance:** The construction of the staking transaction relies on the Solayer API.
* **Fees:** The transaction will incur standard Solana network fees. Solayer might also have protocol fees, which would be embedded in the transaction returned by their API.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_solayer.py>


# Use SolutioFi

The `Use SolutioFi` tool, part of AgentiPy, provides a suite of utilities for managing SPL tokens on the Solana blockchain. These include functionalities like closing token accounts, burning tokens, merging multiple token balances into one, and spreading a single token balance into multiple other tokens. These operations are routed through an Agentipy proxy service and may require a SolutioFi API key.

## Functionality

This tool is implemented in the `SolutiofiManager` class. All its methods interact with an Agentipy proxy service (`agent.base_proxy_url`), sending encrypted private keys, an OpenAI API key, and a SolutioFi API key (`agent.solutiofi_api_key`) with each request.

### Key Methods:

* `close_accounts(agent: SolanaAgentKit, mints: List[str]) -> Optional[Dict[str, Any]]`:
  * Closes the token accounts associated with the provided list of `mints` for the agent's wallet.
  * Returns a dictionary with transaction details or an error.
* `burn_tokens(agent: SolanaAgentKit, mints: List[str]) -> Optional[Dict[str, Any]]`:
  * Burns all tokens in the token accounts associated with the provided list of `mints` for the agent's wallet.
  * Returns a dictionary with transaction details or an error.
* `merge_tokens(agent: SolanaAgentKit, input_assets: List[Dict[str, Any]], output_mint: str, priority_fee: str) -> Optional[Dict[str, Any]]`:
  * Merges multiple `input_assets` (list of dicts, each specifying mint and amount) into a single `output_mint`.
  * `priority_fee` can be 'fast', 'turbo', 'ultra'.
  * This likely involves swapping the input assets for the output asset.
  * Returns a dictionary with transaction details or an error.
* `spread_token(agent: SolanaAgentKit, input_asset: Dict[str, Any], target_tokens: List[Dict[str, Any]], priority_fee: str) -> Optional[Dict[str, Any]]`:
  * Spreads a single `input_asset` (dict with mint and amount) into multiple `target_tokens` (list of dicts, each specifying mint and percentage or amount).
  * `priority_fee` can be 'fast', 'turbo', 'ultra'.
  * This likely involves swapping the input asset for the target assets.
  * Returns a dictionary with transaction details or an error.

##

**Important Considerations:**

* **Proxy Service:** This tool relies on an Agentipy proxy service. The availability, authentication (including the role of OpenAI and SolutioFi API keys), and terms of use for this proxy are critical.
* **On-Chain Actions:** All methods (`close_accounts`, `burn_tokens`, `merge_tokens`, `spread_token`) result in on-chain transactions that modify token balances, close accounts, or execute swaps. These actions incur SOL fees and have financial implications.
* **API Keys:** A `solutiofi_api_key` is explicitly included in the payload to the proxy, indicating it's likely required by the SolutioFi backend accessed via the proxy. An `openai_api_key` is also passed.
* **Token Management:** These tools provide powerful ways to manage multiple tokens, but care must be taken, especially with operations like `merge_tokens` and `spread_token` which likely involve underlying swaps and associated slippage or price impact.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_solutiofi.py>


# Use Squads

The `Use Squads` tool, part of AgentiPy, allows users to interact with the Squads Protocol on Solana. Squads is a platform for creating and managing multi-signature wallets (multisigs) and DAO-like structures. This tool provides functionalities for creating multisigs, creating and managing proposals (approving, rejecting, executing), and managing the multisig treasury. These operations are routed through an Agentipy proxy service.

## Functionality

This tool is implemented in the `SquadsManager` class. All its methods interact with an Agentipy proxy service (`agent.base_proxy_url`), sending encrypted private keys and an OpenAI API key with each request.

### Key Methods:

* `create_squads_multisig(agent: SolanaAgentKit, creator: str) -> Optional[Dict[str, Any]]`:
  * Creates a new Squads multisig.
  * `creator`: The public key of the wallet initiating the multisig creation (likely the agent's wallet or another specified address).
* `create_multisig_proposal(agent: SolanaAgentKit, transaction_index: int) -> Optional[Dict[str, Any]]`:
  * Creates a new proposal within a multisig, referencing a `transaction_index` (which implies transactions are pre-registered or indexed elsewhere, possibly via the proxy or Squads UI).
* `approve_multisig_proposal(agent: SolanaAgentKit, transaction_index: int) -> Optional[Dict[str, Any]]`:
  * Approves an existing multisig proposal identified by `transaction_index`.
* `reject_multisig_proposal(agent: SolanaAgentKit, transaction_index: int) -> Optional[Dict[str, Any]]`:
  * Rejects an existing multisig proposal.
* `execute_multisig_proposal(agent: SolanaAgentKit, transaction_index: int) -> Optional[Dict[str, Any]]`:
  * Executes an approved multisig proposal.
* `deposit_to_multisig_treasury(agent: SolanaAgentKit, amount: float, vault_index: int, mint: Optional[str] = None) -> Optional[Dict[str, Any]]`:
  * Deposits tokens into a multisig's treasury.
  * `amount`: The quantity of tokens to deposit.
  * `vault_index`: The index of the vault within the multisig to deposit into.
  * `mint` (Optional): The mint address of the token being deposited (e.g., USDC, SOL). If not provided, it might default to SOL or require the vault to be specific to a token.
* `transfer_from_multisig_treasury(agent: SolanaAgentKit, amount: float, to: str, vault_index: int, mint: str) -> Optional[Dict[str, Any]]`:
  * Creates a proposal to transfer assets from a multisig treasury.
  * `amount`, `to` (recipient address), `vault_index`, and `mint` of the token. This likely creates a proposal that then needs to be approved and executed.

All methods return a dictionary with the transaction details from the proxy or an error.

##

**Important Considerations:**

* **Proxy Service:** This tool relies on an Agentipy proxy service. The availability, authentication (including the role of the OpenAI API key), and terms of use for this proxy are critical.
* **On-Chain Governance Actions:** All Squads operations (creating multisigs, proposals, treasury management) are significant on-chain transactions that modify state, control assets, and incur SOL fees.
* **Squads Protocol Knowledge:** Users must have a thorough understanding of how Squads multisigs work, including concepts like thresholds, member roles, proposal lifecycles, and vault indexing. Errors can lead to loss of control over assets or failed proposals.
* **Transaction Indexing:** Methods related to proposals often refer to a `transaction_index`. How these indices are determined and managed (likely by the Squads platform or the proxy) is crucial for correct operation.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_squads.py>


# Use Stork

The `Use Stork` tool, part of AgentiPy, allows users to fetch real-time asset price data from the Stork Oracle. Stork provides oracle services for various assets, and this tool enables retrieving the current price and timestamp for a given asset ID.

## Functionality

This tool is implemented in the `StorkManager` class. It uses a helper function `get_stork_price` (from `agentipy.utils.stork.utils`) which likely makes a direct HTTP request to a Stork API endpoint. This tool requires a Stork API key.

### Key Methods:

* `get_price(agent: SolanaAgentKit, asset_id: str)`:
  * (Static async method) Fetches the price data for a specified `asset_id` (e.g., "SOL/USD").
  * The `agent` instance is used to provide the `stork_api_key` (`agent.stork_api_key`).
  * The underlying `get_stork_price` utility constructs the API request to Stork, including the API key.
  * Parses the response to extract the price (converted to float and adjusted by 10^18, common for oracle fixed-point numbers) and the timestamp of the price update.
  * Returns a dictionary containing `price` and `timestamp`.
  * Raises an exception if the API call fails, data is not found, or the response is malformed.

##

**Important Considerations:**

* **API Key Required:** A valid Stork API key must be provided via `agent.stork_api_key`.
* **Direct API Interaction:** This tool interacts directly with the Stork oracle API. It does not use the Agentipy proxy service.
* **Asset IDs:** You need to use the correct `asset_id` string as defined by Stork for the price feed you want to query.
* **Price Precision:** The price is returned as a float, adjusted by 10^18. This is a common practice for oracles to handle fixed-point arithmetic.
* **Data Reliability:** Oracle data is subject to its own update mechanisms and potential (though rare) inaccuracies or delays.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_stork.py>


# Use Switchboard

The `Use Switchboard` tool, part of AgentiPy, provides functionalities for interacting with the Switchboard oracle network on Solana. The current implementation focuses on simulating a Switchboard data feed, which can be useful for testing or development purposes. This operation is routed through an Agentipy proxy service.

## Functionality

This tool is implemented in the `SwitchboardManager` class. It interacts with an Agentipy proxy service (`agent.base_proxy_url`) to perform actions related to Switchboard. The agent's private key is encrypted and sent to this proxy, and an OpenAI API key (`agent.openai_api_key`) also seems to be part of the payload.

### Key Methods:

* `simulate_switchboard_feed(agent: SolanaAgentKit, feed: str, crossbar_url: Optional[str] = None) -> Optional[Dict[str, Any]]`:
  * Simulates a Switchboard data `feed` (likely the public key of a feed account).
  * Parameters:
    * `agent`: The `SolanaAgentKit` instance.
    * `feed`: The feed address (string) to be simulated.
    * `crossbar_url` (Optional): The crossbar URL for Switchboard. If not provided, the proxy service might use a default.
  * Sends a request to the Agentipy proxy endpoint (`/switchboard/simulate-switchboard-feed`).
  * Returns a dictionary with the simulation result from the proxy or an error.

##

**Important Considerations:**

* **Proxy Service:** This tool relies on an Agentipy proxy service. The functionality is dependent on this proxy's implementation of Switchboard feed simulation.
* **Simulation vs. On-Chain:** This method simulates a feed. It does not directly interact with or alter live Switchboard oracle data on-chain but rather provides a way to test or get hypothetical values based on the simulation logic implemented in the proxy.
* **API Keys:** An `openai_api_key` is passed to the proxy; its role in the simulation process should be understood from the proxy's documentation. The agent's Solana private key is also encrypted and sent.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_switchboard.py>


# Use Tensor

The `Use Tensor` tool, part of AgentiPy, allows users to interact with the Tensor NFT marketplace on Solana. It provides functionalities to list NFTs for sale and cancel existing listings. These operations are routed through an Agentipy proxy service.

## Functionality

This tool is implemented in the `TensorManager` class. All its methods interact with an Agentipy proxy service (`agent.base_proxy_url`), sending encrypted private keys and an OpenAI API key with each request. These proxy calls likely translate to on-chain interactions with Tensor's smart contracts.

### Key Methods:

* `list_nft_for_sale(agent: SolanaAgentKit, price: float, nft_mint: str) -> Optional[Dict[str, Any]]`:
  * Lists an NFT for sale on the Tensor marketplace.
  * Parameters:
    * `agent`: The `SolanaAgentKit` instance.
    * `price`: The desired listing price for the NFT (likely in SOL).
    * `nft_mint`: The mint address (string) of the NFT to be listed.
  * Sends a request to the Agentipy proxy endpoint (`/tensor/list-nft-for-sale`).
  * Returns a dictionary with the transaction details from the proxy or an error.
* `cancel_listing(agent: SolanaAgentKit, nft_mint: str) -> Optional[Dict[str, Any]]`:
  * Cancels an active listing for an NFT on Tensor.
  * Parameters:
    * `agent`: The `SolanaAgentKit` instance.
    * `nft_mint`: The mint address (string) of the NFT whose listing is to be canceled.
  * Sends a request to the Agentipy proxy endpoint (`/tensor/cancel-listing`).
  * Returns a dictionary with the transaction details from the proxy or an error.

##

**Important Considerations:**

* **Proxy Service:** This tool relies on an Agentipy proxy service. The functionality is dependent on this proxy's correct implementation of Tensor interactions.
* **On-Chain NFT Operations:** Listing an NFT for sale and canceling a listing are on-chain actions that will interact with your NFT and require SOL for transaction fees.
* **Tensor Platform:** Familiarity with how Tensor listings work, including their fee structure and marketplace rules, is recommended.
* **API Keys:** An `openai_api_key` is passed to the proxy; its role in Tensor operations should be understood from the proxy's documentation. The agent's Solana private key is also encrypted and sent.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_tensor.py>


# Use TipLink

The `Use TipLink` tool, part of AgentiPy, allows users to create TipLinks. TipLink is a service on Solana that enables sending SOL or SPL tokens via a shareable link, making it easy to tip users or onboard new users to crypto without needing their wallet address beforehand. This tool uses an Agentipy proxy service to create these TipLinks.

## Functionality

This tool is implemented in the `TiplinkManager` class. It interacts with an Agentipy proxy service (`agent.base_proxy_url`) to create TipLinks. The agent's private key is encrypted and sent to this proxy, and an OpenAI API key (`agent.openai_api_key`) also seems to be part of the payload.

### Key Methods:

* `create_tiplink(agent: SolanaAgentKit, amount: float, spl_mint_address: Optional[str] = None) -> Optional[Dict[str, Any]]`:
  * Creates a new TipLink funded by the agent's wallet.
  * Parameters:
    * `agent`: The `SolanaAgentKit` instance.
    * `amount`: The amount of SOL or SPL tokens to fund the TipLink with.
    * `spl_mint_address` (Optional): If creating a TipLink for an SPL token, this is its mint address (string). If `None`, SOL is used.
  * Sends a request to the Agentipy proxy endpoint (`/tiplink/create-tiplink`).
  * The response from the proxy is expected to contain the TipLink URL and transaction details for funding it.
  * Returns a dictionary with the TipLink URL, transaction details, or an error.

##

**Important Considerations:**

* **Proxy Service:** This tool relies on an Agentipy proxy service. The functionality is dependent on this proxy's correct implementation of TipLink creation.
* **On-Chain Fund Transfer:** Creating a TipLink is an on-chain action that transfers SOL or SPL tokens from your (the agent's) wallet to a new TipLink account/address. This requires SOL for gas fees and sufficient balance of the asset being tipped.
* **TipLink Security:** Once a TipLink is created and funded, the link itself is the key to accessing the funds. Share these links securely.
* **API Keys:** An `openai_api_key` is passed to the proxy; its role in TipLink creation should be understood from the proxy's documentation. The agent's Solana private key is also encrypted and sent.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_tiplink.py>


# Use Voltr

The `Use Voltr` tool, part of AgentiPy, allows users to interact with Voltr, which appears to be a platform for DeFi yield strategies or vaults on Solana. It provides functionalities to deposit into and withdraw from strategies, and to fetch position values. These operations are routed through an Agentipy proxy service.

## Functionality

This tool is implemented in the `VoltrManager` class. All its methods interact with an Agentipy proxy service (`agent.base_proxy_url`), sending encrypted private keys and an OpenAI API key with each request. These proxy calls likely translate to on-chain interactions with Voltr's smart contracts.

### Key Methods:

* `deposit_strategy(agent: SolanaAgentKit, deposit_amount: str, vault: str, strategy: str) -> Optional[Dict[str, Any]]`:
  * Deposits funds into a specific Voltr strategy.
  * Parameters:
    * `agent`: The `SolanaAgentKit` instance.
    * `deposit_amount`: The amount to deposit (as a string, possibly to handle large numbers or specific decimal precision via the proxy).
    * `vault`: The address (string) of the Voltr vault.
    * `strategy`: The address (string) of the specific strategy within the vault.
  * Sends a request to the Agentipy proxy endpoint (`/voltr/deposit-strategy`).
  * Returns a dictionary with the transaction details from the proxy or an error.
* `withdraw_strategy(agent: SolanaAgentKit, withdraw_amount: str, vault: str, strategy: str) -> Optional[Dict[str, Any]]`:
  * Withdraws funds from a specific Voltr strategy.
  * Parameters are similar to `deposit_strategy`, with `withdraw_amount` specifying the amount to withdraw.
  * Sends a request to the Agentipy proxy endpoint (`/voltr/withdraw-strategy`).
  * Returns a dictionary with transaction details or an error.
* `get_position_values(agent: SolanaAgentKit, vault: str) -> Optional[Dict[str, Any]]`:
  * Fetches the current position values for a given Voltr `vault` address.
  * This is likely a read-only operation through the proxy.
  * Sends a request to the Agentipy proxy endpoint (`/voltr/get-position-values`).
  * Returns a dictionary with the position values or an error.

##

**Important Considerations:**

* **Proxy Service:** This tool relies on an Agentipy proxy service. The functionality is dependent on this proxy's correct implementation of Voltr interactions.
* **On-Chain DeFi Operations:** Depositing into and withdrawing from Voltr strategies are on-chain transactions that involve your assets and will incur SOL fees. These actions carry financial risk associated with DeFi protocols.
* **Voltr Protocol Specifics:** Understanding Voltr's vaults, strategies, fee structures, and the specific tokens involved is crucial before interacting with it. Vault and strategy addresses must be correct.
* **API Keys:** An `openai_api_key` is passed to the proxy; its role in Voltr operations should be understood from the proxy's documentation. The agent's Solana private key is also encrypted and sent.
* **Amount as String:** The `deposit_amount` and `withdraw_amount` are passed as strings, which might be to maintain precision for token amounts with many decimals when processed by the proxy or smart contract.

## Source Code

You can find the source code for this tool on GitHub: <https://github.com/niceberginc/agentipy/blob/main/agentipy/tools/use_voltr.py>


# Examples


# Allora Example

This example demonstrates how to use AgentiPy with the Allora protocol. It sets up a FastAPI service that provides continuous price predictions for BTC and ETH using the Allora Network.

The implementation showcases:

* Real-time price predictions for BTC/ETH (5min and 8hr timeframes)
* Asynchronous data fetching from Allora Network
* Continuous background updates
* REST API endpoint for prediction access
* Production-grade error handling and logging

## Code (`main.py`)

```python
import asyncio
import os
import logging
from fastapi import FastAPI
from pydantic import BaseModel
from datetime import datetime
from typing import Optional
from agentipy.agent import SolanaAgentKit
from agentipy.tools.use_allora import (
    AlloraManager,
    PriceInferenceToken,
    PriceInferenceTimeframe,
    ChainSlug
)

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)

SLEEP_INTERVAL = int(os.getenv("SLEEP_INTERVAL", 300))
API_ENV = os.getenv("ALLORA_ENV", "MAINNET")
CHAIN = ChainSlug.MAINNET if API_ENV.upper() == "MAINNET" else ChainSlug.TESTNET

class Predictions(BaseModel):
    btc_5min: Optional[float] = None
    eth_5min: Optional[float] = None
    btc_8hour: Optional[float] = None
    eth_8hour: Optional[float] = None
    last_updated: Optional[datetime] = None

latest_predictions = Predictions()
allora = None

app = FastAPI()

async def fetch_predictions_loop():
    global latest_predictions
    while True:
        try:
            btc_5min = await allora.get_price_prediction(PriceInferenceToken.BTC, PriceInferenceTimeframe.FIVE_MIN)
            eth_5min = await allora.get_price_prediction(PriceInferenceToken.ETH, PriceInferenceTimeframe.FIVE_MIN)
            btc_8hour = await allora.get_price_prediction(PriceInferenceToken.BTC, PriceInferenceTimeframe.EIGHT_HOURS)
            eth_8hour = await allora.get_price_prediction(PriceInferenceToken.ETH, PriceInferenceTimeframe.EIGHT_HOURS)

            latest_predictions.btc_5min = btc_5min
            latest_predictions.eth_5min = eth_5min
            latest_predictions.btc_8hour = btc_8hour
            latest_predictions.eth_8hour = eth_8hour
            latest_predictions.last_updated = datetime.now()

            logging.info(f"Updated predictions - BTC (5min): {btc_5min}, ETH (5min): {eth_5min}, "
                         f"BTC (8hour): {btc_8hour}, ETH (8hour): {eth_8hour}")
        except Exception as e:
            logging.error(f"Error fetching predictions: {str(e)}")
        await asyncio.sleep(SLEEP_INTERVAL)

@app.on_event("startup")
async def startup_event():
    global allora
    api_key = os.getenv('ALLORA_API_KEY', 'UP-Allora_Api-key')
    agent = SolanaAgentKit(allora_api_key=api_key)
    allora = AlloraManager(agent=agent, chain=CHAIN)
    asyncio.create_task(fetch_predictions_loop())

@app.get("/predictions", response_model=Predictions)
async def get_predictions():
    return latest_predictions

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)
```

## Source Files

You can find the source files for this example (including `readme.md` with setup and usage instructions) on GitHub: <https://github.com/niceberginc/agentipy/blob/main/examples/Allora/>


# Crypto Market Dashboard Example

This example demonstrates how to use the `agentipy` framework to build a crypto market dashboard that:

* Retrieves market prices from Pyth feeds.
* Gets AI-based price predictions via Allora.
* Formats and sends styled embed messages to Discord using a webhook.

## Features

* **Price Updates:** Fetches live prices and confidence intervals for assets such as SOL/USD, BTC/USD, ETH/USD, and TRUMP/USD.
* **AI Forecast:** Retrieves short-term (5min) and longer-term (8hr) predictions for BTC and ETH.
* **Discord Integration:** Sends the updates as a rich embed message to a Discord channel.
* **Robust Logging & Error Handling:** Provides system notices and handles partial outages gracefully.

## Code (`main.py`)

````python
import asyncio
import os
import logging
import datetime
from typing import Dict, List, Any

import aiohttp

from agentipy.tools.use_pyth import PythManager
from agentipy.agent import SolanaAgentKit
from agentipy.tools.use_allora import (
    AlloraManager,
    PriceInferenceToken,
    PriceInferenceTimeframe,
    ChainSlug
)

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[logging.StreamHandler()]
)

# Configuration
SLEEP_INTERVAL = int(os.getenv("SLEEP_INTERVAL", 300))
ALLORA_ENV = os.getenv("ALLORA_ENV", "MAINNET")
DISCORD_WEBHOOK_URL = os.getenv("DISCORD_WEBHOOK_URL")
CHAIN = ChainSlug.MAINNET if ALLORA_ENV.upper() == "MAINNET" else ChainSlug.TESTNET

PYTH_FEEDS: Dict[str, str] = {
    "SOL/USD": "H6ARHf6YXhGYeQfUzQNGk6rDNnLBQKrenN712K4AQJEG",
    "BTC/USD": "GVXRSBjFk6e6J3NbVPXohDJetcTjaeeuykUpbQF8UoMU",
    "ETH/USD": "JBu1AL4obBcCMqKBBxhpWCNUt136ijcuMZLFvTP7iWdB",
    "TRUMP/USD": "A8G6XyA6fSrsavG63ssAGU3Hnt2oDZARxefREzAY5axH",
}

class MarketMonitor:
    def __init__(self):
        self.agent = SolanaAgentKit(
            allora_api_key=os.getenv('ALLORA_API_KEY', 'UP-Allora_API_Key')
        )
        self.session = aiohttp.ClientSession()
        self.last_update = datetime.datetime.utcnow()

    async def close(self):
        await self.session.close()

    def _format_prediction(self, prediction_data: Dict[str, Any]) -> str:
        """Format prediction data with confidence interval"""
        try:
            price = prediction_data.get('price_prediction', 0)
            confidence = prediction_data.get('confidence_interval', [0.0])[0]
            return f"${float(price):.2f} (±${float(confidence):.2f})"
        except Exception as e:
            logging.error(f"Error formatting prediction: {str(e)}")
            return "N/A"

    async def create_embed(self, message_data: dict) -> dict:
        """Create a rich Discord embed with modern UI elements"""
        status_color = 0x00FF88 if message_data.get('status') == "success" else 0xFF3300
        timestamp = datetime.datetime.utcnow().isoformat()

        embed = {
            "title": "🌐 Crypto Market Dashboard",
            "color": status_color,
            "thumbnail": {"url": os.getenv("EMBED_THUMBNAIL", "")},
            "footer": {
                "text": "Market Intelligence v2.4",
                "icon_url": os.getenv("FOOTER_ICON", "")
            },
            "timestamp": timestamp,
            "fields": []
        }

        # Price Section
        price_fields = []
        for symbol, data in message_data.get('prices', {}).items():
            price_fields.append({
                "name": f"🔸 {symbol}",
                "value": (
                    f"```diff\n"
                    f"+ Price: ${data['price']:.4f}\n"
                    f"± Confidence: ${data['confidence']:.4f}\n"
                    f"🕒 Updated: {data['timestamp']}\n"
                    f"```"
                ),
                "inline": True
            })

        # Add prices in grid layout
        for i in range(0, len(price_fields), 2):
            embed["fields"].extend(price_fields[i:i+2])
            if i+2 < len(price_fields):
                embed["fields"].append({"name": "\u200b", "value": "\u200b", "inline": False})

        # Prediction Section
        if message_data.get('predictions'):
            prediction_groups = {}
            for pred in message_data['predictions']:
                key = pred['token']
                if key not in prediction_groups:
                    prediction_groups[key] = []
                prediction_groups[key].append(pred)

            for token, preds in prediction_groups.items():
                pred_lines = [f"**{token} Predictions**"]
                for p in preds:
                    formatted = self._format_prediction(p['data'])
                    pred_lines.append(f"▫️ {p['timeframe']}: {formatted}")

                embed["fields"].append({
                    "name": "🔮 AI Forecast",
                    "value": "\n".join(pred_lines),
                    "inline": False
                })

        # Warnings Section
        if message_data.get('warnings'):
            embed["fields"].append({
                "name": "⚠️ System Notices",
                "value": "\n".join([f"▫️ {warn}" for warn in message_data['warnings']]),
                "inline": False
            })

        return embed

    async def send_discord_update(self, message_data: dict):
        """Send styled embed message to Discord"""
        if not DISCORD_WEBHOOK_URL:
            logging.warning("Discord webhook not configured")
            return

        try:
            embed = await self.create_embed(message_data)
            payload = {
                "embeds": [embed],
                "username": "Crypto Sentinel",
                "avatar_url": os.getenv("BOT_AVATAR", "")
            }

            async with self.session.post(DISCORD_WEBHOOK_URL, json=payload) as resp:
                if resp.status not in (200, 204):
                    error = await resp.text()
                    logging.error(f"Discord API error: {resp.status} - {error}")
                else:
                    logging.info("Sent market update successfully")

        except Exception as e:
            logging.error(f"Notification error: {str(e)}")

    async def fetch_market_data(self) -> dict:
        """Aggregate data from all sources"""
        data = {
            "status": "success",
            "prices": {},
            "predictions": [],
            "warnings": []
        }

        # Fetch Pyth prices
        for symbol, address in PYTH_FEEDS.items():
            try:
                result = await PythManager.get_price(address)
                if result["status"] == "TRADING":
                    data["prices"][symbol] = {
                        "price": result["price"],
                        "confidence": result["confidence_interval"],
                        "timestamp": datetime.datetime.utcnow().strftime("%H:%M:%S UTC")
                    }
                else:
                    data["warnings"].append(f"{symbol} in {result['status']} status")
            except Exception as e:
                data["warnings"].append(f"{symbol} data unavailable")
                logging.error(f"Price error ({symbol}): {str(e)}")

        # Fetch Allora predictions
        try:
            allora = AlloraManager(agent=self.agent, chain=CHAIN)
            timeframes = [
                (PriceInferenceTimeframe.FIVE_MIN, "5min"),
                (PriceInferenceTimeframe.EIGHT_HOURS, "8hr")
            ]

            predictions = []
            for token in [PriceInferenceToken.BTC, PriceInferenceToken.ETH]:
                for timeframe, label in timeframes:
                    try:
                        prediction = await allora.get_price_prediction(token, timeframe)
                        predictions.append({
                            "token": token.name,
                            "timeframe": label,
                            "data": prediction
                        })
                    except Exception as e:
                        data["warnings"].append(f"Prediction failed for {token.name} {label}")
                        logging.error(f"Prediction error ({token.name} {label}): {str(e)}")

            data["predictions"] = predictions

        except Exception as e:
            data["warnings"].append("Prediction service unavailable")
            logging.error(f"Allora connection error: {str(e)}")

        # Update system status
        if len(data["warnings"]) > 2:
            data["status"] = "partial_outage"
        elif len(data["warnings"]) > 0:
            data["status"] = "warning"

        return data

    async def monitor_loop(self):
        """Main monitoring loop"""
        while True:
            try:
                market_data = await self.fetch_market_data()
                await self.send_discord_update(market_data)
                logging.info(f"Sleeping for {SLEEP_INTERVAL}s...")
                await asyncio.sleep(SLEEP_INTERVAL)

            except Exception as e:
                logging.error(f"Critical error: {str(e)}")
                emergency_data = {
                    "status": "error",
                    "warnings": ["System malfunction - attempting recovery"]
                }
                await self.send_discord_update(emergency_data)
                await asyncio.sleep(60)

async def main():
    monitor = MarketMonitor()
    try:
        await monitor.monitor_loop()
    except KeyboardInterrupt:
        await monitor.close()
        logging.info("Graceful shutdown complete")

if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        logging.info("Monitoring stopped by user")
````

## Source Files

You can find the source files for this example (including `readme.md` with setup and usage instructions) on GitHub: <https://github.com/niceberginc/agentipy/blob/main/examples/CryptoMarketDashboard/>


# Elfaai Examples

These examples demonstrate the use of the Agentipy library to interact with the Elfa AI API for blockchain and crypto-related data analysis. Agentipy simplifies interacting with various APIs, including the Elfa AI API, by providing a structured approach for authentication, tool creation, and asynchronous execution.

The examples show how to:

* Initialize a `SolanaAgentKit` object.
* Create and use Elfa AI tools provided by Agentipy.
* Call different Elfa AI endpoints to retrieve information such as smart mentions, top mentions by ticker, search mentions by keywords, trending tokens, and Twitter account stats.
* One script (`elfaai2.py`) provides an interactive way to choose and run these analyses.

## Code

### `elfaai1.py` (Basic Elfa AI API Calls)

```python
import asyncio
import json
import os
from agentipy.agent import SolanaAgentKit
from agentipy.langchain.elfaai import get_elfaai_tools

async def main():
    private_key = os.getenv("SOLANA_PRIVATE_KEY")
    elfa_ai_api_key = os.getenv("ELFA_AI_API_KEY")

    if not private_key or not elfa_ai_api_key:
        print("ERROR: Missing required environment variables!")
        print("Run the following in your terminal:")
        print('export SOLANA_PRIVATE_KEY="your_base58_private_key_here"')
        print('export ELFA_AI_API_KEY="your_elfa_ai_api_key_here"')
        return

    try:
        solana_kit = SolanaAgentKit(private_key=private_key, elfa_ai_api_key=elfa_ai_api_key)
    except Exception as e:
        print("Error initializing SolanaAgentKit:", e)
        return

    tools = get_elfaai_tools(solana_kit)
    results = {}

    # Get Smart Mentions
    smart_mentions_tool = next(tool for tool in tools if tool.name == "elfa_ai_get_smart_mentions")
    smart_mentions_input = json.dumps({"limit": 5, "offset": 0})
    results["Smart Mentions"] = await smart_mentions_tool._arun(smart_mentions_input)

    # Get Top Mentions by Ticker
    top_mentions_tool = next(tool for tool in tools if tool.name == "elfa_ai_get_top_mentions_by_ticker")
    top_mentions_input = json.dumps({
        "ticker": "SOL",
        "time_window": "1h",
        "page": 1,
        "page_size": 5,
        "include_account_details": True
    })
    results["Top Mentions by Ticker"] = await top_mentions_tool._arun(top_mentions_input)

    # Search Mentions by Keywords
    search_mentions_tool = next(tool for tool in tools if tool.name == "elfa_ai_search_mentions_by_keywords")
    search_mentions_input = json.dumps({
        "keywords": "Solana blockchain",
        "from_timestamp": 1672531200,
        "to_timestamp": 1740787200,
        "limit": 5
    })
    results["Search Mentions by Keywords"] = await search_mentions_tool._arun(search_mentions_input)


    # Get Trending Tokens
    trending_tokens_tool = next(tool for tool in tools if tool.name == "elfa_ai_get_trending_tokens")
    trending_tokens_input = json.dumps({
        "time_window": "24h",
        "page": 1,
        "page_size": 10,
        "min_mentions": 5
    })
    results["Trending Tokens"] = await trending_tokens_tool._arun(trending_tokens_input)

    # Get Smart Twitter Account Stats
    twitter_stats_tool = next(tool for tool in tools if tool.name == "elfa_ai_get_smart_twitter_account_stats")
    twitter_stats_input = json.dumps({
        "username": "solana"
    })
    results["Twitter Stats"] = await twitter_stats_tool._arun(twitter_stats_input)

    # Print results
    for name, result in results.items():
        print(f"\n{name}:\n", json.dumps(result, indent=2))

if __name__ == "__main__":
    asyncio.run(main())
```

### `elfaai2.py` (Interactive Elfa AI Analysis)

```python
import asyncio
import json
import os
import datetime
from agentipy.agent import SolanaAgentKit
from agentipy.langchain.elfaai import get_elfaai_tools

async def main():
    # Load required environment variables
    private_key = os.getenv("SOLANA_PRIVATE_KEY")
    elfa_ai_api_key = os.getenv("ELFA_AI_API_KEY")

    if not private_key or not elfa_ai_api_key:
        print("ERROR: Missing required environment variables!")
        print('Run the following in your terminal:')
        print('export SOLANA_PRIVATE_KEY="your_base58_private_key_here"')
        print('export ELFA_AI_API_KEY="your_elfa_ai_api_key_here"')
        return

    try:
        solana_kit = SolanaAgentKit(private_key=private_key, elfa_ai_api_key=elfa_ai_api_key)
    except Exception as e:
        print("Error initializing SolanaAgentKit:", e)
        return

    # Load tools from Elfa AI
    tools = get_elfaai_tools(solana_kit)

    # Let user select which analysis to run
    print("Choose an analysis option:")
    print("1. Get Smart Mentions")
    print("2. Get Top Mentions by Ticker")
    print("3. Search Mentions by Keywords (with date range)")
    print("4. Get Trending Tokens")
    print("5. Get Twitter Stats")
    choice = input("Enter your choice (1-5): ").strip()

    results = {}

    if choice == "1":
        # Get Smart Mentions
        limit = input("Enter number of smart mentions to retrieve (default 5): ").strip() or "5"
        offset = input("Enter offset (default 0): ").strip() or "0"
        smart_mentions_input = json.dumps({
            "limit": int(limit),
            "offset": int(offset)
        })
        tool = next(tool for tool in tools if tool.name == "elfa_ai_get_smart_mentions")
        results["Smart Mentions"] = await tool._arun(smart_mentions_input)

    elif choice == "2":
        # Get Top Mentions by Ticker
        ticker = input("Enter token ticker (e.g., SOL): ").strip() or "SOL"
        time_window = input("Enter time window (e.g., 1h): ").strip() or "1h"
        page = input("Enter page number (default 1): ").strip() or "1"
        page_size = input("Enter page size (default 5): ").strip() or "5"
        include_details_input = input("Include account details? (yes/no, default no): ").strip().lower()
        # Convert input to Boolean (True if user says yes, else False)
        include_details = True if include_details_input.startswith("y") else False
        top_mentions_input = json.dumps({
            "ticker": ticker,
            "time_window": time_window,
            "page": int(page),
            "page_size": int(page_size),
            "include_account_details": include_details
        })
        tool = next(tool for tool in tools if tool.name == "elfa_ai_get_top_mentions_by_ticker")
        results["Top Mentions by Ticker"] = await tool._arun(top_mentions_input)

    elif choice == "3":
        # Search Mentions by Keywords with a date range
        keywords = input("Enter keywords for search: ").strip()
        from_date_str = input("Enter start date (YYYY-MM-DD): ").strip()
        to_date_str = input("Enter end date (YYYY-MM-DD): ").strip()
        try:
            from_timestamp = int(datetime.datetime.strptime(from_date_str, "%Y-%m-%d").timestamp())
            to_timestamp = int(datetime.datetime.strptime(to_date_str, "%Y-%m-%d").timestamp())
        except Exception as e:
            print("Error parsing dates:", e)
            return

        # Validate date range: must be at least 1 day and at most 30 days
        one_day = 86400
        thirty_days = 30 * one_day
        diff = to_timestamp - from_timestamp
        if diff < one_day or diff > thirty_days:
            print("Error: The date range must be between 1 and 30 days.")
            return

        # Get limit input and enforce allowed range (20-30)
        limit_input = input("Enter number of results to retrieve (default 5): ").strip()
        try:
            requested_limit = int(limit_input) if limit_input else 5
        except ValueError:
            requested_limit = 5

        if requested_limit < 20:
            print("Note: Limit must be between 20 and 30. Using minimum value of 20.")
            requested_limit = 20
        elif requested_limit > 30:
            print("Note: Limit must be between 20 and 30. Using maximum value of 30.")
            requested_limit = 30

        search_mentions_input = json.dumps({
            "keywords": keywords,
            "from_timestamp": from_timestamp,
            "to_timestamp": to_timestamp,
            "limit": requested_limit,
            "cursor": ""
        })
        tool = next(tool for tool in tools if tool.name == "elfa_ai_search_mentions_by_keywords")
        results["Search Mentions by Keywords"] = await tool._arun(search_mentions_input)

    elif choice == "4":
        # Get Trending Tokens
        time_window = input("Enter time window (default 24h): ").strip() or "24h"
        page = input("Enter page number (default 1): ").strip() or "1"
        page_size = input("Enter number of tokens to show (default 10): ").strip() or "10"
        min_mentions = input("Enter minimum mentions (default 5): ").strip() or "5"
        trending_tokens_input = json.dumps({
            "time_window": time_window,
            "page": int(page),
            "page_size": int(page_size),
            "min_mentions": int(min_mentions)
        })
        tool = next(tool for tool in tools if tool.name == "elfa_ai_get_trending_tokens")
        results["Trending Tokens"] = await tool._arun(trending_tokens_input)

    elif choice == "5":
        # Get Twitter Stats
        username = input("Enter Twitter username: ").strip()
        twitter_stats_input = json.dumps({
            "username": username
        })
        tool = next(tool for tool in tools if tool.name == "elfa_ai_get_smart_twitter_account_stats")
        results["Twitter Stats"] = await tool._arun(twitter_stats_input)

    else:
        print("Invalid choice!")
        return

    for name, result in results.items():
        print(f"\n{name}:\n{json.dumps(result, indent=2)}")

if __name__ == "__main__":
    asyncio.run(main())
```

## Source Files

You can find the source files for this example (including `readme.md` with setup and usage instructions) on GitHub: <https://github.com/niceberginc/agentipy/blob/main/examples/Elfaai/>


# Image Generation Example

This example demonstrates how to use the `ImageGenerator` utility within AgentiPy to create images using DALL·E. It leverages Agentipy's `SolanaAgentKit` for authentication (by holding the OpenAI API key) and asynchronous handling of the image generation request.

## Key Features of the `ImageGenerator` Tool

* **Secure Key Management**: Automatically uses the `openai_api_key` stored in a `SolanaAgentKit` instance.
* **Async-First API**: All operations use the OpenAI `AsyncOpenAI` client for non-blocking calls.
* **Flexible Models & Sizes**: Defaults to DALL·E 2 with support for 256×256, 512×512, and 1024×1024; easily switch to DALL·E 3 by adjusting the `model` parameter.
* **Robust Error Handling**: Throws descriptive errors if the API key is missing or if generation fails.

## Code (`gen_img.py`)

```python
import os
import asyncio

from agentipy.tools.create_image import ImageGenerator
from agentipy.agent import SolanaAgentKit

async def main():
    api_key = "sk-proj----"
    #api_key = os.getenv("OPENAI_API_KEY")
    if not api_key:
        raise ValueError("Please set the OPENAI_API_KEY environment variable.")

    agent = SolanaAgentKit(openai_api_key=api_key)

    prompt = "A cartoon green python snake wearing tiny glasses, typing Python code on a glowing laptop. The screen shows Solana blockchain code (e.g., 'async def transaction()') with Solana logo (purple S-shaped vortex) floating nearby. Snake’s tail forms a blockchain symbol (🔗) and a tiny SOL coin. Background: clean digital workspace with abstract crypto nodes. Style: friendly, minimalist 2D flat design with mint green and purple accents."
    size = "1024x1024"
    num_images = 1

    try:
        response = await ImageGenerator.create_image(agent, prompt, size=size, n=num_images)
        images = response.get("images", [])

        for i, url in enumerate(images, start=1):
            print(f"Image {i}: {url}")
    except Exception as err:
        print(f"Failed to generate images: {err}")

if __name__ == "__main__":
    asyncio.run(main())
```

## Source Files

You can find the source files for this example (including `readme.md` with more details on setup, configuration, and best practices) on GitHub: <https://github.com/niceberginc/agentipy/blob/main/examples/Image_Generation/>


# Langchain CoinGecko Chatbot Example

This example provides a terminal-based chatbot that interacts with the CoinGecko API using Agentipy's Langchain tools to fetch cryptocurrency data. Users can query top gainers, trending tokens, token prices, and latest pools. Results can be exported to JSON files for further analysis.

## Features

* **Fetch Data**:
  * Top gainers in the last hour.
  * Latest pools on the Solana network.
  * Token prices for specified Solana token addresses.
  * Trending tokens.
* **Export Data**:
  * Export fetched data to JSON files for offline analysis.
* **User-Friendly**:
  * Simple terminal interface with clear prompts. Requires a CoinGecko API key (Pro key for some features).

## Code (`coingecko_chatbot.py`)

```python
import asyncio
import json
import time
from agentipy.agent import SolanaAgentKit
from agentipy.langchain.coingecko import get_coingecko_tools

def initialize_solana_kit(api_key):
    return SolanaAgentKit(coingecko_api_key=api_key)

# Load all CoinGecko tools
def load_tools(solana_kit):
    return get_coingecko_tools(solana_kit)

# Export data to a JSON file
def export_data(data, filename):
    with open(filename, "w") as f:
        json.dump(data, f, indent=4)
    print(f"Data exported to {filename}")

# Chatbot interaction
async def chatbot():
    # Prompt user for CoinGecko API key
    api_key = input("Enter your CoinGecko API key: ").strip()
    solana_kit = initialize_solana_kit(api_key)
    tools = load_tools(solana_kit)

    print("Welcome to the CoinGecko Chatbot! Type 'exit' to quit.")

    while True:
        user_input = input("\nWhat would you like to know? ").strip().lower()

        if user_input == "exit":
            print("Goodbye!")
            break

        # Tool 1: Get Top Gainers
        if "top gainers" in user_input:
            gainers_tool = next(t for t in tools if t.name == "coingecko_get_top_gainers")
            gainers_input = json.dumps({"duration": "1h", "top_coins": 10})
            result = await gainers_tool._arun(gainers_input)
            print(f"🔼 Top Gainers (1h):\n{json.dumps(result, indent=4)}")
            if result.get("top_gainers") is not None:
                export = input("Export this data? (yes/no): ").strip().lower()
                if export == "yes":
                    export_data(result, "top_gainers.json")
            else:
                print("Error: Unable to fetch top gainers. Check your API key or try again later.")

        # Tool 2: Get Latest Pools
        elif "latest pools" in user_input:
            latest_pools_tool = next(t for t in tools if t.name == "coingecko_get_latest_pools")
            result = await latest_pools_tool._arun()
            print(f"💧 Latest Pools:\n{json.dumps(result, indent=4)}")
            if result.get("latest_pools") is not None:
                export = input("Export this data? (yes/no): ").strip().lower()
                if export == "yes":
                    export_data(result, "latest_pools.json")
            else:
                print("Error: Unable to fetch latest pools. Check your API key or try again later.")

        # Tool 3: Get Token Price Data
        elif "token prices" in user_input:
            price_tool = next(t for t in tools if t.name == "coingecko_get_token_price_data")
            token_addresses = input("Enter token addresses (comma-separated): ").strip().split(",")
            price_input = json.dumps({"token_addresses": token_addresses})
            result = await price_tool._arun(price_input)
            print(f"💲 Token Prices:\n{json.dumps(result, indent=4)}")
            if result.get("price_data") is not None:
                export = input("Export this data? (yes/no): ").strip().lower()
                if export == "yes":
                    export_data(result, "token_prices.json")
            else:
                print("Error: Unable to fetch token prices. Check your API key or token addresses.")

        # Tool 4: Get Trending Tokens
        elif "trending tokens" in user_input:
            trending_tokens_tool = next(t for t in tools if t.name == "coingecko_get_trending_tokens")
            result = await trending_tokens_tool._arun()
            print(f"🚀 Trending Tokens:\n{json.dumps(result, indent=4)}")
            if result.get("trending_tokens") is not None:
                export = input("Export this data? (yes/no): ").strip().lower()
                if export == "yes":
                    export_data(result, "trending_tokens.json")
            else:
                print("Error: Unable to fetch trending tokens. Check your API key or try again later.")

        else:
            print("Sorry, I don't understand that command. Try one of these:")
            print("- What are the top gainers?")
            print("- Show me the latest pools.")
            print("- Get token prices.")
            print("- What are the trending tokens?")

        time.sleep(1)

if __name__ == "__main__":
    asyncio.run(chatbot())
```

## Source Files

You can find the source files for this example (including its original `readme.md` with setup and usage instructions) on GitHub: <https://github.com/niceberginc/agentipy/blob/main/examples/langChain/CoinGecko/>


# Langchain CoinGecko Explorer Example

This example, Agentipy CoinGecko Explorer, is a simple, asynchronous tool that leverages Agentipy’s LangChain-based CoinGecko tools to fetch, process, and explore live cryptocurrency data. This tool demonstrates how to orchestrate multiple data-fetching tasks—including trending tokens, price data, detailed token info, and top gainers—using LangGraph, and how to integrate LLM analysis with OpenAI's GPT-3.5-turbo.

## Features

* **Fetch Trending Tokens:** Retrieves trending tokens data from CoinGecko.
* **Fetch Price Data:** Extracts current price data for the top 5 tokens.
* **Token Information:** Fetches detailed token info, with fallback logic if the token address is invalid.
* **Top Gainers:** Retrieves the list of tokens with the highest gains in the last 24 hours.
* **LLM Analysis:** Integrates OpenAI’s GPT-3.5-turbo to analyze token info and generate insights.
* **State Memory Logging:** Maintains a log of workflow steps for robust debugging and traceability.

## Code (`coingecko_explorer.py`)

```python
import json
import asyncio
import openai
import re
from typing import TypedDict, List, Dict, Optional, Annotated
from langgraph.graph import StateGraph
from agentipy.agent import SolanaAgentKit
from agentipy.langchain.coingecko import get_coingecko_tools

# Set your OpenAI API key here or via environment variable
openai.api_key = ""

class AgentState(TypedDict):
    memory: Annotated[List[str], "multi"]
    trending_tokens: Optional[Dict]
    price_data: Optional[Dict]
    token_info: Optional[Dict]
    top_gainers: Optional[Dict]
    token_analysis: Optional[str]

solana_kit = SolanaAgentKit(
    private_key="",  # Use your private key
    rpc_url="https://api.mainnet-beta.solana.com"
)
tools = get_coingecko_tools(solana_kit)

def extract_trending_list(trending_tokens):
    """
    Helper to extract a list of tokens from trending_tokens.
    If trending_tokens is a dict with a 'coins' key, return that list;
    otherwise, assume trending_tokens is already a list.
    """
    if isinstance(trending_tokens, dict):
        return trending_tokens.get("coins", [])
    return trending_tokens

def is_valid_solana_address(addr: str) -> bool:
    """
    Simple heuristic: Solana addresses are Base58 strings typically 32-44 characters long.
    """
    if not (32 <= len(addr) <= 44):
        return False
    valid_chars = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
    return all(c in valid_chars for c in addr)

async def fetch_trending_tokens(state: AgentState) -> AgentState:
    """Node: Fetch trending tokens"""
    tool = next(t for t in tools if t.name == "coingecko_get_trending_tokens")
    result = await tool._arun()

    state['memory'].append("Fetched trending tokens")
    state['trending_tokens'] = result['trending_tokens']
    return state

async def fetch_price_data(state: AgentState) -> AgentState:
    """Node: Fetch price data for trending tokens"""
    if not state['trending_tokens']:
        return state

    trending_list = extract_trending_list(state['trending_tokens'])
    if not trending_list:
        state['memory'].append("No tokens available for price data")
        return state

    tool = next(t for t in tools if t.name == "coingecko_get_token_price_data")
    addresses = [token["item"]["id"] for token in trending_list[:5]]
    input_json = json.dumps({"token_addresses": addresses})

    result = await tool._arun(input_json)
    state['memory'].append(f"Fetched price data for {len(addresses)} tokens")
    state['price_data'] = result['price_data']
    return state

async def fetch_token_info(state: AgentState) -> AgentState:
    """Node: Fetch info for first token"""
    if state['trending_tokens']:
        trending_list = extract_trending_list(state['trending_tokens'])
        if trending_list:
            token_item = trending_list[0]["item"]
            address = token_item.get("contract_address") or token_item.get("id")
            if not is_valid_solana_address(address):
                state['memory'].append(f"Token address '{address}' is not a valid Solana address. Using token item data instead.")
                state['token_info'] = token_item
                return state
            tool = next(t for t in tools if t.name == "coingecko_get_token_info")
            result = await tool._arun(json.dumps({"token_address": address}))
            state['memory'].append(f"Fetched token info for: {address}")
            state['token_info'] = result['token_info']
    return state

async def fetch_top_gainers(state: AgentState) -> AgentState:
    """Node: Fetch top gainers"""
    tool = next(t for t in tools if t.name == "coingecko_get_top_gainers")
    result = await tool._arun(json.dumps({"duration": "24h", "top_coins": 10}))

    state['memory'].append("Fetched top 24h gainers")
    state['top_gainers'] = result['top_gainers']
    return state

async def llm_interaction(state: AgentState) -> AgentState:
    """Node: Use OpenAI's LLM for interaction based on token info."""
    if not state['token_info']:
        state['memory'].append("No token info available to analyze with LLM.")
        return state

    prompt = f"Please analyze the following token info and provide insights:\n{json.dumps(state['token_info'], indent=2)}"

    try:
        response = await asyncio.to_thread(lambda: openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=[{"role": "user", "content": prompt}],
            temperature=0.7
        ))
        analysis = response['choices'][0]['message']['content']
        state['memory'].append("LLM analysis completed.")
        state['token_analysis'] = analysis
    except Exception as e:
        state['memory'].append(f"LLM interaction failed: {str(e)}")

    return state

# Build graph with unique node keys
graph = StateGraph(AgentState)

graph.add_node("node_trending_tokens", fetch_trending_tokens)
graph.add_node("node_price_data", fetch_price_data)
graph.add_node("node_token_info", fetch_token_info)
graph.add_node("node_top_gainers", fetch_top_gainers)
graph.add_node("node_llm_interaction", llm_interaction)

graph.set_entry_point("node_trending_tokens")
graph.add_edge("node_trending_tokens", "node_price_data")
graph.add_edge("node_price_data", "node_token_info")
graph.add_edge("node_token_info", "node_top_gainers")
graph.add_edge("node_top_gainers", "node_llm_interaction")

app = graph.compile()

async def main():
    initial_state = AgentState(
        memory=[],
        trending_tokens=None,
        price_data=None,
        token_info=None,
        top_gainers=None,
        token_analysis=None
    )
    return await app.ainvoke(initial_state)

if __name__ == "__main__":
    final_state = asyncio.run(main())

    # Print trending tokens (showing the top 5)
    trending_list = extract_trending_list(final_state['trending_tokens'])
    print("Trending Tokens:")
    for token in trending_list[:5]:
        item = token.get("item", {})
        print(f"- ID: {item.get('id')}, Name: {item.get('name')}, Symbol: {item.get('symbol')}")

    print("\nPrice Data for 5 Tokens:")
    print(json.dumps(final_state['price_data'], indent=2))

    if final_state['token_info']:
        token_info = final_state['token_info']
        minimal_info = {
            "id": token_info.get("id"),
            "name": token_info.get("name"),
            "symbol": token_info.get("symbol"),
        }
        data = token_info.get("data", {})
        if data:
            minimal_info["price"] = data.get("price")
            minimal_info["market_cap"] = data.get("market_cap")
        print("\nMinimal Final Token Info:")
        print(json.dumps(minimal_info, indent=2))

    print("\nLLM Analysis:")
    print(final_state.get("token_analysis"))

    print("\nMemory History:")
    for entry in final_state['memory']:
        print(f"- {entry}")

```

## Source Files

You can find the source files for this example (including its original `readme.md` with setup and usage instructions) on GitHub: <https://github.com/niceberginc/agentipy/blob/main/examples/langChain/Agentipy_CoinGecko_Explorer/>


# Pyth Tool Examples

These examples demonstrate how to use Agentipy's `PythManager` to fetch real-time, on-chain-verified price feeds from the Pyth Network. The tool supports all Pyth Network price feeds and provides prices with confidence intervals.

## Features

* **Agentipy-Compatible**: Seamlessly integrates as a tool within the Agentipy framework.
* **Async-First**: Fully asynchronous implementation for non-blocking performance.
* **All Feeds Supported**: Works with every Pyth Network price feed.
* **Robust Error Handling**: Graceful fallbacks for network issues and invalid addresses.
* **Confidence Reporting**: Returns price with ±confidence interval for data quality checks.
* **Auto Connection Management**: Opens and closes RPC connections automatically.

## Code

### `main1.py` (Basic Price Fetching)

This script fetches multiple Pyth feeds concurrently and prints their prices along with confidence intervals.

```python
import asyncio
from agentipy.tools.use_pyth import PythManager

PYTH_FEEDS = {
    "SOL/USD": "H6ARHf6YXhGYeQfUzQNGk6rDNnLBQKrenN712K4AQJEG",
    "BTC/USD": "GVXRSBjFk6e6J3NbVPXohDJetcTjaeeuykUpbQF8UoMU",
    "AAVE/USD": "3wDLxH34Yz8tGjwHszQ2MfzHwRoaQgKA32uq2bRpjJBW",
    "AEVO/USD": "26emwftTvy4CcXUcPYCHF9PcPHar4kYKfzwM1onYHBCN"
}

async def fetch_all():
    async def one(symbol, addr):
        data = await PythManager.get_price(addr)
        if data["status"] == "TRADING":
            print(f"{symbol}: ${data['price']:.4f} ±${data['confidence_interval']:.4f}")
        else:
            print(f"{symbol}: {data['status']} — {data.get('message','')}")
    await asyncio.gather(*(one(s, a) for s, a in PYTH_FEEDS.items()))

if __name__ == "__main__":
    asyncio.run(fetch_all())
```

### `main2.py` (Langchain Integration for Market Analysis)

This script combines Pyth price feeds with a LangChain/OpenAI agent for automated market analysis. It allows users to input a token (predefined like BTC, SOL, ETH, or a custom Pyth feed address) and get an analysis that combines on-chain price data with market news from DuckDuckGo search.

```python
import asyncio
import os
from dotenv import load_dotenv
from agentipy.tools.use_pyth import PythManager
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain.agents import Tool, AgentExecutor, create_openai_tools_agent
from langchain_community.tools import DuckDuckGoSearchRun
from pythclient.pythaccounts import PythPriceAccount, PythPriceStatus
from pythclient.solana import SolanaClient, SolanaPublicKey

load_dotenv()

api_key = os.getenv("OPENAI_API_KEY")
if api_key is None:
    raise RuntimeError(
        "Environment variable OPENAI_API_KEY is not set. "
        "Please add it to your .env file or export it in your shell."
    )

os.environ["OPENAI_API_KEY"] = api_key

PYTHNET_ENDPOINT = "https://pythnet.rpcpool.com/"
VALID_FEEDS_URL = "https://pyth.network/developers/price-feed-ids"

PREDEFINED_FEEDS = {
    "sol": ("SOL/USD", "H6ARHf6YXhGYeQfUzQNGk6rDNnLBQKrenN712K4AQJEG"),
    "btc": ("BTC/USD", "GVXRSBjFk6e6J3NbVPXohDJetcTjaeeuykUpbQF8UoMU"),
    "eth": ("ETH/USD", "JBu1AL4obBcCMqKBBxhpWCNUt136ijcuMZLFvTP7iWdB"),
}

async def validate_mint_address(mint_address: str) -> bool:
    """Validate Pyth network mint address via on-chain status check."""
    client = SolanaClient(endpoint=PYTHNET_ENDPOINT)
    try:
        account = PythPriceAccount(SolanaPublicKey(mint_address), client)
        await account.update()
        return account.aggregate_price_status == PythPriceStatus.TRADING
    except Exception:
        return False
    finally:
        await client.close()

async def analyze_token():
    llm = ChatOpenAI(model="gpt-4-turbo", temperature=0.7)
    search = DuckDuckGoSearchRun()

    tools = [
        Tool(
            name="MarketSearch",
            func=search.run,
            description="Search for latest cryptocurrency news and market trends"
        )
    ]

    # Agent prompt setup
    prompt = ChatPromptTemplate.from_messages([
        ("system", """Analyze cryptocurrency prices using:
        1. Verified on-chain data from Pyth Network
        2. Latest market developments
        Provide: Technical analysis, risk assessment, and short-term prediction"""),
        ("user", "{input}"),
        MessagesPlaceholder(variable_name="agent_scratchpad"),
    ])

    agent = create_openai_tools_agent(llm, tools, prompt)
    executor = AgentExecutor(agent=agent, tools=tools, verbose=False)

    token = input("Enter token (btc/sol/eth) or 'custom': ").lower()

    if token == "custom":
        symbol = input("Symbol (e.g. XYZ/USD): ").strip()
        mint_address = input("Pyth mint address: ").strip()

        is_valid = await validate_mint_address(mint_address)
        if not is_valid:
            print(f"Invalid Pyth feed address. Check valid feeds at:\n{VALID_FEEDS_URL}")
            return
    else:
        try:
            symbol, mint_address = PREDEFINED_FEEDS[token]
        except KeyError:
            print(f"Available tokens: {', '.join(PREDEFINED_FEEDS.keys())}")
            return

    print(f"\n🔍 Fetching {symbol} data...")
    try:
        price_data = await PythManager.get_price(mint_address)

        if price_data["status"] != "TRADING":
            raise ValueError(f"Price feed not active: {price_data['status']}")

        analysis = await executor.ainvoke({
            "input": f"""Analyze {symbol} with:
            - Current Price: ${price_data['price']:,.4f}
            - Confidence Interval: ±${price_data['confidence_interval']:,.4f}
            Provide comprehensive market analysis"""
        })

        print(f"\n {symbol} Analysis")
        print(f"• Current Price: ${price_data['price']:,.4f}")
        print(f"• Confidence Range: ±${price_data['confidence_interval']:,.4f}")
        print(f"\n Market Insights:\n{analysis['output']}")

    except Exception as e:
        print(f"\n Analysis failed: {str(e)}")
        web_results = search.run(f"{symbol} cryptocurrency latest news")
        print(f"\n Latest Web Results:\n{web_results[:500]}...")

if __name__ == "__main__":
    asyncio.run(analyze_token())
```

## Source Files

You can find the source files for this example (including its original `readme.md` with setup and usage instructions) on GitHub: <https://github.com/niceberginc/agentipy/blob/main/examples/pyth_tool/>


# RugCheck CLI Example

The **RugCheck CLI Tool** is a command-line interface (CLI) application that allows users to fetch and display RugCheck reports for Solana tokens by entering their Contract Address (CA). The tool uses Agentipy's `RugCheckManager` (which wraps the RugCheck API) to provide detailed information about a token's risks, score, and LP lockers.

## Features

* **Fetch RugCheck Reports**:
  * Get a summary report for a token, including its risk score, identified risks, and creator tokens.
* **Fetch LP Lockers**:
  * Retrieve information about the token's LP (Liquidity Pool) lockers and total locked value.
* **User-Friendly Output**:
  * Display results in an easy-to-read format.
* **Error Handling**:
  * Provide clear error messages for invalid inputs or API issues.

## Code (`rugcheck_cli.py`)

```python
import asyncio
from agentipy.tools.rugcheck import RugCheckManager

async def main():
    api_key = "YOUR_API_KEY"  # Replace with your actual RugCheck API key
    rugcheck = RugCheckManager(api_key)

    print("Enter the Contract Address (CA) of the token.")
    print("Example CA: So11111111111111111111111111111111111111112 (Wrapped SOL)")
    user_input = input("Your input: ").strip()

    try:
        print("\nFetching RugCheck report...\n")

        report = await rugcheck.fetch_token_report_summary(user_input)
        print(report.to_user_friendly_string())

        lockers = await rugcheck.fetch_token_lp_lockers(user_input)
        print("\n" + lockers.to_user_friendly_string())

    except Exception as e:
        print(f"\nError: {e}")
        print("Please ensure you entered a valid Contract Address (CA).")
        print("Example CA: So11111111111111111111111111111111111111112 (Wrapped SOL)")

if __name__ == "__main__":
    asyncio.run(main())
```

**Note:** You need to replace `"YOUR_API_KEY"` in the script with your actual RugCheck API key for the example to work. Some RugCheck endpoints might work without an API key but could be rate-limited or offer less data.

## Source Files

You can find the source files for this example (including its original `readme.md` with setup and usage instructions) on GitHub: <https://github.com/niceberginc/agentipy/blob/main/examples/rugCheck/>


# Integrations

Discover how AgentiPy simplifies AI agent development on Solana through powerful SDK integrations. Learn about our ready-to-use LangChain tools and get a roadmap for upcoming native support for CrewAI

AgentiPy provides seamless integration with various AI and blockchain SDKs, starting with LangChain. This current integration enables AI agents to interact with a wide range of Solana-based protocols and services, empowering developers to effortlessly build sophisticated AI-driven blockchain applications

**Supported Integrations**

We offer out-of-the-box support for various SDKs. All you need to do is incorporate the pre-built tools; no additional configuration or custom code is required from you.&#x20;

<table data-card-size="large" data-view="cards"><thead><tr><th></th><th data-hidden data-card-target data-type="content-ref"></th><th data-hidden data-card-cover data-type="files"></th></tr></thead><tbody><tr><td> <strong>LangChain:</strong> We offer <strong>out-of-the-box, pre-configured tooling for LangChain</strong>. All you need to do is incorporate the pre-built AgentiPy tools and call them; no manual configuration or extensive custom code is required from you.</td><td><a href="/pages/AT8MYKrPbq8GslrpYmMT">/pages/AT8MYKrPbq8GslrpYmMT</a></td><td><a href="/files/5F3hUUmpA5j10qcyeNvK">/files/5F3hUUmpA5j10qcyeNvK</a></td></tr></tbody></table>

**Coming Soon: Expanded Tooling & Support**

We are actively working to expand our **pre-configured and highly simplified tooling** to include more of your favorite AI SDKs. While full AgentiPy tool integration (requiring just a tool call) is under development, you can still use these SDKs by writing your own agent code:<br>

* [**CrewAI:** Integrate CrewAI for collaborative AI agent frameworks.](/integrations/crewai)
* [**Google SDK:** Access Google's AI services and APIs within your Solana applications.](/integrations/google-adk)
* [**OpenAI SDK:** Connect to OpenAI's powerful models and services.](/integrations/openai)

\
Stay tuned for updates that will further simplify the integration of these platforms!


# Langchain

## AgentiPy Integrations: LangChain

AgentiPy seamlessly integrates with LangChain, empowering your AI agents to perform complex operations directly on the Solana blockchain. This integration provides **out-of-the-box, pre-configured tooling** that simplifies the development of sophisticated AI-driven decentralized applications (dApps).

This document outlines how to set up and use AgentiPy's LangChain integration to build a console-based Solana blockchain assistant.

### Key Features

* **Pre-configured Tools:** Access Solana blockchain functionalities as readily available LangChain tools.
* **Low-Code Integration:** Focus on your agent's logic, not boilerplate code for blockchain interactions.
* **AI-Powered Blockchain Operations:** Leverage Large Language Models (LLMs) to intelligently select and execute Solana functions based on natural language queries.
* **Console Application Ready:** Easily demonstrate and test blockchain operations directly from your terminal.

### Prerequisites

Before you begin, ensure you have the following:

1. **Python 3.9+:** Installed on your system.
2. **Solana Wallet Private Key:** A base58-encoded private key for a Solana wallet with some SOL (for gas fees) and potentially other tokens you wish to interact with.
   * **Important:** For development and testing, it's highly recommended to use a **devnet private key** and devnet SOL. **Never use your mainnet private key for testing or in insecure environments.**
3. **OpenAI API Key:** An API key from OpenAI to use their `gpt-4o-mini` model.

### Installation

You'll need to install AgentiPy, LangChain, OpenAI's Python client, and `python-dotenv`:

```bash
pip install agentipy langchain-openai langgraph python-dotenv
```

### Setup Environment Variables

Create a file named `.env` in the root directory of your project (where your Python script will be located). Add your private key and OpenAI API key to this file:

```dotenv
SOLANA_PRIVATE_KEY="YOUR_BASE58_ENCODED_SOLANA_PRIVATE_KEY"
OPENAI_API_KEY="YOUR_OPENAI_API_KEY"
```

Replace `"YOUR_BASE58_ENCODED_SOLANA_PRIVATE_KEY"` and `"YOUR_OPENAI_API_KEY"` with your actual keys.

### Code Explanation: Solana Blockchain Assistant

The following Python script demonstrates a console-based AI assistant powered by AgentiPy's LangChain integration. It uses `langgraph` to create an agent that can dynamically call Solana-related tools based on user input.

```python
import asyncio
import os
import json
from dotenv import load_dotenv

# AgentiPy and LangChain imports
from agentipy.agent import SolanaAgentKit
from agentipy.langchain.core import get_all_core_tools
from langchain_openai import ChatOpenAI
from langchain_core.messages import SystemMessage, HumanMessage
from langgraph.graph import MessagesState
from langgraph.graph import StateGraph
from langgraph.prebuilt import ToolNode
from langgraph.prebuilt import tools_condition
from langgraph.graph import START

# Load environment variables
load_dotenv()

# --- Solana Agent and LLM Setup ---
# Initialize Solana agent with your private key and desired RPC endpoint.
# 'https://api.mainnet-beta.solana.com' is used here, but 'https://api.devnet.solana.com'
# is recommended for testing.
agent = SolanaAgentKit(
    os.getenv("SOLANA_PRIVATE_KEY"),
    "https://api.mainnet-beta.solana.com"
)

# AgentiPy provides pre-built tools compatible with LangChain.
# get_all_core_tools() retrieves functions like checking balance, creating tokens, etc.
tools = [*get_all_core_tools(solana_kit=agent)]

# Initialize the Language Model (LLM).
# The llm_with_tools is a bound version of the LLM that's aware of the available tools.
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
llm_with_tools = llm.bind_tools(tools)

# Define the system message. This guides the AI's behavior and response format.
# It emphasizes blockchain operations and specific output formatting.
sys_msg = SystemMessage(
    content="""You are an AI assistant specializing in blockchain-related operations. You help users with Solana blockchain tasks such as checking wallet balances, creating tokens, retrieving token prices, and other blockchain operations.

When responding, please follow this format:

📋 OPERATION:
[Brief description of what's being done]

🔍 DETAILS:
[Relevant information and data]

💡 RESULT:
[Final outcome or response]

📝 NOTE:
[Any additional information or recommendations, if applicable]

Remember:
1. All function inputs must be formatted as a JSON string, ensuring proper escaping. Examples:
   - "{"name":"test","surname":"test"}"
   - "{"amount":100,"recipient":"abc123"}"
   - "{"token":"USDT"}"

2. Always return valid JSON objects inside strings
3. Keys must be strings, values properly formatted (numbers as integers, booleans as true/false)
4. Escape necessary characters for valid JSON
5. For non-blockchain requests, respond with:
   "I'm sorry, I can only assist with blockchain-related operations."
"""
)

# --- LangGraph Setup ---
# The assistant function defines how the LLM processes messages within the graph.
# It invokes the LLM with the system message and the current conversation history.
def assistant(state: MessagesState):
    """
    Invokes the LLM with the current state messages and system message.
    """
    return {"messages": [llm_with_tools.invoke([sys_msg] + state["messages"])]}

# Initialize LangGraph's StateGraph to build the agent's workflow.
builder = StateGraph(MessagesState)

# Add nodes to the graph:
# 'assistant': Calls the LLM to determine the next action (respond or call a tool).
# 'tools': Executes the chosen LangChain tool.
builder.add_node("assistant", assistant)
builder.add_node("tools", ToolNode(tools))

# Define the graph's flow:
# START -> 'assistant': The conversation always begins with the assistant.
builder.add_edge(START, "assistant")

# Conditional edges from 'assistant':
# 'tools_condition' from langgraph determines if the LLM wants to call a tool.
# If so, the flow goes to 'tools'; otherwise, it remains with 'assistant' to generate a final response.
builder.add_conditional_edges(
    "assistant",
    tools_condition, # Condition to check if LLM wants to use a tool
)

# 'tools' -> 'assistant': After a tool is executed, the result is fed back to the assistant
# for it to process the output and formulate a user-friendly response.
builder.add_edge("tools", "assistant")

# Compile the graph, making it ready to be invoked.
graph = builder.compile()

# --- Response Extraction Logic ---
# Helper function to parse the AI's potentially multi-part response into a clean answer.
def extract_answer(response_text: str) -> str:
    """
    Extracts the most relevant answer from the AI's response based on the
    defined format. Prioritizes '💡 RESULT:' section or JSON outputs.
    """
    try:
        lines = response_text.split("\n")
        for line in lines:
            if line.strip().startswith("{") and line.strip().endswith("}"):
                data = json.loads(line.strip())
                if data.get("status") == "success":
                    if "balance" in data:
                        return f"Balance: {data['balance']} {data.get('token', 'SOL')}"
                    return str(data)
    except json.JSONDecodeError:
        pass
    except Exception as e:
        print(f"Error parsing potential JSON: {e}")

    sections = response_text.split("\n\n")
    for section in sections:
        if section.startswith("💡 RESULT:"):
            return section.replace("💡 RESULT:", "").strip()

    for line in response_text.split("\n"):
        if line.strip() and not line.startswith(("📋", "🔍", "💡", "📝")):
            return line.strip()

    return response_text.strip()

# --- Console Application Logic ---
# The main asynchronous function for the console application.
async def main():
    """
    Main function to run the console application.
    Prompts the user for a question, processes it, and prints the response.
    """
    print("Welcome to the Solana Blockchain Assistant!")
    print("Type 'exit' to quit.")

    while True:
        question_input = input("\nYour question: ").strip()
        if question_input.lower() == 'exit':
            print("Goodbye!")
            break

        if not question_input:
            print("Please enter a question.")
            continue

        try:
            # Wrap the user's question in a HumanMessage.
            messages = [HumanMessage(content=question_input)]
            # Invoke the compiled LangGraph with the user's message.
            result = await graph.ainvoke({"messages": messages})

            # Process the response messages from the graph.
            response_text = ""
            for m in result["messages"]:
                if hasattr(m, "content") and m.content:
                    response_text += f"{m.content}\n"
                elif hasattr(m, "tool_calls") and m.tool_calls:
                    response_text += "Performing blockchain operations via tool call...\n"
                elif hasattr(m, "tool_outputs") and m.tool_outputs:
                    response_text += f"Tool Output: {m.tool_outputs}\n"

            # Extract and print the simplified answer.
            answer = extract_answer(response_text.strip())
            print(f"\nAI Assistant: {answer}")

        except Exception as e:
            print(f"\nAn error occurred: {e}")
            print("Please ensure your environment variables are correctly set and the Solana node is accessible.")

if __name__ == "__main__":
    # Essential for asyncio on Windows to prevent runtime errors.
    if os.name == "nt":
        asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

    # Run the main console application.
    asyncio.run(main())
```

### How to Run

1. **Save the code:** Save the script above as `solana_assistant.py` (or any other `.py` file).
2. **Ensure `.env` file exists:** Make sure your `.env` file is in the same directory as `solana_assistant.py` and contains your `SOLANA_PRIVATE_KEY` and `OPENAI_API_KEY`.
3. **Run from terminal:** Open your terminal or command prompt, navigate to the directory where you saved the file, and run:

   ```bash
   python solana_assistant.py
   ```

The assistant will start and prompt you for input.

### Example Usage

Once the application is running, you can type questions into the console:


# CrewAi

### Integration of Agentipy with crewAI

This serves as a practical example of how to integrate **Agentipy** toolkit with the crewAI multi-agent framework. The integration showcases:

1. **Bringing Blockchain to AI Agents**: How to equip AI agents with blockchain capabilities through Agentipy
2. **Tool Integration**: How to wrap agentipy functionality as crewAI tools
3. **Configuration-Driven Design**: Using YAML files to configure blockchain agents

**Integration Pattern**

The integration follows this pattern:

```python
# 1. Import both libraries
from crewai import Agent, Crew, Task
from agentipy.agent import SolanaAgentKit

# 2. Create a Solana kit instance
solana_kit = SolanaAgentKit(
    private_key=os.getenv("SOLANA_PRIVATE_KEY"),
    rpc_url="https://api.devnet.solana.com"
)

# 3. Create tools from agentipy capabilities
@tool("get_sol_balance")
def get_sol_balance() -> str:
    # Use agentipy BalanceFetcher to get blockchain data
    balance = loop.run_until_complete(BalanceFetcher.get_balance(agent))
    return f"The current SOL balance is {balance:.4f} SOL"

# 4. Attach tools to crewAI agents
solana_agent = Agent(
    config=agents_config["solana_operator"],
    tools=[make_balance_tool(agent=solana_kit)],
    llm=ChatOpenAI(model=os.getenv("MODEL"), temperature=0)
)

# 5. Create tasks using these agents
solana_task = Task(
    description="Analyze instruction and take action: {user_input}",
    agent=solana_agent
)

# 6. Orchestrate with crewAI
crew = Crew(
    agents=[solana_agent],
    tasks=[solana_task],
    process=Process.sequential
)
```

This pattern demonstrates how to leverage both frameworks' strengths:

* agentipy provides blockchain interaction capabilities
* crewAI provides agent orchestration, task management, and goal-oriented behavior

### Architecture

The repository is structured as follows:

```
src/solana_agent_agentipy/
├── config/
│   ├── agents.yaml         # Agent configuration definitions
│   └── tasks.yaml          # Task configuration definitions
├── tools/
│   ├── custom_tool.py      # Custom tools for the Solana agent
│   └── __init__.py
├── crew.py                 # Main crew definition and orchestration
├── main.py                 # Entry point for running the system
└── __init__.py
```

#### Components

**1. SolanaWalletCrew**

The core component of the system is the `SolanaWalletCrew` class defined in `crew.py`. This class:

* Initializes a SolanaAgentKit with provided credentials
* Defines the Solana agent's capabilities and tools
* Sets up tasks for the agent to perform
* Orchestrates the execution flow in a sequential process

**2. Custom Tools**

The `custom_tool.py` file defines tools that the agent can use to interact with the Solana blockchain, such as:

* `get_sol_balance`: A tool to fetch and display the current SOL balance of the wallet

**3. Configuration**

The system uses YAML configuration files to define:

* **agents.yaml**: Defines the Solana operator agent's role, goals, and backstory
* **tasks.yaml**: Defines the operations to be performed based on user input

### Setup and Installation

#### Prerequisites

* Python >=3.10 <3.13
* [UV](https://docs.astral.sh/uv/) for dependency management

#### Installation Steps

1. Install UV if not already installed:

```bash
pip install uv
```

2. Clone the repository and navigate to the project directory
3. Install dependencies (using the crewAI CLI):

```bash
crewai install
```

4. Create a `.env` file with the following variables:

```
OPENAI_API_KEY=your_openai_api_key
SOLANA_PRIVATE_KEY=your_solana_private_key
MODEL=gpt-4-turbo
```

### Usage

Run the project from the root folder with:

```bash
crewai run
```

Example input:

```
"Check my balance and send 1 SOL if I'm above $1000"
```

This will:

1. Initialize the SolanaWalletCrew
2. Process the natural language input
3. Check the current SOL balance using the Solana blockchain
4. Analyze if conditional requirements are met
5. Execute the requested operations if conditions are satisfied

### Customization

The system is designed to be easily customizable:

1. **Adding New Agents**: Modify the `agents.yaml` file to define additional agents with different roles and capabilities
2. **Defining New Tasks**: Update the `tasks.yaml` file to create new task definitions for your agents
3. **Creating Custom Tools**: Extend the tools available to your agents by adding new tools in the `tools/` directory
4. **Custom Logic**: Modify the `crew.py` file to implement custom logic, additional tools, or specific arguments

### Integration with agentipy

This project leverages the [agentipy](broken://pages/r0DCOLHmlYFU4378HzB8) library to interact with the Solana blockchain, providing:

* Wallet management
* Balance fetching
* Transaction capabilities

### Dependencies

* crewAI: Framework for creating and orchestrating AI agent systems
* agentipy: Solana blockchain interaction toolkit
* langchain-openai: LLM integration for natural language processing
* python-dotenv: Environment variable management

### Advanced Use Cases

The system can be extended to support:

* Multi-token wallet management
* Complex conditional operations
* Integration with other blockchain operations
* Custom token transfers and transactions

### Troubleshooting

If you encounter issues:

* Ensure your Solana private key is valid and has funds on the devnet
* Verify your OpenAI API key is correctly set and has sufficient credits
* Check that you're using the correct Solana RPC URL (default is devnet)


# OpenAI

AgentiPy provides seamless integration with OpenAI's function calling capabilities, allowing you to create AI agents that can interact with the Solana blockchain. This integration enables developers to build sophisticated AI-driven blockchain applications with natural language interfaces.

### 🚀 Quick Start

```python
import asyncio
from agentipy.agent import SolanaAgentKit
from agents import Agent, Runner, function_tool
from agentipy.tools.get_balance import BalanceFetcher
from rich.console import Console
from rich.panel import Panel
from rich.prompt import Prompt
from solders.pubkey import Pubkey
import os

# Initialize Rich console
console = Console()

# Initialize Solana agent
solana_agent = SolanaAgentKit(
    private_key=os.getenv("PRIVATE_KEY"),
    rpc_url="https://api.mainnet-beta.solana.com"
)

# Create function tools
@function_tool
async def check_sol_balance() -> str:
    """Get the SOL balance for the current wallet."""
    balance = await BalanceFetcher.get_balance(solana_agent)
    return f"SOL balance: {balance} SOL"

# Initialize OpenAI agent
agent = Agent(
    name="Solana Assistant",
    instructions="You are a Solana blockchain assistant that can check balances.",
    tools=[check_sol_balance],
)

# Run the agent
result = await Runner.run(agent, input="Check my SOL balance")
```

### 🛠️ Key Components

#### 1. Function Tools

Function tools are the building blocks of your AI agent's capabilities. They are decorated with `@function_tool` and define the actions your agent can perform.


# Google ADK

## Integrating Google ADK with Agentipy

This guide demonstrates how to integrate Google's Agent Development Kit (ADK) with Agentipy to create intelligent agents that can interact with blockchain networks.

### Prerequisites

* Python 3.9+
* A Solana wallet private key
* Google API key

### Setup

1. **Install required packages**

```bash
pip install agentipy google-adk python-dotenv
```

2. **Create an environment file**

Create a `.env` file in your project root with the following variables:

```
PRIVATE_KEY=your_solana_private_key
GOOGLE_GENAI_USE_VERTEXAI=FALSE
GOOGLE_API_KEY=your_google_api_key
```

### Folder Structure

```
.
├── agent/
│   ├── __init__.py     # Agent configuration definitions
│   └── agent.py        # Task configuration definitions
└── .env
```

#### Basic Structure

The integration follows these key steps:

1. Create your AgentiPy kit for the specific blockchain
2. Define domain-specific tools/functions
3. Create a Google LlmAgent and provide your tools
4. Set the LlmAgent as your root agent

#### Example: Solana Balance Checker

```python
from agentipy.agent import SolanaAgentKit
from agentipy.tools.get_balance import BalanceFetcher
import os
from dotenv import load_dotenv
from google.adk.agents import LlmAgent
from google.adk.agents import Agent
from typing import Optional

# Load environment variables
load_dotenv()

# Initialize Solana agent kit
agent = SolanaAgentKit(
    private_key=os.getenv("PRIVATE_KEY"),
    rpc_url="https://api.mainnet-beta.solana.com"  # Mainnet RPC endpoint
)

# Define a tool/function for your agent
async def get_balance(token_address: Optional[str] = None) -> str:
    """Get the current balance of the wallet.
    Args:
        token_address (Optional[str]): The token address to get the balance of.
    Returns:
        str: The balance of the wallet.
    """
    try:
        balance = await BalanceFetcher.get_balance(agent, token_address)
        return f"Current balance: {balance}"
    except Exception as e:
        return f"Error getting balance: {str(e)}"

# Create a Google LlmAgent with your tool
check_balance = LlmAgent(
    name="Check_Balance",
    description="Check the balance of the wallet for a specific token or SOL",
    tools=[get_balance],
    model="gemini-2.0-flash",
)

# Set as root agent
root_agent = check_balance
```

### Running Your Agent

Create a file named `main.py` to run your agent:

To ensure proper execution, utilize either `adk web` or `adk run` commands. Confirm execution from the root folder

```
// adk run or adk web 
```

### Extending Your Agent

You can add more tools to your agent by:

1. Creating additional functions that use the AgentiPy kit
2. Adding these functions to your LlmAgent's tools list

Example of adding a token transfer tool:

```python
async def transfer_token(recipient: str, amount: float, token_address: Optional[str] = None) -> str:
    """Transfer tokens to another wallet.
    Args:
        recipient (str): The recipient's wallet address.
        amount (float): The amount to transfer.
        token_address (Optional[str]): The token address to transfer. Default is SOL.
    Returns:
        str: The transaction result.
    """
    try:
        # Implement transfer logic using AgentiPy
        return f"Transferred {amount} to {recipient}"
    except Exception as e:
        return f"Error transferring tokens: {str(e)}"

# Update your agent with multiple tools
wallet_agent = LlmAgent(
    name="Wallet_Agent",
    description="Manage wallet balance and transfers",
    tools=[get_balance, transfer_token],
    model="gemini-2.0-flash",
)
```

### Best Practices

1. **Error Handling**: Always include proper error handling in your tool functions
2. **Documentation**: Provide clear docstrings for all tools
3. **Environment Variables**: Keep sensitive information in environment variables
4. **Modular Design**: Create specific agents for different functionalities
5. **Testing**: Test your agents with various inputs before deployment

### Resources

* [Google ADK Documentation](https://google.github.io/adk-docs/)
* [AgentiPy Documentation](https://agentipy.fun/)


# OmniCoreAgent

AgentiPy provides seamless integration with the OmniAgent framework, allowing you to create AI agents that can interact with the Solana blockchain through natural language interfaces. This integration enables developers to build sophisticated AI-driven blockchain applications with conversational capabilities, real-time event streaming, and robust memory management.

## 🚀 Quick Start

```python
import asyncio
from mcpomni_connect.omni_agent import OmniAgent
from mcpomni_connect.memory_store.memory_router import MemoryRouter
from mcpomni_connect.events.event_router import EventRouter
from mcpomni_connect.agents.tools.local_tools_registry import ToolRegistry
from agentipy.agent import SolanaAgentKit
from agentipy.tools.get_balance import BalanceFetcher
from agentipy.tools.transfer import TokenTransferManager
from dotenv import load_dotenv
from typing import Optional
import os

load_dotenv()

# Initialize Solana agent
solana_agent = SolanaAgentKit(
    private_key=os.getenv("SOLANA_PRIVATE_KEY"),
    rpc_url="https://api.mainnet-beta.solana.com"
)

# Create tool registry
async def create_tool_registry() -> ToolRegistry:
    """Create a tool registry with Solana operations."""
    tool_registry = ToolRegistry()

    @tool_registry.register_tool("get_balance_solana")
    async def get_balance(address: Optional[str] = None) -> str:
        """Get the balance of a Solana address."""
        try:
            balance_sol = await BalanceFetcher.get_balance(
                solana_agent, 
                token_address=address
            )
            return {"status": "success", "data": balance_sol}
        except Exception as e:
            return {"status": "error", "message": str(e)}

    @tool_registry.register_tool("transfer_solana")
    async def transfer_solana(address: str, amount: float) -> str:
        """Transfer SOL to a Solana address."""
        try:
            sig = await TokenTransferManager.transfer(
                solana_agent, 
                to=address, 
                amount=amount
            )
            return {
                "status": "success",
                "message": "SOL transferred successfully",
                "signature": sig
            }
        except Exception as e:
            return {"status": "error", "message": str(e)}
    
    return tool_registry

# Initialize memory and event systems
memory_store = MemoryRouter(memory_store_type="in_memory")
event_router = EventRouter(event_store_type="in_memory")

# Create the OmniAgent
async def create_agent():
    tool_registry = await create_tool_registry()
    
    agent = OmniAgent(
        name="solana_agent",
        system_instruction="""
You are a Solana agent with the ability to check balances and transfer SOL.

CRITICAL RULES:
- Always check balance before transfers using get_balance_solana
- Verify sufficient funds before calling transfer_solana
- Only use available tools in the registry
        """,
        model_config={
            "provider": "openai",
            "model": "gpt-4.1",
            "temperature": 0.7,
            "max_context_length": 50000,
        },
        local_tools=tool_registry,
        agent_config={
            "max_steps": 15,
            "tool_call_timeout": 60,
            "request_limit": 1000,
            "memory_config": {"mode": "token_budget", "value": 10000},
        },
        memory_store=memory_store,
        event_router=event_router,
        debug=True,
    )
    
    return agent

# Run the agent
async def main():
    agent = await create_agent()
    
    # Check balance
    response = await agent.run(
        "What's my SOL balance?",
        session_id="session_001"
    )
    print(response)
    
    # Transfer SOL
    response = await agent.run(
        "Transfer 0.5 SOL to <address>",
        session_id="session_001"
    )
    print(response)

asyncio.run(main())
```

## 🛠️ Key Components

{% stepper %}
{% step %}

### Tool Registry

The `ToolRegistry` is the foundation of your agent's capabilities. It manages all the tools (functions) that your AI agent can execute.

```python
tool_registry = ToolRegistry()

@tool_registry.register_tool("tool_name")
async def tool_function(param: str) -> dict:
    """Tool description that the AI will use to understand when to call this."""
    # Your implementation
    return {"status": "success", "data": result}
```

Key Features:

* Automatic function registration
* Type hints for parameter validation
* Docstrings used by AI for tool selection
* Async/await support
  {% endstep %}

{% step %}

### OmniAgent Configuration

The `OmniAgent` is the core component that orchestrates AI reasoning, tool execution, and memory management.

```python
agent = OmniAgent(
    name="agent_name",
    system_instruction="Detailed instructions for the AI...",
    model_config={
        "provider": "openai",  # or "anthropic", "google"
        "model": "gpt-4.1",
        "temperature": 0.7,
        "max_context_length": 50000,
    },
    local_tools=tool_registry,
    agent_config={
        "max_steps": 15,              # Maximum reasoning steps
        "tool_call_timeout": 60,       # Timeout per tool call
        "request_limit": 1000,         # Rate limiting
        "memory_config": {
            "mode": "token_budget",    # or "sliding_window"
            "value": 10000
        },
    },
    memory_store=memory_store,
    event_router=event_router,
    debug=True,
)
```

Configuration Options:

| Parameter            | Description            | Default  |
| -------------------- | ---------------------- | -------- |
| `name`               | Agent identifier       | Required |
| `system_instruction` | AI behavior guidelines | Required |
| `model_config`       | LLM configuration      | Required |
| `local_tools`        | Tool registry          | None     |
| `agent_config`       | Execution settings     | {}       |
| `memory_store`       | Conversation memory    | None     |
| `event_router`       | Event tracking         | None     |
| `debug`              | Enable debug logging   | False    |
| {% endstep %}        |                        |          |

{% step %}

### Memory Management

The memory system maintains conversation context across interactions:

```python
# In-memory storage (development)
memory_store = MemoryRouter(memory_store_type="in_memory")

# Persistent storage (production)
memory_store = MemoryRouter(
    memory_store_type="redis",
    redis_config={
        "host": "localhost",
        "port": 6379,
        "db": 0
    }
)
```

Memory Modes:

* `token_budget`: Maintains last N tokens of conversation
* `sliding_window`: Keeps last N messages
  {% endstep %}

{% step %}

### Event Streaming

Events provide real-time visibility into agent operations:

```python
event_router = EventRouter(event_store_type="in_memory")

# Stream events from a session
async for event in agent.stream_events(session_id):
    print(f"Event: {event.type}")
    print(f"Data: {event.data}")
```

Event Types:

* `agent.start` - Agent begins processing
* `tool.call` - Tool execution started
* `tool.result` - Tool execution completed
* `agent.response` - Agent generates response
* `agent.error` - Error occurred
  {% endstep %}
  {% endstepper %}

## 🌐 FastAPI Integration

Create a production-ready API service:

```python
from fastapi import FastAPI, Request
from fastapi.responses import StreamingResponse
from contextlib import asynccontextmanager

@asynccontextmanager
async def lifespan(app: FastAPI):
    # Initialize agent on startup
    app.state.agent = await create_agent()
    yield
    # Cleanup on shutdown
    await app.state.agent.cleanup()

app = FastAPI(lifespan=lifespan)

@app.post("/chat")
async def chat(message: str, session_id: str = None):
    agent = app.state.agent
    response = await agent.run(message, session_id)
    return response

@app.get("/events/{session_id}")
async def get_events(session_id: str):
    agent = app.state.agent
    async def event_generator():
        try:
            async for event in agent.stream_events(session_id):
                yield f"event: {event.type}\ndata: {event.json()}\n\n"
        except Exception as e:
            yield f"error: {str(e)}\n\n"
    
    return StreamingResponse(
        event_generator(), 
        media_type="text/event-stream"
    )
```

## 📋 Available Tools

### Get Balance

Check the SOL balance of any Solana address:

```python
@tool_registry.register_tool("get_balance_solana")
async def get_balance(address: Optional[str] = None) -> dict:
    """
    Get the balance of a Solana address.
    If no address is provided, returns the agent's wallet balance.
    
    Args:
        address: Optional Solana address to check
        
    Returns:
        Dictionary with status and balance data
    """
    balance = await BalanceFetcher.get_balance(
        solana_agent, 
        token_address=address
    )
    return {"status": "success", "data": balance}
```

### Transfer SOL

Send SOL to any Solana address:

```python
@tool_registry.register_tool("transfer_solana")
async def transfer_solana(address: str, amount: float) -> dict:
    """
    Transfer SOL to a Solana address.
    
    Args:
        address: Destination Solana address
        amount: Amount of SOL to transfer
        
    Returns:
        Dictionary with status and transaction signature
    """
    signature = await TokenTransferManager.transfer(
        solana_agent,
        to=address,
        amount=amount
    )
    return {
        "status": "success",
        "signature": signature
    }
```

## 🔒 Best Practices

{% stepper %}
{% step %}

### Balance Verification

Always check balance before transfers:

```python
system_instruction = """
CRITICAL: Before ANY SOL transfer:
1. Call get_balance_solana to check current balance
2. Compare balance with requested transfer amount
3. Only proceed if balance >= transfer amount
4. Inform user if insufficient funds
"""
```

{% endstep %}

{% step %}

### Error Handling

Implement robust error handling in tools:

```python
@tool_registry.register_tool("tool_name")
async def tool_function(param: str) -> dict:
    try:
        result = await perform_operation(param)
        return {"status": "success", "data": result}
    except ValueError as e:
        return {"status": "error", "message": f"Invalid input: {str(e)}"}
    except Exception as e:
        return {"status": "error", "message": f"Operation failed: {str(e)}"}
```

{% endstep %}

{% step %}

### Environment Variables

Store sensitive data securely:

```bash
# .env file
SOLANA_PRIVATE_KEY=your_private_key_here
OPENAI_API_KEY=your_openai_key_here
```

```python
from dotenv import load_dotenv
import os

load_dotenv()

private_key = os.getenv("SOLANA_PRIVATE_KEY")
```

{% endstep %}

{% step %}

### Session Management

Use session IDs for context preservation:

```python
# Same session maintains conversation context
response1 = await agent.run("Check my balance", session_id="user_123")
response2 = await agent.run("Transfer 0.5 SOL to <address>", session_id="user_123")
```

{% endstep %}
{% endstepper %}

## 🎯 Use Cases

### Conversational Wallet

```python
# Natural language interactions
"What's my current SOL balance?"
"Send 0.5 SOL to ABC123..."
"How much SOL do I have left after that transfer?"
```

### Automated Trading Bot

```python
# Conditional transfers based on balance
"If my balance is above 10 SOL, transfer 5 SOL to the treasury address"
```

### Multi-User Support

```python
# Different sessions for different users
await agent.run(message, session_id=f"user_{user_id}")
```

## 🐛 Debugging

Enable debug mode for detailed logging:

```python
agent = OmniAgent(
    # ... other config
    debug=True
)
```

This will log:

* Tool selection reasoning
* Parameter extraction
* Execution results
* Error traces

## 📚 API Reference

### `OmniAgent.run()`

Execute a user message and return response.

```python
async def run(
    self,
    message: str,
    session_id: Optional[str] = None
) -> dict:
    """
    Process a user message and return the agent's response.
    
    Args:
        message: User input message
        session_id: Optional session identifier for context
        
    Returns:
        Dictionary containing agent response and metadata
    """
```

### `OmniAgent.stream_events()`

Stream real-time events from a session.

```python
async def stream_events(
    self,
    session_id: str
) -> AsyncIterator[Event]:
    """
    Stream events from a specific session.
    
    Args:
        session_id: Session identifier
        
    Yields:
        Event objects with type and data
    """
```

## 🚦 Next Steps

* Explore [CrewAI Integration](broken://pages/a728d77019ee02f6ab975ea5b840d2d12e5d5019)
* Learn about [Google ADK Integration](broken://pages/02dd4c372005e545ce54da58bc2c13fb6bb2f0de)
* Check [Advanced Configuration](broken://pages/15d0c72838bbbb3b08782d6dfcd9699eabf207c2)
* See [Production Deployment Guide](broken://pages/d8c7d4cd459a24b476a9b2e91ff17649889b7a47)


