Skip to content

xuanbach0212/somnia-agent-kit

Repository files navigation

Somnia Agent Kit

Production-ready SDK for building autonomous AI agents on Somnia blockchain

npm version License: MIT TypeScript

Complete toolkit for building AI agents on blockchain - combines AI reasoning, smart contracts, autonomous runtime, and real-time monitoring.


πŸ“š Documentation & Package

πŸ“– Full Documentation on GitBook - Complete guides, tutorials, examples, and API reference

πŸ“¦ npm Package - Install and use the SDK


Key Features: Autonomous Agents β€’ Smart Contracts β€’ LLM Integration β€’ Token Management β€’ Multicall Batching β€’ Monitoring β€’ CLI Tools


πŸš€ Quick Start

# Install
npm install somnia-agent-kit

# Or install globally for CLI
npm install -g somnia-agent-kit
import { SomniaAgentKit, SOMNIA_NETWORKS } from 'somnia-agent-kit';

// Option 1: With manual config
const kit = new SomniaAgentKit({
  network: SOMNIA_NETWORKS.testnet,
  contracts: {
    agentRegistry: '0xC9f3452090EEB519467DEa4a390976D38C008347',
    agentManager: '0x77F6dC5924652e32DBa0B4329De0a44a2C95691E',
    agentExecutor: '0x157C56dEdbAB6caD541109daabA4663Fc016026e',
    agentVault: '0x7cEe3142A9c6d15529C322035041af697B2B5129',
  },
  privateKey: process.env.PRIVATE_KEY, // Optional
});

// Or: Auto-load from .env (recommended)
const kit = new SomniaAgentKit();

await kit.initialize();

// Register an agent
await kit.contracts.registry.registerAgent(
  'My AI Agent',
  'Trading bot for DeFi',
  'QmX...', // IPFS hash
  ['trading', 'defi'] // capabilities
);

πŸ“– Usage Guide

Initialize SDK

import { SomniaAgentKit } from 'somnia-agent-kit';

// Auto-load config from .env
const kit = new SomniaAgentKit();
await kit.initialize();

Work with Agents

// Register new agent
const tx = await kit.contracts.registry.registerAgent(
  'My AI Agent',
  'Trading bot for DeFi',
  'QmX...', // IPFS hash
  ['trading', 'defi'] // capabilities
);
await tx.wait();

// Query agents
const totalAgents = await kit.contracts.registry.getTotalAgents();
const agent = await kit.contracts.registry.getAgent(1);
console.log(agent.name, agent.owner, agent.isActive);

Manage Vault & Funds

import { parseEther, formatEther } from 'somnia-agent-kit';

// Get agent address
const agent = await kit.contracts.registry.getAgent(agentId);
const agentAddress = agent.owner;

// Deposit native tokens to vault
await kit.contracts.vault.depositNative(agentAddress, {
  value: parseEther('1.0')
});

// Check balance
const balance = await kit.contracts.vault.getNativeBalance(agentAddress);
console.log(`Balance: ${formatEther(balance)} STT`);

// Withdraw funds
await kit.contracts.vault.withdrawNative(
  agentAddress,
  recipientAddress,
  parseEther('0.5')
);

Create & Execute Tasks

// Create task for agent
const tx = await kit.contracts.manager.createTask(
  agentId,
  JSON.stringify({ action: 'analyze', symbol: 'ETH/USD' }),
  { value: parseEther('0.001') } // Payment
);
await tx.wait();

// Execute task
await kit.contracts.executor.execute(taskId);

Build Autonomous Agent

import { Agent, OllamaAdapter, LLMPlanner } from 'somnia-agent-kit';

const agent = new Agent({
  name: 'Trading Bot',
  description: 'Automated DeFi trading',
  capabilities: ['analyze', 'trade', 'monitor'],
  llm: new OllamaAdapter({ model: 'llama3.2' }),
  planner: new LLMPlanner(),
  triggers: [
    { type: 'interval', config: { interval: 60000 } } // Run every minute
  ],
  memory: { enabled: true, maxSize: 1000 }
});

// Start agent
await agent.start();

// Stop agent
await agent.stop();

Use LLM for AI Reasoning

import { OllamaAdapter, OpenAIAdapter } from 'somnia-agent-kit';

// Local AI (FREE)
const ollama = new OllamaAdapter({
  baseURL: 'http://localhost:11434',
  model: 'llama3.2'
});

const response = await ollama.chat([
  { role: 'user', content: 'Should I buy ETH now?' }
]);

// OpenAI
const openai = new OpenAIAdapter({
  apiKey: process.env.OPENAI_API_KEY
});

const analysis = await openai.chat([
  { role: 'system', content: 'You are a DeFi trading expert' },
  { role: 'user', content: 'Analyze ETH price trend' }
]);

Token Operations

import { ERC20Manager, ERC721Manager } from 'somnia-agent-kit';

// ERC20 tokens
const erc20 = new ERC20Manager(kit.getChainClient());
await erc20.transfer(tokenAddress, recipientAddress, amount);
const balance = await erc20.getBalance(tokenAddress, walletAddress);
const allowance = await erc20.getAllowance(tokenAddress, owner, spender);

// ERC721 NFTs
const erc721 = new ERC721Manager(kit.getChainClient());
await erc721.transferNFT(nftAddress, fromAddress, toAddress, tokenId);
const owner = await erc721.getOwner(nftAddress, tokenId);

Batch Contract Calls (Multicall)

import { MultiCall } from 'somnia-agent-kit';

const multicall = new MultiCall(kit.getChainClient());

// Batch multiple reads in one call
const results = await multicall.aggregate([
  {
    target: registryAddress,
    callData: registry.interface.encodeFunctionData('getAgent', [1])
  },
  {
    target: vaultAddress,
    callData: vault.interface.encodeFunctionData('getNativeBalance', [agentAddress])
  },
  {
    target: registryAddress,
    callData: registry.interface.encodeFunctionData('getTotalAgents')
  }
]);

Monitor Agent Activity

import { Logger, Metrics, Dashboard } from 'somnia-agent-kit';

// Structured logging
const logger = new Logger({ level: 'info' });
logger.info('Agent started', { agentId: 1, timestamp: Date.now() });
logger.error('Task failed', { taskId: 123, error: 'Timeout' });

// Track metrics
const metrics = new Metrics();
metrics.recordLLMCall(250, true); // duration, success
metrics.recordTransaction('0x...', true, 0.001);
console.log(metrics.getSummary());

// Web dashboard
const dashboard = new Dashboard({ port: 3001 });
await dashboard.start();
// Visit http://localhost:3001

CLI Usage

# Install CLI globally
npm install -g somnia-agent-kit

# Initialize project
sak init

# Agent management
sak agent:list
sak agent:register --name "My Bot"
sak agent:info --id 1

# Task operations
sak task:create --agent-id 1 --data '{"action":"analyze"}'
sak task:status --task-id 123

# Wallet operations
sak wallet:balance
sak wallet:send --to 0x... --amount 1.0

# Network info
sak network:info

πŸ“¦ Smart Contracts

Deployed on Somnia Testnet (Chain ID: 50312)

Contract Address
AgentRegistry 0xC9f3452090EEB519467DEa4a390976D38C008347
AgentManager 0x77F6dC5924652e32DBa0B4329De0a44a2C95691E
AgentExecutor 0x157C56dEdbAB6caD541109daabA4663Fc016026e
AgentVault 0x7cEe3142A9c6d15529C322035041af697B2B5129

RPC: https://dream-rpc.somnia.network
Explorer: https://explorer.somnia.network


βš™οΈ Configuration

Create .env file:

# Network
SOMNIA_RPC_URL=https://dream-rpc.somnia.network
SOMNIA_CHAIN_ID=50312

# Private Key (optional - only for write operations)
PRIVATE_KEY=0x...

# Contract Addresses
AGENT_REGISTRY_ADDRESS=0xC9f3452090EEB519467DEa4a390976D38C008347
AGENT_MANAGER_ADDRESS=0x77F6dC5924652e32DBa0B4329De0a44a2C95691E
AGENT_EXECUTOR_ADDRESS=0x157C56dEdbAB6caD541109daabA4663Fc016026e
AGENT_VAULT_ADDRESS=0x7cEe3142A9c6d15529C322035041af697B2B5129

# LLM API Keys (optional)
OPENAI_API_KEY=sk-...
DEEPSEEK_API_KEY=sk-...

πŸ“š Additional Documentation

Local documentation files:


πŸ“‚ Examples

Check out the examples directory:

Run examples:

npx ts-node examples/01-quickstart/index.ts

πŸ› οΈ Development

# Clone repository
git clone https://github.com/xuanbach0212/somnia-agent-kit.git
cd somnia-agent-kit

# Install dependencies
pnpm install

# Build all packages
pnpm build

# Run tests
pnpm test

# Build specific package
pnpm build:kit

πŸ“¦ Project Structure

somnia-agent-kit/
β”œβ”€β”€ packages/
β”‚   └── agent-kit/          # Main SDK package
β”‚       β”œβ”€β”€ src/
β”‚       β”‚   β”œβ”€β”€ core/       # Blockchain SDK
β”‚       β”‚   β”œβ”€β”€ runtime/    # Autonomous agents
β”‚       β”‚   β”œβ”€β”€ llm/        # LLM integration
β”‚       β”‚   β”œβ”€β”€ monitor/    # Monitoring
β”‚       β”‚   β”œβ”€β”€ tokens/     # Token management
β”‚       β”‚   └── cli/        # CLI tools
β”‚       └── dist/           # Built files
β”œβ”€β”€ contracts/              # Smart contracts
β”‚   β”œβ”€β”€ contracts/          # Solidity files
β”‚   β”œβ”€β”€ scripts/            # Deploy scripts
β”‚   └── test/               # Contract tests
β”œβ”€β”€ examples/               # Usage examples
β”œβ”€β”€ docs/                   # Documentation
└── test/                   # Integration tests

πŸ”— Links

Package & Documentation

Somnia Network


πŸ“„ License

MIT License - see LICENSE for details.


Built with ❀️ for Somnia Network

About

SDK for building and managing AI agents on Somnia blockchain. Features LLM integration, smart contracts, token management, and real-time monitoring.

Topics

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors