Cambrian Agent Kit
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 .
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.
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
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 fees
2. Project Setup
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
:
OPENAI_API_KEY=your_openai_api_key
SEI_PRIVATE_KEY=your_wallet_private_key
RPC_URL=https://evm-rpc.sei-apis.com
Important Security Notes:
- Never share your private key: Your private key controls your funds
3. Running Your First Agent
npm run test
The following is the output and interaction with the Cambrian Agent:
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
Understanding the Transaction:
- SEI Address:
0x0
represents native SEI token in the agent kit - Transaction Hash: Can be verified on SeiTrace
- Gas Fees: Automatically calculated and deducted from your balance
4. Explore Core Features & Protocols
a) Check Token Balance with Error Handling
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
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');
}
}
}
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
c) Liquid Staking with Silo Protocol
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');
}
}
}
Silo Staking Details:
- iSEI Token: Represents your staked SEI plus auto-compounded rewards
- No Unbonding Period: Immediate liquidity unlike traditional staking
- 5% Fee: Annual management fee of 5% on rewards
- MEV Benefits: Validators share MEV profits with stakers
d) Lending/Borrowing with Takara Protocol
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
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');
}
}
}
/tools/
for more advanced protocol integrations!Error Handling & Troubleshooting
Common Error Types
Comprehensive Error Handling Examples:
// 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');
}
}
}
Transaction Monitoring
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 SeiTrace');
}
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:
# 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 SeiTrace: https://seitrace.com/
5. Advanced Features & Customization
Multi-Protocol Strategy Example
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:
// 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
Resources & Additional Information
Official Documentation
- SEI Documentation: https://docs.sei.io
- SEI Explorer: https://seitrace.com/
- Takara Lend: https://mirror.xyz/0x6C4AF8f4822e4dA0E4BC2D892c0433D6880c34b2/lvoT-BZawdsNHTa3cFJMTfcRSzua2ZKExNvNn1HdWhY
- Silo Protocol: https://silostaking.gitbook.io/silo-staking
- Citrex Markets: https://app.citrex.markets
- Symphony Exchange: https://symph.ag
Security Resources
- DeFi Security Guide: https://blog.chain.link/defi-security-best-practices/
- Smart Contract Security: https://www.certik.com/resources/blog/top-10-defi-security-best-practices
- Error Handling: https://www.halborn.com/blog/post/understanding-error-handling-vulnerabilities-in-solidity
Wrap Up & Next Steps
- You’ve set up, explored, and customized the Cambrian Agent Kit for SEI
- You understand the security considerations and best practices
- You know how to handle errors and troubleshoot issues
- You can safely interact with multiple DeFi protocols
- Try plugging into your own frontend, build agentic chatbots, or automate complex strategies
- For more, check out CambrianAgents/sei-agent-kit on GitHub , Cambrian Twitter , and Docs
Pro Tips for Production:
- Start Small: Begin with small transaction amounts
- Test Thoroughly: Test extensively before production deployment
- Monitor Actively: Set up comprehensive monitoring
- Stay Updated: Keep up with protocol updates and security advisories
- Community: Join the SEI community for support
All examples above can be mixed and matched for your specific use case. You can focus only on Takara, Silo, or Citrex as needed.
Conclusion
Building powerful, autonomous AI agents on SEI that can interact with multiple DeFi protocols (Takara, Silo, Citrex, Symphony) simultaneously only takes a few lines of code, and is even more succinct if you’re already familiar with blockchain development and JavaScript/TypeScript.
To view the complete demo application leveraging the code snippets covered throughout this document, take a look at the GitHub repository .