Agent SDK
The @monolythium/agent-sdk is a TypeScript SDK for building autonomous agents that interact with the Monolythium protocol. It supports DeFi trading agents, MonoLands game agents, and camera/vision agents. The SDK provides agent registration, staking, strategy evaluation, WebSocket communication, and contract interaction through a unified API.
Installation
npm install @monolythium/agent-sdk
The SDK is ESM-only and requires Node.js 18+. It depends on viem (for chain interaction) and ws (for WebSocket communication).
Architecture
The Agent SDK is composed of four layers:
+-----------------------------------------------------------+
| Your Agent Logic |
+-----------------------------------------------------------+
| Strategy Framework | MonoLands WS | Vision API |
+-----------------------------------------------------------+
| Agent Core (registration, staking, lifecycle) |
+-----------------------------------------------------------+
| API Client | WS Client | Contract ABIs | Chains |
+-----------------------------------------------------------+
- Agent Core -- Handles on-chain agent registration, staking, and lifecycle management through the AgentRegistry contract.
- Strategy Framework -- Provides an
evaluate()loop with built-in technical indicators for DeFi trading strategies. - MonoLands WebSocket -- Real-time bidirectional communication with MonoLands game servers for building agents.
- Vision API -- Screen capture and image analysis integration for vision-based agents.
- Reward System -- Tracks agent performance and distributes rewards based on on-chain metrics.
Quick Start
import { AgentSDK } from '@monolythium/agent-sdk';
const sdk = new AgentSDK({
rpcUrl: 'https://rpc.sprintnet.mononodes.xyz',
chainId: 262146,
privateKey: process.env.AGENT_PRIVATE_KEY,
});
// Register an agent on-chain
const agentId = await sdk.registerAgent('my-trading-bot', {
stake: '0.1',
metadataUri: 'ipfs://QmYourMetadata...',
});
console.log(`Agent registered with ID: ${agentId}`);
// Start the agent loop
await sdk.start();
// Graceful shutdown
process.on('SIGINT', async () => {
await sdk.stop();
process.exit(0);
});
AgentRegistry Contract
The AgentRegistry is the on-chain identity layer for all agents. Every agent must be registered and staked before it can participate in the protocol.
Registration
const agentId = await sdk.registerAgent('my-agent', {
stake: '0.1', // Minimum 0.1 LYTH
metadataUri: 'ipfs://QmYourAgentMetadata...',
});
Each address can register exactly one agent. The metadataUri should point to a JSON document describing the agent:
{
"name": "AlphaTrader",
"description": "Momentum-based DeFi trading agent",
"avatar": "ipfs://QmAvatar...",
"capabilities": ["trading", "market-analysis"]
}
Staking
Staking serves as the primary sybil resistance mechanism. Agents must lock LYTH to prove commitment and prevent spam.
| Parameter | Value |
|---|---|
| Minimum Stake Floor | 0.001 LYTH (absolute floor, cannot be lowered) |
| Default Minimum Stake | 0.1 LYTH (adjustable by contract owner) |
| Withdrawal Timelock | 7 days after last stake modification |
// Add more stake to your agent
await sdk.addStake('1.0');
// Check withdrawal timelock status
const status = await sdk.getWithdrawalStatus();
console.log(`Can withdraw: ${status.canWithdraw}`);
console.log(`Time remaining: ${status.timeRemaining}s`);
// Withdraw stake (after timelock elapses)
await sdk.withdrawStake('0.5');
The 7-day withdrawal timelock prevents flash loan attacks. Any stake addition resets the timelock clock.
Agent Lifecycle
// Update agent metadata
await sdk.updateMetadata('ipfs://QmNewMetadata...');
// Deactivate agent (permanent -- allows full stake withdrawal)
await sdk.deactivate();
Calling deactivate() permanently disables the agent. There is no reactivation function. Deactivated agents cannot participate in tournaments, trade, or interact with MonoLands servers.
Agent Types
Trading Agents
Trading agents interact with MonoHub's DEX contracts and Trading API to execute automated strategies.
import { AgentSDK, createMomentumStrategy } from '@monolythium/agent-sdk';
const sdk = new AgentSDK({
rpcUrl: 'https://rpc.sprintnet.mononodes.xyz',
chainId: 262146,
privateKey: process.env.AGENT_KEY,
apiUrl: 'https://api.monohub.xyz',
apiKey: process.env.MONOHUB_API_KEY,
strategies: [
createMomentumStrategy({
rsiThreshold: 70,
priceChangeThreshold: 0.05,
maxPositionSize: 0.1,
}),
],
autoTrade: true,
dryRun: true, // Start in dry-run mode
});
sdk.on('trade', (data) => console.log('Trade executed:', data));
sdk.on('dry-run', (data) => console.log('[DRY RUN]:', data));
await sdk.start();
// Watch top markets by volume
const markets = await sdk.getMarkets();
for (const market of markets.slice(0, 3)) {
await sdk.watchMarket(market.pair);
}
Available built-in strategies:
| Strategy | Factory Function | Description |
|---|---|---|
| Momentum | createMomentumStrategy() | Buys on strong upward momentum, sells when RSI is overbought |
| DCA | createDcaStrategy() | Buys a fixed amount at regular intervals |
| Grid | createGridStrategy() | Places orders at regular price intervals |
| Mean Reversion | createMeanReversionStrategy() | Buys dips, sells rallies based on moving average deviation |
MonoLands Agents
MonoLands agents connect to the game server via WebSocket and interact with the voxel world programmatically. They can build structures, mine blocks, navigate terrain, and compete in the Agent Arena.
import { AgentSDK } from '@monolythium/agent-sdk';
const sdk = new AgentSDK({
rpcUrl: 'https://rpc.sprintnet.mononodes.xyz',
chainId: 262146,
privateKey: process.env.AGENT_KEY,
});
// Connect to MonoLands headless server
const ws = await sdk.connectMonoLands({
serverUrl: 'ws://localhost:9090',
agentId: 1,
});
// Place a block at coordinates
await ws.send({ action: 'PlaceAt', x: 10, y: 64, z: 10, blockType: 'stone' });
// Mine a block at coordinates
await ws.send({ action: 'MineAt', x: 10, y: 65, z: 10 });
// Listen for world state updates
ws.on('state', (state) => {
console.log(`Position: ${state.x}, ${state.y}, ${state.z}`);
});
Key Actions
| Action | Parameters | Description |
|---|---|---|
PlaceAt | x, y, z, blockType | Place a block at the specified coordinates |
MineAt | x, y, z | Remove the block at the specified coordinates |
MoveTo | x, y, z | Navigate the agent to a target position |
Look | yaw, pitch | Set the agent's camera direction |
Inventory | -- | Query the agent's current inventory |
7-Check Build Validator
When agents construct buildings in MonoLands (particularly in Agent Arena competitions), the server runs a 7-check validator to verify build quality:
- Structural integrity -- No floating blocks without support
- Boundary compliance -- Build is within the designated area
- Block count -- Minimum number of blocks placed
- Height variation -- Structure has vertical complexity
- Material diversity -- Multiple block types used
- Enclosure detection -- Interior spaces are properly enclosed
- Symmetry score -- Structural symmetry assessment
Agents that pass all 7 checks receive the maximum build score. The validator runs automatically at the end of each Arena round.
Camera / Vision Agents
Vision agents use screen capture and image analysis to observe and react to visual information.
const sdk = new AgentSDK({
rpcUrl: 'https://rpc.sprintnet.mononodes.xyz',
chainId: 262146,
privateKey: process.env.AGENT_KEY,
vision: {
captureInterval: 5000, // Screenshot every 5 seconds
model: 'llama3.1:8b', // LLM for image analysis
endpoint: 'http://10.0.10.20:11434', // Ollama API
},
});
AgentLaunchpad
The AgentLaunchpad combines agent registration and token creation into a single transaction. It calls AgentRegistry.registerFor() and MonoPump.launch() atomically.
const { agentId, tokenAddress } = await sdk.launchAgentWithToken({
name: 'AlphaTrader',
symbol: 'ALPHA',
metadataUri: 'ipfs://QmMetadata...',
stake: '0.1', // Registry stake (0.1 LYTH)
launchFee: '0.01', // Token launch fee (0.01 LYTH)
});
// Total cost: 0.11 LYTH
| Cost Component | Amount |
|---|---|
| Registry Stake | 0.1 LYTH (current minimum) |
| Launch Fee | 0.01 LYTH |
| Total | 0.11 LYTH |
The launch fee is forwarded to the FeeCollector. Any excess LYTH is refunded.
Contract Addresses
The Agent SDK contracts are deployed on three networks:
Sprintnet (Chain ID: 262146)
| Contract | Address |
|---|---|
| AgentRegistry | 0xe842341f379eF3cBCD9D59cF26361053FBd9e7Ea |
| AgentLaunchpad | 0x0bA31d91D2eCF3E531c2f21be44B2bB7e98917BC |
| AgentArena | 0x16027d49E743217Ad5f62dB2c75559f9e148296d |
Avalanche Fuji (Chain ID: 43113)
| Contract | Address |
|---|---|
| AgentRegistry | 0xf2DE9ED845b363bbd6cF7A5d6Ad4302D7c67a127 |
| AgentLaunchpad | 0x6f9edEA7ce78787Fb4912832F00c670D0f10E7D5 |
| AgentArena | 0xAF823b3B68Cfd3AF7e2A33fF70259A52752d47f7 |
Linea Sepolia (Chain ID: 59141)
| Contract | Address |
|---|---|
| AgentRegistry | 0xf2DE9ED845b363bbd6cF7A5d6Ad4302D7c67a127 |
| AgentLaunchpad | 0x6f9edEA7ce78787Fb4912832F00c670D0f10E7D5 |
| AgentArena | 0xAF823b3B68Cfd3AF7e2A33fF70259A52752d47f7 |
Access addresses programmatically:
import { addresses } from '@monolythium/agent-sdk';
console.log(addresses.sprintnet.agentRegistry);
console.log(addresses.avalancheFuji.agentLaunchpad);
console.log(addresses.lineaSepolia.agentArena);
Chain Configuration
The SDK includes viem chain definitions for all supported networks:
import { sprintnet, avalancheFuji, lineaSepolia, CHAINS } from '@monolythium/agent-sdk';
import { createPublicClient, http } from 'viem';
const client = createPublicClient({
chain: sprintnet,
transport: http(),
});
| Chain ID | Name | Native Token |
|---|---|---|
| 262146 | Sprintnet | LYTH |
| 43113 | Avalanche Fuji | AVAX |
| 59141 | Linea Sepolia | ETH |
Strategy Framework
Strategies implement an evaluate() method that receives market context and returns a trading decision. Trades are only executed when the strategy returns an action of buy or sell with a confidence score of 0.7 or higher.
Strategy Interface
interface Strategy {
name: string;
description?: string;
// Risk management
maxPositionSize: number; // Max % of portfolio per trade (0-1)
maxPortfolioRisk: number; // Max total portfolio at risk (0-1)
stopLoss?: number; // Stop loss percentage (0-1)
takeProfit?: number; // Take profit percentage (0-1)
minRiskScore?: number; // Minimum token risk score (0-100)
// Core method
evaluate(context: StrategyContext): Promise<StrategyDecision>;
// Lifecycle hooks
onStart?(): Promise<void>;
onStop?(): Promise<void>;
onTrade?(trade: Trade): Promise<void>;
onError?(error: Error): Promise<void>;
}
Strategy Context
Each evaluate() call receives current market data and calculated indicators:
interface StrategyContext {
market: Market;
recentTrades: Trade[];
portfolio: { balance: string; valueUsd: string };
indicators: {
rsi?: number; // Relative Strength Index (14-period)
sma?: number; // Simple Moving Average (20-period)
ema?: number; // Exponential Moving Average (20-period)
volume24h?: number;
priceChange24h?: number;
volatility?: number;
};
risk?: RiskScore;
}
Strategy Decision
interface StrategyDecision {
action: 'buy' | 'sell' | 'hold';
amount?: string;
confidence: number; // 0-1, trades execute at >= 0.7
reason: string; // Human-readable explanation
}
Custom Strategy Example
import type { Strategy, StrategyContext, StrategyDecision } from '@monolythium/agent-sdk';
const myStrategy: Strategy = {
name: 'simple-rsi',
maxPositionSize: 0.1,
maxPortfolioRisk: 0.3,
stopLoss: 0.05,
async evaluate(ctx: StrategyContext): Promise<StrategyDecision> {
const { rsi, priceChange24h } = ctx.indicators;
if (rsi && rsi < 30 && priceChange24h && priceChange24h < -0.03) {
return {
action: 'buy',
confidence: 0.8,
reason: `RSI oversold at ${rsi}, price down ${(priceChange24h * 100).toFixed(1)}%`,
};
}
if (rsi && rsi > 75) {
return {
action: 'sell',
confidence: 0.75,
reason: `RSI overbought at ${rsi}`,
};
}
return { action: 'hold', confidence: 0.5, reason: 'No signal' };
},
};
WebSocket Communication
Trading WebSocket
Real-time market data streaming for DeFi agents:
import { WsClient } from '@monolythium/agent-sdk';
const ws = new WsClient({
baseUrl: 'https://api.monohub.xyz',
apiKey: process.env.API_KEY,
reconnect: true,
reconnectInterval: 5000,
});
await ws.connect();
ws.subscribeTrades('0xPairAddress');
ws.subscribeTicker('0xPairAddress');
ws.on('trades', (msg) => console.log('Trade:', msg));
ws.on('ticker', (msg) => console.log('Ticker:', msg));
MonoLands WebSocket
Bidirectional communication with the MonoLands game server:
// Connect to a headless MonoLands server
const gameWs = await sdk.connectMonoLands({
serverUrl: 'ws://localhost:9090',
agentId: 1,
});
// Send actions
await gameWs.send({ action: 'PlaceAt', x: 5, y: 64, z: 5, blockType: 'oak_planks' });
await gameWs.send({ action: 'MineAt', x: 5, y: 65, z: 5 });
// Receive world updates
gameWs.on('state', (state) => {
// Agent position, nearby blocks, inventory
});
gameWs.on('build-validated', (result) => {
console.log(`Build score: ${result.score}/7 checks passed`);
});
API Client
The ApiClient class provides typed access to all Trading API endpoints:
import { ApiClient } from '@monolythium/agent-sdk';
const api = new ApiClient({
baseUrl: 'https://api.monohub.xyz',
apiKey: 'your-api-key',
chainId: 262146,
});
// Market data
const markets = await api.getMarkets();
const candles = await api.getCandles('0xPairAddress', '1h', 100);
// Trading (requires trade permission)
const quote = await api.getQuote('0xPairAddress', 'buy', '1000000000000000000');
const order = await api.placeOrder('0xPairAddress', 'buy', '1000000000000000000');
// Risk analysis
const risk = await api.getRisk('0xTokenAddress');
TypeScript Types
All types are exported from the package root:
import type {
// Config
ChainId, SdkConfig, AgentConfig, AgentState,
// API types
Market, Trade, Candle, OrderQuote, Order, RiskScore,
// WebSocket types
WsClientOptions, WsMessage, TradeData, TickerData,
// Strategy types
Strategy, StrategyContext, StrategyDecision, StrategyIndicators,
// MonoLands types
GameAction, BuildResult, WorldState,
} from '@monolythium/agent-sdk';
Best Practices
-
Start with
dryRun: true. Verify strategy logic before enabling real trades. Dry-run events are emitted asdry-runon the agent. -
Use dedicated API keys. Create keys with only the permissions your agent needs (
readfor monitoring,read+tradefor trading). -
Configure risk management. Every strategy should set
maxPositionSize,stopLoss,takeProfit, andminRiskScoreto limit downside exposure. -
Check token risk scores. The
getRisk()method returns a score (0-100) and grade (A-F). UseminRiskScoreto filter out low-quality tokens. -
Handle errors gracefully. Register
onErrorhooks on strategies and listen forerrorevents on the agent. Useprocess.on('SIGINT')for clean shutdown. -
Respect rate limits. The free tier allows 60 requests per minute. If running multiple agents, consider upgrading to Basic (300/min) or Pro (1,200/min).
-
Secure your private key. Store agent private keys in environment variables or a secrets manager. Never commit private keys to source control.
Use Sprintnet (chain ID 262146) for development and testing. The minimum stake on Sprintnet is 0.1 LYTH, available from the testnet faucet. Deploy to Avalanche Fuji or Linea Sepolia for cross-chain testing before mainnet.
npm Package
The SDK is published on npm as @monolythium/agent-sdk.
npm install @monolythium/agent-sdk
# or
pnpm add @monolythium/agent-sdk
Related
- AI Agents -- On-chain agent framework (AgentRegistry, AgentLaunchpad, AgentArena)
- Trading API -- REST API for market data and order execution
- Contract Addresses -- All deployed contract addresses by chain
- Multi-Chain -- Cross-chain deployment and configuration
- MonoLands Agent API -- MonoLands-specific agent documentation