git clone https://github.com/elizaos/elizaos.git
cd elizaos
npm install
npm run start
This gives you a local MCP server and agent runtime for testing.
Understanding On-Chain AI Agents
What exactly is an on-chain AI agent? In my experience, it’s code that autonomously reacts to blockchain events or off-chain triggers, executing smart contract calls without continuous human intervention. These agents often encapsulate the AI model inference off-chain or via zkML to reduce gas costs and then sign transactions using wallet keys.
Key components include:
- Agent Wallet: Holds the funds and signs transactions; must be tightly secured.
- Smart Contract Logic: Defines agent behavior, often upgradeable or managed through account abstraction (e.g., ERC-4337).
- Integration Protocols: MCP servers or payment protocols like x402 for compensating the AI logic.
For a working setup guide, see onchain-ai-agent-setup.
Key Frameworks and SDKs Overview
Several community-built SDKs help bootstrap your agent development. Here’s a quick factual breakdown:
| Framework |
Language(s) |
Chain Support |
License |
Maturity & Notes |
| ElizaOS |
TypeScript/Node |
EVM Chains, L2s |
MIT |
Early; MCP native, good dev tooling |
| Solana Agent Kit |
Rust/TypeScript |
Solana |
Apache 2.0 |
Production usage, performant |
| GOAT SDK |
Python/JS |
EVM + Some L2s |
GPLv3 |
Modular, but limited docs |
| Rig Framework |
Rust |
EVM-based + L2 |
MIT |
Strong on security, fast |
| Fetch.ai uAgents |
Python/Rust |
EVM + Cosmos chains |
Apache 2.0 |
zkML support, experimental |
Each has trade-offs. For example, ElizaOS’s MCP server integration is mature but restricted to EVM chains, whereas Solana Agent Kit offers high throughput but requires Rust proficiency.
Compare detailed docs on framework-comparison.
Step-by-Step: Deploying a Simple On-Chain AI Agent
Here’s a bare-bones example deploying an ElizaOS agent that calls a smart contract method periodically.
Prerequisites: Node.js, Goerli wallet with test ETH, ElizaOS cloned and running locally.
- Define the smart contract ABI and address:
const CONTRACT_ADDRESS = "0xYourTestnetContract";
const CONTRACT_ABI = ["function updateState(uint256 newValue)"];
- Configure agent wallet and provider:
import { ethers } from 'ethers';
const provider = new ethers.providers.JsonRpcProvider('https://goerli.infura.io/v3/YOUR_API_KEY');
const wallet = new ethers.Wallet(process.env.AGENT_PRIVATE_KEY!, provider);
- Instantiate the contract:
const contract = new ethers.Contract(CONTRACT_ADDRESS, CONTRACT_ABI, wallet);
- Agent logic (pseudo-code):
async function agentLoop() {
// Example: increment contract state each interval
try {
const tx = await contract.updateState(Math.floor(Date.now() / 1000));
console.log("Tx sent:", tx.hash);
await tx.wait();
console.log("Tx confirmed");
} catch (error) {
console.error("Agent error:", error);
}
setTimeout(agentLoop, 60000); // Run every 60 seconds
}
agentLoop();
This demo reveals how agent wallets directly interact with smart contracts by signing transactions. It’s a basic pattern but solid groundwork for more sophisticated AI logic.
Security Best Practices: Agent Wallets and Spending Limits
My hard-learned lesson is never trust an agent wallet with unlimited power.
- Use session keys scoped by spending limits or time constraints.
- Avoid directly hardcoding private keys in source code; use environment variables or hardware-secured modules.
- Implement safe approvals for ERC-20 tokens with allowance caps.
- Consider account abstraction (ERC-4337) to enforce transaction validation policies on-chain.
Here’s an example of a spending limit pattern using session keys:
mapping(address => uint256) public sessionLimits;
function executeWithLimit(address sessionKey, uint256 amount) external {
require(msg.sender == sessionKey, "Not authorized");
require(amount <= sessionLimits[sessionKey], "Amount exceeds limit");
sessionLimits[sessionKey] -= amount;
// Continue with transaction logic
}
And remember, agent wallets can be drained by unsafe approvals or untrusted MCP servers. Lock down your payment channels and audit the entire wallet lifecycle.
More on this in agent-wallet-security.
MCP Server Integration and Payment Protocols
MCP (Model Context Protocol) servers enable off-chain AI model hosting and request orchestration with guaranteed payments.
To tie an agent to an MCP server, you:
- Register the agent with the MCP registry
- Configure x402 payment keys that the agent can use
- Use SDKs to send/receive AI model queries funded through crypto
Here’s a minimal example using ElizaOS SDK to call an MCP endpoint with x402 payments:
import { McpClient } from 'elizaos/mcp';
const mcp = new McpClient('https://mcp.testnet');
const requestPayload = { query: "get latest block info" };
const response = await mcp.callModel({
modelAddress: '0xModelContract',
paymentKey: agentPaymentKey,
payload: requestPayload
});
console.log("MCP response:", response);
These patterns are still evolving. For in-depth MCP setup, check the mcp-server-integration guide.
Troubleshooting Common Pitfalls
Some gotchas I’ve hit while building agents:
- RPC rate limits causing failed calls—use dedicated RPC endpoints or rate-limit your agent loops.
- Gas estimation failures when transaction payloads get complex; always specify gas manually or increase gas buffer.
- Session key expiration due to clock drift or state desync, locking out agent actions.
- Slither or Aderyn flagged security issues when deploying before audits: reentrancy, unchecked calls, or delegatecall misuse.
If you encounter errors like transaction underpriced or invalid signature, ensure private keys match wallet addresses and nonce synchronization is correct.
See FAQ for common developer queries and fixes.
Tool Comparison for Agent Development
Here’s a more detailed comparison highlighting pros and cons:
| Tool |
Strengths |
Limitations |
Language |
Chains Supported |
| ElizaOS |
Built-in MCP, active TypeScript dev |
Early release, limited docs |
TypeScript |
Ethereum (Goerli), L2s |
| Solana Agent Kit |
High throughput, Rust support |
Rust complexity, fewer tools |
Rust |
Solana |
| GOAT SDK |
Modular, popular in trading bots |
GPL license restricts usage |
Python/JS |
EVM + Layer 2 |
| Rig Framework |
Security-centric, audit-ready |
Smaller community |
Rust |
Ethereum + L2 |
| Fetch.ai uAgents |
zkML support, multi-chain |
Experimental, docs sparse |
Python/Rust |
Cosmos, EVM |
Choose based on your team’s language skills, target chains, and security requirements. For deeper comparisons, visit framework-comparison.
Testing and Simulating Agent Strategies on Forked Networks
Before I let any autonomous agent touch mainnet funds, I run it against a forked network. In my experience, this single habit catches the majority of logic errors in crypto ai agent development — the ones that only surface when real liquidity, slippage, and MEV enter the picture.
Why forking beats a plain testnet
Testnets have thin liquidity and stale pool states, so your agent's decisions look nothing like production. Forking mainnet at a specific block gives you real balances, real pool depths, and real oracle prices while spending zero gas.
## Fork mainnet locally with anvil (Foundry)
anvil --fork-url $RPC_URL --fork-block-number 21000000
Point your agent's RPC at http://127.0.0.1:8545, then impersonate a whale to fund the agent wallet:
cast rpc anvil_impersonateAccount 0xWhaleAddress
cast send $AGENT_WALLET --value 5ether --from 0xWhaleAddress --unlocked
What I always assert in a simulation
- Slippage tolerance — does the agent abort when price impact exceeds its threshold?
- Nonce handling — can it recover from a dropped or replaced transaction?
- Failure paths — what happens when a swap reverts mid-strategy?
I run each strategy across at least three historical blocks — a calm block, a high-volatility block, and a congested block. If the agent behaves identically in gas estimation and decision output across all three, only then does it graduate toward a real deployment.
Gas Optimization and Cost Management for Autonomous Agents
An autonomous agent that trades or rebalances on a schedule can quietly burn through its treasury on gas alone. Throughout my own crypto ai agent development work, cost control turned out to be as important as strategy quality — a profitable signal is worthless if fees eat the edge.
Where the cost actually goes
| Cost driver |
Typical impact |
My mitigation |
| Base fee spikes |
5–20x during congestion |
Gas-price ceiling + deferral queue |
| Redundant approvals |
~46k gas each |
Approve once with a bounded allowance |
| On-chain reads in loops |
Compounds per call |
Batch via multicall |
| Failed reverts |
Full gas lost |
Simulate with eth_call first |
Practical patterns I rely on
Simulate before sending. Every transaction goes through a dry eth_call so I never pay gas for a guaranteed revert.
try {
await contract.callStatic.executeSwap(params); // reverts here cost nothing
const tx = await contract.executeSwap(params, { maxFeePerGas });
} catch (e) {
logger.warn("Simulation failed, skipping tx", e.reason);
}
Set a hard gas ceiling. I give each agent a maxFeePerGas cap and a deferral queue — if the network is expensive, non-urgent actions wait rather than execute at any price.
Batch reads with multicall. Reading ten positions in one call instead of ten round-trips slashes both latency and RPC billing. Cheaper L2s like Base or Arbitrum are my default for high-frequency agents.
Monitoring and Observability for Production Crypto AI Agents
Deploying an agent is the easy part; knowing what it's doing at 3 a.m. is the hard part. In my experience, the difference between a hobby script and production-grade crypto ai agent development is a serious observability layer — you cannot trust what you cannot see.
The three signals I never skip
- Wallet balance drift — a sudden drop flags a compromised key or a runaway loop.
- Decision logs with rationale — every action stores the inputs, the model's reasoning, and the resulting tx hash.
- On-chain confirmation lag — a transaction stuck in the mempool means the agent's world-state is now stale.
A minimal structured-log pattern
I log every decision as structured JSON so it's queryable later, not buried in plain text:
logger.info({
event: "agent_action",
strategy: "rebalance",
txHash: receipt.hash,
gasUsed: receipt.gasUsed.toString(),
reasoning: decision.rationale,
walletBalance: balanceAfter,
});
Alerting rules that saved me
| Condition |
Threshold |
Action |
| Balance drop |
> 10% in 1h |
Pause agent, page me |
| Failed tx streak |
3 in a row |
Halt and require manual review |
| No heartbeat |
> 5 min silent |
Restart + alert |
I pipe these into a lightweight watcher that runs independently of the agent — because if the agent itself crashes, its own monitoring goes down with it. A separate heartbeat process is non-negotiable for anything holding real value.
Conclusion and Next Steps
Building on-chain crypto AI agents demands understanding both blockchain infrastructure and AI tooling intricacies. What I've found is that starting with a simple agent wallet setup and iterating with strong security controls is key. Then, layer in MCP interactions for monetized AI model calls.
Next, I’d recommend:
- Exploring the onchain-ai-agent-setup tutorial to get a working dev environment
- Testing your agents locally with ElizaOS or Solana Agent Kit
- Auditing smart contracts using Slither or Aderyn before mainnet deploy
- Experimenting with client-side key management and spending limit patterns in agent-wallet-security
Feeling stuck? Check the FAQ for common build issues and join community forums dedicated to agent development.
Happy building—and remember, on-chain AI is a rapidly evolving space with early tooling, so keep security front and center. Your agents’ wallets will thank you.
Internal links helpful for further reading: