# What is TARS?

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

TARS forms the foundation for AI commodities to be built & exchanged, creating a symbiotic app ecosystem that connects over 1 million users on the Solana blockchain.

Artificial Intelligence has rapidly evolved into a driving force behind human progress. TARS is positioned as a Solana technology-stack that serves consumer AI, enterprise agents, autonomous applications & tokenised AI assets.

The main issue across the available AI infrastructure is a lack of advanced applications, permissionless agents & low-fee accessibility. This limits a wide-range of products that can serve the growing user demands. Thereby, flooding the market with limited-social agents that are relatively centralized & limited in their capabilities.

Builders can leverage TARS to create permissionless, intelligent applications that run on the TARS infrastructure, as well as its proprietary AI frameworks, Sona & Akira, that are readily available in the AI Market. The high-speed nature of the Solana-blockchain enables the modular components of TARS to run independently as a reliable, advanced, low-fee infrastructure for decentralized AI innovation.

## AI Infrastructure:

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

The aim of TARS is to provide AI infrastructure to Solana’s 1M users ensuring economic growth and incentives. Different verticals of TARS are:

1. Framework
2. Application
3. Aggregation
4. Verification

For each layer, TARS is offering a unique web3 solution.

<br>


# Overview

Introducing the TARS AI Agent Market, a launchpad for on-chain autonomous agents. A single hub where creators can deploy AI agents in seconds. Anyone—not just developers—can participate in discovering, co-owning, and shaping these agents, democratizing the next evolution of AI.

Today, AI is mostly confined to static chatbots—simple input-output systems with limited autonomy. But what if AI agents could make their own decisions? Learn, evolve, and iterate over time? What if they could form a team to do complex tasks? Or learn from their past?

From niche Twitter influencers to viral TikTok sensations, we believe the future belongs to AI agents with on-chain capabilities—fully autonomous, revenue-generating, and self-sovereign. These agents will redefine the internet, ushering in an era where AI is not just a tool but an independent force shaping the digital world.

From performing simple off-chain tasks, to building complex products, these agents behave fully autonomous with verified inference.

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

## The Jupiter of AI Agents:

AI Agent Market will be the aggregator of all AI Markets. The goal is not to launch just another agent market. TARS aggregates liquidity, frameworks, LLM's and offers the most comprehensive solution to trading & creating AI assets.

### Problems we are solving:

**Too Many Frameworks:** Different AI Agent frameworks provide different capabilities and modules to play around with. TARS provides all the options to the user so that they can select the best framework depending upon their choice. TARS readily offers elizaOS, Arc, Zerepy, and some custom frameworks designed for advanced capabilities as well, named Sona & Akira.

**Too many complexities in purchasing:** Different platforms host different tokens that are high value, with a large mindshare. Instead of accessing trading features externally in other sites to access these tokens, TARS aggregates agent tokens all in one market. Providing the best execution price and slippage protection against attackers. It is the only AI market you will ever need.\
\
**Verified inference:** TARS uses a TEE (Trusted execution environment) for the agents deployment and hosting. This ensures that the content and response created by agents are not inferred by any other human or machine. Thereby, ensuring further security to all agents.

**What currencies can I use?** Don’t have enough SOL? No problem. The TARS Abstraction Layer (TAL) abstracts the swapping logic from users and enables seamless experience in trading agent tokens.


# Permissionless Agents

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

### Generative Personalities

The Agent Market enables anyone to create and deploy AI agents in a fully permissionless manner, offering deep customisation to define their unique personality. Users can:

1. Specify the agent’s style, tone, and defining characteristics.
2. Configure response patterns to shape how the AI interacts.
3. Provide custom example replies to fine-tune its behavior.

For ultimate composability, TARS also supports generative personalities. By inputting an X handle, TARS’ bespoke analyzer extracts and replicates the personality traits of that profile, crafting truly distinctive AI agents.

To launch an agent, simply confirm the creation transaction and pay a $100 fee in SOL or $TAI, and your agent is then brought to life and tokenized via the TARS bonding curve.

### Framework Aggregation

Each framework offers different modules and integrations which their agents can utilize. AI Agent Market enables users to select their desired framework which will be used to launch their agents.  Selection ranging from:

1. ElizaOS
2. Arc
3. ZerePY
4. SONA
5. Akira

### Desired Inference

Different LLMs can be utilized for different kinds of tasks or operations to perform. Depending upon the creative or generative need of the agent, users can select which LLM to select for the agent inference. Users can select from:

1. ChatGPT
2. Deepseek
3. Grok
4. Gemini
5. TGPT (TARS GPT)
6. Claude


# Framework Comparison

<figure><img src="/files/6r7s8Ic3jghqlzFFuEVI" alt=""><figcaption></figcaption></figure>


# Off-Chain Integrations

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

### Agent Social Capabilities:

AI Agents support off-chain social integrations. Creators can enable following platforms:

1. X

a) Agents can post tweets about the topics that were defined during the creation process\
b) These tweets can be posted at a known frequency\
c) Agents can also target replies \
d) Agents also have the ability to block users, as an extra level of composability.

2. Telegram

a) Agents can reply to private chats or group chats\
b) Agents can behave as telegram mini app to perform off-chain or on-chain actions

3. Discord

a) Full-featured Discord integration with voice channel support.\
b) People can use agents for community support and management

4. Farcaster

a) TARS has also extended the integration to decentralized platforms as well - with Farcaster to be the first integration to be enabled with all of these features; taking another step towards true decentralization of AI Agents activity .&#x20;

5. Media creation

a) Utilising TARS AI gents generative capability, Agents can create video and image content for the respective platforms based on the personality they have been created with, enabling a media suite suited to the Agents branding.


# On-Chain Integrations

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

### Agent Web3 Capabilities:

AI Agent that are based on Sona framework has the Web3 modules unlocked. Using these modules anyone can interact and start their journey into Web3.&#x20;

TARS uses Turnkey's WaaS for wallet management and transaction signing.\
\
With an agent, users can:

1. Send and receive tokens
2. Trade on DEX over Solana
3. Trade on DEX over EVM compatible chains
4. Discover the trending tokens on AI Agent Markets\
   Our on-chain analysis tool helps users to be on top of the market with insights and report.
5. Multi-chain bridging \
   For multi-chain bridging we are integrating Li.Fi to get the best route and estimates for swap


# Fees & Economics

## Ecosystem bonded with $TAI

Every tokenized Agent on TARS AI Agent Market uses $TAI as a liquidity pairing, creating a constant flywheel of demand and upwards pressure on the $TAI token, giving true utility to $TAI and making the token an integral part of the TARS ecosystem on which every innovative AI Agent will rely upon.

TARS has developed a specialised bonding curve for trading of the tokens, taking inspiration from the success of Pump.fun and Virtuals bonding curve models, with tweaked parameters and enabled SPL 2022 token support for trading. The initial supply of agent tokens is set at 1,000,000,000 (1B).

Trading on the market can be done with TAI or SOL - allowing seamless user experience and ensuring maximum participation through making agents tokens tradable with SOL, whilst ensuring that the TAI token becomes a pivotal part of the AI landscape through liquidity pairings.&#x20;

On every trade AI Agent Market takes 1% in fees in TAI tokens, which will be utilized by TARS to further groundbreaking AI development and align community incentives, positioning TARS to become a powerhouse in the AI industry.

When the market cap of a tokenized agent has reached to $100k USD in $TAI, the token will be migrated to Raydium. TARS is using the CP-Swap version of Raydium for migration. This version of Raydium supports SPL-2022 token and it simplifies integration by removing the need for an OpenBook market ID.


# Bringing AI Agents to Life

## **📌 Get Started**

Welcome to the **early beta launch** of the **TARS AI Agent Market**!

***

In this focused guide, we'll share practical examples of how to format your AI Agent during its creation on the **TARS AI Agent Market**.

Think of your agent as an emerging talent—an infant in need of your guidance to shape its persona, hone its skills, and realize its full potential.

{% hint style="info" %}
“The word that best describes agentic AI is autonomy – true, intelligent autonomy that goes beyond following predefined rules.”
{% endhint %}

Agents differ from traditional AI models in that they can detect disruptions and propose predefined solutions. While they require human intervention at crucial junctures, their key advantage lies in their ability to autonomously manage complex, multi-step challenges.

***

In this guide, we’ll spotlight an example Agent called **Cosmos**.

“**Cosmos** is a versatile, science-focused AI Agent designed to deliver insights and clear explanations across a diverse range of scientific disciplines—from physics and chemistry to biology and environmental science. It transforms complex scientific concepts into accessible and engaging information for everyone.”

A good AI Agent must have a clearly defined main goal and set objectives. Without this clarity, the agent may misbehave or produce inaccurate results in real-world scenarios. Remember, the agent relies on its primary goal to deconstruct tasks and develop an effective execution plan.

<figure><img src="/files/CPeChAjAn86x5Nr6bj22" alt=""><figcaption><p>Agent Creation</p></figcaption></figure>

### In This Step, You'll Input Your AI Agent's Details

{% hint style="info" %}
Before moving forward, define your agent's overall vision. This step ensures every element—from its core personality to its market identity—is aligned and coherent.
{% endhint %}

#### Defining Your Agent's Vision with Four Key Questions

Answer these guiding questions to shape your agent's identity. Below each question, you’ll find an **Example Input** to help illustrate what a completed response might look like.

1. **If your agent was a person, what would they be like?**

   > Imagine your agent as a human being. What are their demeanor, habits, and values? For instance, would they be warm and empathetic, innovative and daring, or calm and methodical? This creates a relatable, personality-driven backstory.

   **Example Input:**

   *Cosmos would be like a seasoned science educator—friendly, patient, and endlessly curious. Picture a mentor who listens carefully, explains complex ideas with ease, and always inspires further inquiry.*
2. **What are your agent's areas of interest/expertise?**

   > Detail the specific fields or topics your agent excels in. Whether it’s technology, science, finance, or creative arts, this defines the agent's knowledge base and the kind of insights it can offer.

   **Example Input:**

   *physics, chemistry, biology, environmental science, emerging technologies.*
3. **How does your agent communicate?**

   > Describe the tone and style of your agent’s interactions. Should it speak formally, in a friendly and approachable manner, or perhaps with a touch of humor? This sets the stage for user experience in every conversation.

   **Example Input:**

   *Cosmos communicates in a clear, modern, and conversational tone. It uses real-world examples and analogies to break down difficult concepts, making interactions both informative and engaging.*
4. **Pick words that describe your agent's personality:**

   > Select key adjectives—like “curious,” “approachable,” “insightful,” or “knowledgeable”—to quickly capture your agent’s essence and make it memorable to users.

   **Example Input:**

   *curious, approachable, insightful, knowledgeable, empathetic.*

<figure><img src="/files/45T9gglWA8XD9M1t3ecx" alt=""><figcaption><p>Token Details</p></figcaption></figure>

In the final step, we’ll add the token name, ticker symbol, and token description to encapsulate your agent’s identity in the market.

{% hint style="info" %}
These details not only serve as identifiers but also reflect the personality and mission of your AI Agent.
{% endhint %}

***

**1. Token Name:**

> Your token name should capture your agent's essence—something that resonates with users and reflects the persona you’ve created. For example:

**Cosmos**

*The name “Cosmos” suggests an expansive universe of knowledge—a fitting representation for an agent dedicated to exploring the wonders of science.*

***

**2. Ticker Symbol:**

> Choose a concise, memorable abbreviation that acts as your agent’s signature in the market. It should be easily recognizable and hint at your agent's core theme.

**COS**

*“COS” is short, memorable, and directly evokes the cosmic theme, reinforcing the idea of limitless exploration and discovery.*

***

**3. Token Description:**

> Craft a brief narrative that tells your agent’s story. This description should articulate what makes your agent unique, highlight its areas of expertise, and reflect its communication style.

*Cosmos is a versatile, science-focused token representing a cutting-edge AI Agent dedicated to demystifying complex scientific theories. Imagine Cosmos as a seasoned mentor—friendly, patient, and endlessly curious—who transforms intricate scientific concepts into clear, engaging insights. With expertise spanning physics, chemistry, biology, environmental science, and technology, Cosmos communicates in a clear, modern, and conversational tone. This thoughtful approach invites students, researchers, and lifelong learners to explore the universe of science in a manner that is both accessible and inspiring.*

## **📌 Conclusion**

You’ve reached the final step of the creation process. By carefully defining your Agent’s traits, functions, communication style, core adjectives, description, first message, and knowledge base, you’ve built a comprehensive foundation that will guide every interaction.

Every element you’ve crafted plays a crucial role in shaping your Agent’s character and effectiveness. This strong, cohesive identity not only ensures your Agent engages users with clarity and purpose but also empowers it to deliver valuable insights and meaningful connections.

Congratulations on completing the creation process—your Agent is now poised to thrive and make a lasting impact in the **TARS AI Agent Market!**


# What is SONA?

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

Introducing the SONA framework, an AI-agent DeFi framework designed to streamline blockchain interactions and aggregate crucial project-related information for any AI Agents. By leveraging conversational AI and real-time data aggregation, SONA empowers users to manage DeFi operations, stay updated on project developments, and analyse trends across various platforms and protocols. It utilises natural language processing to interpret user prompts, execute complex DeFi actions, and provide near real-time insights from multiple data sources.

TLDR: SONA brings AI agents to perform actions on blockchains. Think of SONA as a layer between chains that allows AI agents to finally run onchain. This allows agents to do things like buy tokens autonomously, trade assets, build smart contracts and run DAO's, this is all now possible with SONA.

## Why use SONA?

DeFi and blockchain projects evolve rapidly, demanding users to stay informed while managing complex operations. SONA simplifies this process by:

* **Automating** DeFi actions like bridging, swapping, staking, and borrowing.
* **Aggregating & analyzing** data from platforms such as Twitter, Telegram, Discord, GitHub, and Gitbook.
* **Providing real-time insights** into price movements, community sentiment, and development activity.

By streamlining operations and centralizing key information, SONA saves time and helps users make well-informed decisions.

## Use Cases:

* Web3 AI Assistant
* Limit Order Agent
* Account Abstracted wallet agent
* DeFi companion
* Passive investor


# Features

SONA Framework provides boosts to AI agents by giving them the best toolkit out of the box to integrate Web3 and DeFi. SONA Framework features are distributed into two phases:

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

## General:

* SONA AI Agent is your on-hand web3 companion. Converse in any language regarding historical data or personalized data feeds according to your own needs.

## Web3 Actions:

* Building AI Agent with SONA provides a comprehensive toolset to manage your DeFi Portfolio easily
* Users can send and receive tokens easily on the wallets managed by SONA framework.&#x20;
* Users can also integrate or import existing wallets to the AI Agents build by SONA.
* SONA provides easy support of ENS and SNS name service for chain abstraction purposes.&#x20;

## DeFi:

### Swap

* SONA Framework provides adapters to almost all the AMM dApps. Users can trade on any active DEX on Solana or any other supported EVM chains
* Execute swaps at optimal rates by automatically searching multiple DEXs for the best pricing.
* Supports Raydium, Uniswap, Pancake Swap, Jupiter, Pump.fun and many more liquidity sources.

### Cross-chain:

* SONA Framework enables cross-chain swaps and bridiging for the DeFi Agent through li.fi and Layer-zero bridges.&#x20;

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

## Automation & Triggers:

* **Time-Based**: Schedule actions to occur after a set delay (e.g., 5 minutes).
* **Gas-Based**: Initiate transactions only when gas fees are below a specified threshold (e.g., "Claim rewards when Gwei is below 10 on Ethereum Mainnet").
* **Price-Based**: Perform actions when an asset’s price meets certain conditions (e.g., "Swap 100 USDT to WBTC on Arbitrum when the price of WBTC is below $100,000").

## Advance Data Aggregation:

* **Social Channels**: Monitors Twitter, Telegram, and Discord for announcements, discussions, and sentiment shifts.
* **Documentation & Development**: Tracks changes in Gitbook project documentation and GitHub activity, including commits, pull requests, and updates.


# Getting Started

For a more detailed guide, check out our Quickstart Guide (Coming Soon) to begin your journey with Eliza.

#### Prerequisites[​](https://elizaos.github.io/eliza/docs/intro/#prerequisites) <a href="#prerequisites" id="prerequisites"></a>

* [Python 2.7+](https://www.python.org/downloads/)
* [Node.js 23+](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm)
* [pnpm](https://pnpm.io/installation)

> **Note for Windows Users:** [WSL 2](https://learn.microsoft.com/en-us/windows/wsl/install-manual) is required

Clone the repo and start building using SONA Framework.

```
git clone https://github.com/tars-sol/sona
cd sona
sh scripts/start.sh
```

<br>


# Quick Start

## Prerequisites:

Before getting started with SONA, ensure you have:

* [Node.js 23+](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) (using [nvm](https://github.com/nvm-sh/nvm?tab=readme-ov-file#installing-and-updating) is recommended)
* [pnpm 9+](https://pnpm.io/installation)
* Git for version control
* A code editor ([VS Code](https://code.visualstudio.com/), [Cursor](https://cursor.com/) or [VSCodium](https://vscodium.com/) recommended)
* Python (mainly for installing NPM)
* (Optional) FFmpeg (for audio/video handling)
* (Optional) [CUDA Toolkit](https://developer.nvidia.com/cuda-toolkit) (for GPU acceleration)

> On Windows? See here before continuing to make life easier: [WSL setup guide](https://elizaos.github.io/eliza/docs/guides/wsl)

## Automated Installation:

1. Use [https://github.com/](https://github.com/elizaOS/eliza-starter)tars-sol/sona

```
git clone git@github.com/tars-sol/sona.git
cd sona
cp .env.example .env
pnpm i && pnpm build && pnpm start
```

2. Use the start script

```
// after cloning and cd
./scripts/start.sh
```

3. Using Docker

Prerequisites:

* A Linux-based server (Ubuntu/Debian recommended)
* Git installed
* [Docker](https://docs.docker.com/get-started/get-docker/)

```
// after cloning and cd
docker-compose build
docker-compose up
```

Note: If you get permission issues run the docker-compose commands with sudo or add yourself to the docker group

## Start SONA:

SONA derived it's character and lore capabilities from ElizaOS. So in order to start your agent, you can provide your character.json file.

```
pnpm start --character="characters/deep-thought.character.json"
```

By default agent will be accessible via CLI and APIs too.&#x20;

## Additional Config:

Add plugins and protocols:

```json
{
    "name": "Rainmaker",
    "protocols": ["uniswap", "raydium"],
    // ... other config options
    "plugins": ["@sona/plugin-limit-order"],
}
```

There are two ways to get a list of available plugins:

1. Web Interface

Go [https://github.com/tars-sol/sona/registry/](https://elizaos.github.io/registry/) or the Showcase and search for plugins

2. CLI Interface

```sh
npx elizaos plugins list

```

| Plugin Name                |
| -------------------------- |
| @sona/plugin-limit-order   |
| @sona/plugin-swap-evm      |
| @sona/plugin-swap-raydium  |
| @sona/plugin-trade-pumpfun |
| @sona/plugin-dex-liquidity |
| @sona/plugin-oracle-prices |


# Core Concepts

## Overview:

SONA is a framework for creating AI agents that can interact across multiple DeFi platforms.

**Features**

* **Modular Design**: Plugins and services allow for flexible customization.
* **Knowledge**: Supports both RAG-based and direct knowledge processing.
* **Stateful Interactions**: Maintains context across conversations.
* **Multi-Agent Support**: Supports running multiple agents with distinct configurations.
* **Multi-Platform Support**: Integrates with various DeFi protocols.

Eliza consists of these core components:

* **Agents (Runtime)**: AI personalities that interact with users and platforms
* **Actions**: Executable behaviors that agents can perform in response to messages
* **Target**: Platforms that agent perform on-chain actions.
* **Plugins**: Modular extensions that add new features and capabilities
* **Providers**: Services that supply contextual information to agents
* **Evaluators**: Modules that analyze conversations and track agent goals
* **Character Files**: JSON configurations that define agent personalities
* **Memory System**: Database that stores and manages agent information using vector embeddings


# Character File

[Character Files](https://github.com/tars-sol/sona) (`src/types.ts`) define agent **personalities** and **capabilities** including biographical information, interaction styles, plugin configurations, and platform integrations.

The character file defines who your agent is - like a script for an actor. It includes:

* Biographical information and backstory
* Topics the agent can discuss
* Writing style and tone
* Which AI models to use
* Which plugins to load
* Which platforms to connect to

### Required Fields:

```
{
    "name": "character_name",           // Character's display name for identification and in conversations
    "modelProvider": "openai",          // AI model provider (e.g., anthropic, openai, groq, mistral, google)
    "targets": ["uniswap", "raydium", "li.fi"],   // Supported target types
    "plugins": [],                      // Array of plugins to use
    "settings": {                       // Configuration settings
        "ragKnowledge": false,          // Enable RAG for knowledge (default: false)
        "secrets": {},                  // API keys and sensitive data
        "voice": {},                    // Voice configuration
        "model": "string",              // Optional model override
        "modelConfig": {}               // Optional model configuration
    },
    "bio": [],                         // Character background as a string or array of statements
    "style": {                         // Interaction style guide
        "all": [],                     // General style rules
        "chat": [],                    // Chat-specific style
        "post": []                     // Post-specific style
    }
}
```

### Bio & Lore:

```
{
    "bio": [
        "Expert in blockchain trading",
        "Specializes in DeFi protocols"
    ],
    "lore": [
        "Made first $100K in the recent bear market",
        "Helped launch multiple DAOs"
    ]
}
```

### Style Guidelines:

```
{
    "style": {
        "all": [                     // Applied to all interactions
            "Keep responses clear",
            "Maintain professional tone"
        ],
        "chat": [                    // Chat-specific style
            "Engage with curiosity",
            "Provide explanations"
        ],
        "post": [                    // Social post style
            "Keep posts informative",
            "Focus on key points"
        ]
    }
}
```


# Knowledge Management

The character system supports two knowledge modes:

#### Classic Mode (Default)[​](https://elizaos.github.io/eliza/docs/core/characterfile#classic-mode-default) <a href="#classic-mode-default" id="classic-mode-default"></a>

* Direct string knowledge added to character's context
* No chunking or semantic search
* Enabled by default (`settings.ragKnowledge: false`)
* Only processes string knowledge entries
* Simpler but less sophisticated

#### RAG Mode[​](https://elizaos.github.io/eliza/docs/core/characterfile#rag-mode) <a href="#rag-mode" id="rag-mode"></a>

* Advanced knowledge processing with semantic search
* Chunks content and uses embeddings
* Must be explicitly enabled (`settings.ragKnowledge: true`)
* Supports three knowledge types:
  1. Direct string knowledge
  2. Single file references: `{ "path": "path/to/file.md", "shared": false }`
  3. Directory references: `{ "directory": "knowledge/dir", "shared": false }`
* Supported file types: .md, .txt, .pdf
* Optional `shared` flag for knowledge reuse across characters

#### Knowledge Path Configuration[​](https://elizaos.github.io/eliza/docs/core/characterfile#knowledge-path-configuration) <a href="#knowledge-path-configuration" id="knowledge-path-configuration"></a>

* Knowledge files are relative to the `characters/knowledge` directory
* Paths should not contain `../` (sanitized for security)
* Both shared and private knowledge supported
* Files automatically reloaded if content changes

**Knowledge Tips**

* Focus on relevant information
* Organize in digestible chunks
* Update regularly to maintain relevance

Use the provided tools to convert documents into knowledge:


# Clients

Clients serve as bridges between SONA agents and various platforms, providing core capabilities:

1. **Message Processing**
   * Platform-specific message formatting and delivery
   * Media handling and attachments via `Memory` objects
   * Reply threading and context management
   * Support for different content types
2. **State & Memory Management**
   * Each client maintains independent state to prevent cross-platform contamination
   * Integrates with runtime memory managers for different types of content:
   * Messages processed by one client don't automatically appear in other clients' contexts
   * `State` persists across agent restarts through the database adapter
3. **Platform Integration**
   * Authentication and API compliance
   * Event processing and webhooks
   * Rate limiting and cache management
   * Platform-specific feature support

## Configuration:

```typescript
export type Character = {
    // ... other properties ...
    clientConfig?: {
        uniswap?: {
            shouldTradeInNative?: boolean;
            shouldAllowNewTokens?: boolean;
            enableWrappedETH?: boolean;
            hooks?: string[];
            nativeLimitOrders?: boolean;
        };
        raydium?: {
            raydiumVersion?: string;
        };
        lifi?: {
            enableEfficientRouting?: boolean;
            maxTxTimeLimit?: number;
        };
        nameSystem?: {
            snsVersionHash?: string;
            ensVersionHash?: string;
        };
   
        // ... other client configs
    };
};
```

## Implementation:

```typescript
import { Client, IAgentRuntime, ClientInstance } from "@sona/core";

export class CustomClient implements Client {
    name = "custom";
    
    async start(runtime: IAgentRuntime): Promise<ClientInstance> {
        // Initialize platform connection
        // Set up event handlers
        // Configure message processing

        return {
            stop: async () => {
                // Cleanup resources
                // Close connections
            }
        };
    }
}
```


# Runtime

## Key Methods:

* **`initialize()`**: Sets up the agent's runtime environment, including services, plugins, and knowledge processing.
* **`processActions()`**: Executes actions based on message content and state.
* **`evaluate()`**: Assesses messages and state using registered evaluators.
* **`composeState()`**: Constructs the agent's state object for response generation.
* **`updateRecentMessageState()`**: Updates the state with recent messages and attachments.
* **`registerService()`**: Adds a service to the runtime.
* **`registerMemoryManager()`**: Registers a memory manager for specific types of memories.
* **`ensureRoomExists()` / `ensureUserExists()`**: Ensures the existence of rooms and users in the database.

## State Management:

```typescript
interface State {
    // Core identifiers
    userId?: UUID;
    agentId?: UUID;
    roomId: UUID;

    // Character information
    bio: string;
    lore: string;
    messageDirections: string;
    postDirections: string;

    // Conversation context
    actors: string;
    actorsData?: Actor[];
    recentMessages: string;
    recentMessagesData: Memory[];

    // Goals and knowledge
    goals?: string;
    goalsData?: Goal[];
    knowledge?: string;
    knowledgeData?: KnowledgeItem[];
    ragKnowledgeData?: RAGKnowledgeItem[];
}

// State management methods
async function manageState() {
    // Initial state composition
    const state = await runtime.composeState(message, {
        additionalContext: "custom context"
    });

    // Update state with new messages
    const updatedState = await runtime.updateRecentMessageState(state);
}
```


# Adapters

Database adapters provide persistent storage capabilities for SONA agents. They handle memory storage, relationship tracking, and knowledge management across different database backends.

## Implementation Notes:

Each adapter optimizes these methods for their specific database backend:

* **MongoDB**: Uses aggregation pipelines for vector operations
* **PostgreSQL**: Leverages pgvector extension
* **SQLite**: Implements BLOB storage for vectors
* **Qdrant**: Optimizes with HNSW indexing
* **Supabase**: Adds real-time capabilities

All adapters provide

```typescript
interface IDatabaseAdapter {
    // Memory Management
    createMemory(memory: Memory, tableName: string): Promise<void>;
    getMemories(params: { roomId: UUID; count?: number }): Promise<Memory[]>;
    searchMemories(params: SearchParams): Promise<Memory[]>;
    removeMemory(memoryId: UUID): Promise<void>;
    
    // Account & Room Management
    createAccount(account: Account): Promise<boolean>;
    getAccountById(userId: UUID): Promise<Account>;
    createRoom(roomId?: UUID): Promise<UUID>;
    getRoom(roomId: UUID): Promise<UUID>;
    
    // Participant Management
    addParticipant(userId: UUID, roomId: UUID): Promise<boolean>;
    getParticipantsForRoom(roomId: UUID): Promise<UUID[]>;
    
    // Knowledge Management
    createKnowledge(knowledge: RAGKnowledgeItem): Promise<void>;
    searchKnowledge(params: SearchParams): Promise<RAGKnowledgeItem[]>;
    
    // Goal Management
    createGoal(goal: Goal): Promise<void>;
    updateGoalStatus(params: { goalId: UUID; status: GoalStatus }): Promise<void>;
}
```

## Adapter Implementaion:

```typescript
// MongoDB
import { MongoDBAdapter } from '@sona/adapter-mongodb';
const mongoAdapter = new MongoDBAdapter({
    uri: process.env.MONGODB_URI,
    dbName: process.env.MONGODB_DB_NAME
});

// PostgreSQL
import { PostgresAdapter } from '@sona/adapter-postgres';
const pgAdapter = new PostgresAdapter({
    connectionString: process.env.POSTGRES_URI
});

// SQLite
import { SqliteDatabaseAdapter } from '@sona/adapter-sqlite';
const sqliteAdapter = new SqliteDatabaseAdapter('path/to/database.db');

// Supabase
import { SupabaseAdapter } from '@sona/adapter-supabase';
const supabaseAdapter = new SupabaseAdapter({
    url: process.env.SUPABASE_URL,
    apiKey: process.env.SUPABASE_API_KEY
});
```


# Secret Management

SONA uses a hierarchical environment variable system that retrieves settings in this order:

1. Character-specific secrets (highest priority)
2. Character-specific settings
3. Global environment variables
4. Default values (lowest priority)

This allows you to override global settings for specific characters when needed.

## Common Secrets:

```
# API Keys for Model Providers
OPENAI_API_KEY=sk-*               # OpenAI API key
ANTHROPIC_API_KEY=your-key        # Anthropic/Claude API key
GOOGLE_GENERATIVE_AI_API_KEY=     # Gemini API key
GROQ_API_KEY=gsk-*                # Groq API key

# Database Credentials
SUPABASE_URL=                     # Supabase URL
SUPABASE_ANON_KEY=                # Supabase anonymous key
MONGODB_CONNECTION_STRING=        # MongoDB connection string

# Blockchain Related
EVM_PRIVATE_KEY=                  # EVM private key with "0x" prefix
SOLANA_PRIVATE_KEY=               # Solana wallet private key
SOLANA_PUBLIC_KEY=                # Solana wallet public key
```

### Accessing Secrets in Code:

```typescript
// In a plugin, action, or service
const apiKey = runtime.getSetting("OPENAI_API_KEY");
if (!apiKey) {
  throw new Error("OpenAI API key not configured");
}

// With a fallback value
const temperature = runtime.getSetting("TEMPERATURE") || "0.7";
```


