> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sei.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Cambrian Agent Kit Ecosystem Tutorial

> Learn to build powerful, autonomous AI agents and agentic chatbots on the SEI blockchain with DeFi protocol integrations including Takara, Silo, Citrex, and Symphony.

## Overview

Cambrian Agent Kit is a developer SDK for building powerful, autonomous AI agents and agentic chatbots on the SEI blockchain. It lets you interact with DeFi protocols (Takara, Silo, Citrex, Symphony), manage SEI tokens and NFTs, and seamlessly integrate AI workflows. In this tutorial, you'll learn how to set up the kit, run your first agent, and use it for real DeFi use cases—customized for your needs. To understand more and deep dive into how it works under the hood, please refer to the [Cambrian Agent Kit Documentation](https://deepwiki.com/CambrianAgents/sei-agent-kit/1-overview).

## Supported Features

The SEI Agent Kit supports a comprehensive set of features for blockchain agent development:

* Token Operations: Complete SEI ERC-20 and ERC-721 token management
* DeFi Protocol Integration: Seamless interaction with SEI's DeFi ecosystem
* Swap Functionality: Token swapping through Symphony aggregator
* Liquidity Management: Add and remove liquidity with DragonSwap
* Lending & Borrowing: Interact with Takara protocol for lending operations
* Staking Operations: Stake and unstake SEI tokens with Silo
* LangChain Integration: Build AI agents with LangChain and LangGraph

## What this guide teaches you:

This tutorial guides you through:

* **Setup**: Install and configure the Agent Kit, connect your wallet and API keys.
* **Core Concepts**: Understand agents, supported protocols, and how these components fit together.
* **End-to-End Examples**: You'll run practical code to:
  * Check your token/NFT balances.
  * Swap tokens using Symphony.
  * Stake/unstake SEI in Silo.
  * Lend/borrow with Takara.
  * Trade perps with Citrex.
* **Customization**: Learn to adapt the kit for your own protocol or workflow.

<Info>
  **Some Use Cases:**

  * **Autonomous DeFi Agents**: Agents that can automatically manage token positions, provide liquidity, or engage in lending activities
  * **AI-Assisted Wallets**: Conversational interfaces for blockchain operations
  * **Financial Assistant Agents**: AI agents that can analyze market conditions and execute trades
  * **Portfolio Management Agents**: Automated management of crypto asset portfolios
</Info>

## Hands-on Tutorial

### 1. Prerequisites

* Node.js & npm installed
* SEI wallet private key
* OpenAI API key (for AI integrations)
* **Minimum SEI balance**: Ensure you have sufficient SEI for gas

### 2. Project Setup

```bash theme={"dark"}
git clone https://github.com/CambrianAgents/sei-agent-kit.git
cd sei-agent-kit
cp .env.example .env   # Fill in your keys!
npm install
```

Edit `.env`:

```env theme={"dark"}
OPENAI_API_KEY=your_openai_api_key
SEI_PRIVATE_KEY=your_wallet_private_key
RPC_URL=https://evm-rpc.sei-apis.com
```

<Warning>
  **Important Security Notes:**

  * **Never share your private key**: Your private key controls your funds
</Warning>

### 3. Running Your First Agent

```bash theme={"dark"}
npm run test
```

The following is the output and interaction with the Cambrian Agent:

```bash theme={"dark"}
npm run test

> sei-agent-kit@0.0.3 test
> tsx test/index.ts


  ███████╗███████╗██╗      █████╗  ██████╗ ███████╗███╗   ██╗████████╗    ██╗  ██╗██╗████████╗
  ██╔════╝██╔════╝██║     ██╔══██╗██╔════╝ ██╔════╝████╗  ██║╚══██╔══╝    ██║ ██╔╝██║╚══██╔══╝
  ███████╗█████╗  ██║     ███████║██║  ███╗█████╗  ██╔██╗ ██║   ██║       █████╔╝ ██║   ██║
  ╚════██║██╔══╝  ██║     ██╔══██║██║   ██║██╔══╝  ██║╚██╗██║   ██║       ██╔═██╗ ██║   ██║
  ███████║███████╗██║     ██║  ██║╚██████╔╝███████╗██║ ╚████║   ██║       ██║  ██╗██║   ██║
  ╚══════╝╚══════╝╚═╝     ╚═╝  ╚═╝ ╚═════╝ ╚══════╝╚═╝  ╚═══╝   ╚═╝       ╚═╝  ╚═╝╚═╝   ╚═╝


Starting chat with the Cambrian Agent... Type 'bye' to end.

You: Hey, I would like to swap some sei to usdc.

Cambrian Agent: Sure thing! How much SEI would you like to swap for USDC? Let me know, and I'll get the magic started! ✨

-----------------------------------


You: I would like to swap 0.2 sei for some usdc

Cambrian Agent:

-----------------------------------

Getting token address for USDC...
Swapping 0.2 0x0 to 0x3894085ef7ff0f0aedf52e2a2704928d1ec074f1...
Querying balance of SEI for 0xa0E377AEaF32024f949667f56e7fa4409AFE6b8D...

Cambrian Agent: {"status":"success","result":"0x638d08db41e9ed370504861b4d2ced693869c45136bfdba2d92e8aed43c080fa","fromToken":"SEI","toToken":"USDC","amount":"0.2"}

-----------------------------------


Cambrian Agent: Your swap of 0.2 SEI to USDC was successful! 🎉 The transaction hash is `0x638d08db41e9ed370504861b4d2ced693869c45136bfdba2d92e8aed43c080fa`. If you have any more magical swaps or questions, just let me know! 🪄

-----------------------------------


You: Give me my new balances after the previous transaction

Cambrian Agent:

-----------------------------------

Getting token address for SEI...
Getting token address for USDC...
Querying balance of 0x3894085ef7ff0f0aedf52e2a2704928d1ec074f1 for 0xa0E377AEaF32024f949667f56e7fa4409AFE6b8D...
Querying balance of 0x67da7010c6c231ad620e3940e707adb6c1a08f23 for 0xa0E377AEaF32024f949667f56e7fa4409AFE6b8D...

Cambrian Agent: {"status":"success","balance":"0","token":{"ticker":"SEI"}}

-----------------------------------


Cambrian Agent: After the swap, your new balances are:

- SEI: 0 SEI (Looks like you've spent it all!)
- USDC: 0.147866 USDC

If you need anything else, just give me a shout! 📢

-----------------------------------


You: bye
```

<Info>
  **Understanding the Transaction:**

  * **SEI Address**: `0x0` represents native SEI token in the agent kit
  * **Transaction Hash**: Can be verified on [Seiscan](https://seiscan.io/)
  * **Gas Fees**: Automatically calculated and deducted from your balance
</Info>

### 4. Explore Core Features & Protocols

#### a) Check Token Balance with Error Handling

```typescript theme={"dark"}
import { SeiAgentKit } from './src/agent';

async function checkBalanceWithErrorHandling() {
  try {
    const agent = new SeiAgentKit(process.env.SEI_PRIVATE_KEY, 'openai');

    // Check SEI balance
    const balance = await agent.getERC20Balance(); // SEI or specify contract address
    console.log('Your SEI Balance:', balance);

    // Validate balance before proceeding
    if (parseFloat(balance) < 0.01) {
      console.warn('⚠️ Low SEI balance. You may need more SEI for gas fees.');
    }
  } catch (error) {
    console.error('Error checking balance:', error.message);

    // Handle specific error types
    if (error.message.includes('insufficient funds')) {
      console.log('💡 Tip: Add more SEI to your wallet');
    } else if (error.message.includes('network')) {
      console.log('💡 Tip: Check your RPC connection');
    }
  }
}
```

#### b) Safe Token Swapping with Symphony

```typescript theme={"dark"}
async function safeSwap() {
  try {
    const agent = new SeiAgentKit(process.env.SEI_PRIVATE_KEY, 'openai');

    // Validate inputs
    const amount = '1.0';
    const fromToken = '0x0'; // SEI
    const toToken = 'usdc_contract_address';

    // Check balance first
    const balance = await agent.getERC20Balance();
    if (parseFloat(balance) < parseFloat(amount)) {
      throw new Error('Insufficient balance for swap');
    }

    // Execute swap with error handling
    const tx = await agent.swap(amount, fromToken, toToken);
    console.log('Swap TX:', tx);

    // Verify transaction
    if (tx.status === 'success') {
      console.log('✅ Swap successful!');
      console.log('🔗 Transaction hash:', tx.result);
    } else {
      console.error('❌ Swap failed:', tx.error);
    }
  } catch (error) {
    console.error('Swap error:', error.message);

    // Handle common swap errors
    if (error.message.includes('slippage')) {
      console.log('💡 Tip: Try increasing slippage tolerance');
    } else if (error.message.includes('liquidity')) {
      console.log('💡 Tip: Insufficient liquidity for this pair');
    }
  }
}
```

<Warning>
  **Swap Safety Tips:**

  * **SEI Native Token**: Use "0x0" as the address for native SEI token while using the agent kit
  * **Slippage Protection**: Always set appropriate slippage tolerance
  * **Price Impact**: Monitor price impact before large swaps
</Warning>

#### c) Liquid Staking with Silo Protocol

```typescript theme={"dark"}
async function stakingWithSilo() {
  try {
    const agent = new SeiAgentKit(process.env.SEI_PRIVATE_KEY, 'openai');

    // Stake SEI and receive iSEI
    const stakeAmount = '2.0';
    const stakeTx = await agent.stake(stakeAmount);
    console.log('Staked TX:', stakeTx);

    if (stakeTx.status === 'success') {
      console.log('✅ Successfully staked SEI!');
      console.log('📄 You received iSEI tokens representing your stake');
      console.log('💰 Your rewards will auto-compound over time');
    }

    // Later, unstake if needed
    const unstakeAmount = '1.0';
    const unstakeTx = await agent.unstake(unstakeAmount);
    console.log('Unstaked TX:', unstakeTx);
  } catch (error) {
    console.error('Staking error:', error.message);

    if (error.message.includes('minimum amount')) {
      console.log('💡 Tip: Check minimum staking amount requirements');
    }
  }
}
```

<Info>
  **Silo Staking Details:**

  * **iSEI Token**: [Represents your staked SEI plus auto-compounded rewards](https://silostaking.gitbook.io/silo-staking/general-faq)
  * **No Unbonding Period**: [Immediate liquidity unlike traditional staking](https://medium.com/@nordicmoney22/unleashing-the-power-of-liquid-staking-on-sei-4a1d045232e1)
  * **5% Fee**: [Annual management fee of 5% on rewards](https://silostaking.gitbook.io/silo-staking/general-faq)
  * **MEV Benefits**: [Validators share MEV profits with stakers](https://www.silostaking.io/)
</Info>

#### d) Lending/Borrowing with Takara Protocol

```typescript theme={"dark"}
async function takaraLending() {
  try {
    const agent = new SeiAgentKit(process.env.SEI_PRIVATE_KEY, 'openai');

    // Mint tTokens (supply liquidity)
    const mintTx = await agent.mintTakara('USDC', '10');
    console.log('Mint Takara:', mintTx);

    if (mintTx.status === 'success') {
      console.log('✅ Successfully supplied USDC to Takara');
      console.log('💰 You are now earning interest on your supply');
    }

    // Borrow against collateral
    const borrowTx = await agent.borrowTakara('USDC', '5');
    console.log('Borrow Takara:', borrowTx);

    if (borrowTx.status === 'success') {
      console.log('✅ Successfully borrowed USDC from Takara');
      console.log('⚠️ Remember to monitor your collateral ratio');
    }

    // Repay borrowed amount
    const repayTx = await agent.repayTakara('USDC', '5');
    console.log('Repay Takara:', repayTx);
  } catch (error) {
    console.error('Takara error:', error.message);

    if (error.message.includes('collateral')) {
      console.log('💡 Tip: Add more collateral to maintain healthy ratio');
    } else if (error.message.includes('liquidity')) {
      console.log('💡 Tip: Insufficient liquidity in the pool');
    }
  }
}
```

#### e) Perpetual Trading with Citrex Markets

```typescript theme={"dark"}
async function citrexTrading() {
  try {
    const agent = new SeiAgentKit(process.env.SEI_PRIVATE_KEY, 'openai');

    // Deposit margin
    const depositAmount = '10';
    const depositTx = await agent.citrexDeposit(depositAmount);
    console.log('Citrex Deposit:', depositTx);

    if (depositTx.status === 'success') {
      console.log('✅ Successfully deposited margin to Citrex');
      console.log('⚡ You can now trade perpetuals with up to 20x leverage');
    }

    // Check available products
    const products = await agent.citrexGetProducts();
    console.log('Available Products:', products);

    // Withdraw margin when done
    const withdrawTx = await agent.citrexWithdraw('5');
    console.log('Citrex Withdraw:', withdrawTx);
  } catch (error) {
    console.error('Citrex error:', error.message);

    if (error.message.includes('margin')) {
      console.log('💡 Tip: Ensure sufficient margin for your positions');
    } else if (error.message.includes('leverage')) {
      console.log('💡 Tip: Reduce leverage to lower risk');
    }
  }
}
```

<Info>See `/tools/` for more advanced protocol integrations!</Info>

## Error Handling & Troubleshooting

### Common Error Types

<Info>
  **Comprehensive Error Handling Examples:**

  ```typescript theme={"dark"}
  // Robust error handling for all operations
  async function robustAgentOperation() {
    const agent = new SeiAgentKit(process.env.SEI_PRIVATE_KEY, 'openai');

    try {
      // Operation code here
    } catch (error) {
      // Network errors
      if (error.code === 'NETWORK_ERROR') {
        console.log('🌐 Network issue - retrying in 5 seconds...');
        await new Promise((resolve) => setTimeout(resolve, 5000));
        // Implement retry logic
      }

      // Insufficient funds
      if (error.message.includes('insufficient funds')) {
        console.log('💰 Insufficient funds for this operation');
        const balance = await agent.getERC20Balance();
        console.log('Current balance:', balance);
      }

      // Gas estimation errors
      if (error.message.includes('gas')) {
        console.log('⛽ Gas estimation failed - transaction may fail');
        console.log('Try reducing transaction amount or increasing gas limit');
      }

      // Contract-specific errors
      if (error.message.includes('revert')) {
        console.log('📋 Smart contract reverted the transaction');
        console.log('Check transaction parameters and try again');
      }
    }
  }
  ```
</Info>

### Transaction Monitoring

```typescript theme={"dark"}
async function monitorTransaction(txHash: string) {
  const maxRetries = 30; // 30 seconds max wait
  let retries = 0;

  while (retries < maxRetries) {
    try {
      // Check transaction status
      const receipt = await checkTransactionStatus(txHash);

      if (receipt.status === 'success') {
        console.log('✅ Transaction confirmed!');
        return receipt;
      } else if (receipt.status === 'failed') {
        console.log('❌ Transaction failed');
        return receipt;
      }

      // Wait and retry
      await new Promise((resolve) => setTimeout(resolve, 1000));
      retries++;
    } catch (error) {
      console.log(`⏳ Waiting for confirmation... (${retries}/${maxRetries})`);
      retries++;
      await new Promise((resolve) => setTimeout(resolve, 1000));
    }
  }

  console.log('⏰ Transaction timeout - check manually on Seiscan');
}
```

### Troubleshooting Guide

| Issue                 | Cause                   | Solution                    |
| --------------------- | ----------------------- | --------------------------- |
| "Insufficient funds"  | Low SEI balance         | Add more SEI to your wallet |
| "Transaction failed"  | Gas estimation error    | Reduce transaction amount   |
| "Network error"       | RPC connection issue    | Check RPC URL in .env       |
| "Slippage too high"   | Price moved during swap | Increase slippage tolerance |
| "Invalid private key" | Incorrect key format    | Verify private key format   |

**Debug Commands:**

```bash theme={"dark"}
# Check network connection
curl -X POST https://evm-rpc.sei-apis.com \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}'

# Verify wallet balance
# Use Seiscan: https://seiscan.io/
```

### 5. Advanced Features & Customization

#### Multi-Protocol Strategy Example

```typescript theme={"dark"}
async function deFiStrategy() {
  const agent = new SeiAgentKit(process.env.SEI_PRIVATE_KEY, 'openai');

  try {
    // 1. Swap SEI for USDC via Symphony
    console.log('Step 1: Swapping SEI for USDC...');
    const swapTx = await agent.swap('10', '0x0', 'usdc_address');

    // 2. Supply USDC to Takara for lending
    console.log('Step 2: Supplying USDC to Takara...');
    const supplyTx = await agent.mintTakara('USDC', '5');

    // 3. Stake remaining SEI via Silo
    console.log('Step 3: Staking SEI via Silo...');
    const stakeTx = await agent.stake('5');

    // 4. Monitor positions
    console.log('Step 4: Monitoring positions...');
    const balance = await agent.getERC20Balance();

    console.log('✅ Multi-protocol strategy executed successfully!');
    console.log('📊 Final balance:', balance);
  } catch (error) {
    console.error('Strategy failed:', error.message);
    // Implement rollback logic if needed
  }
}
```

#### Monitoring & Alerts:

```typescript theme={"dark"}
// Set up monitoring for your agent
async function setupMonitoring() {
  const agent = new SeiAgentKit(process.env.SEI_PRIVATE_KEY, 'openai');

  // Monitor balance changes
  setInterval(async () => {
    const balance = await agent.getERC20Balance();
    if (parseFloat(balance) < 1.0) {
      console.warn('⚠️ Low balance alert:', balance);
      // Send alert to your monitoring system
    }
  }, 60000); // Check every minute

  // Monitor failed transactions
  agent.on('transactionFailed', (error) => {
    console.error('Transaction failed:', error);
    // Log to monitoring system
  });
}
```

#### Custom Protocol Integration

To extend the Cambrian Agent Kit for your own protocol, please follow this repository which explains how to add plugins to the agent kit so that it can support your protocol: [Cambrian Agents Plugin Guide](https://github.com/CambrianAgents/cambrian-plugin)
