Smart Contract Automation with AI Agents: A Developer's Guide
Combine AI agents with smart contracts for the ultimate automation stack. This guide shows how to build agents that monitor on-chain events, execute DeFi strategies, and self-manage crypto positions.
Builder of AI agents, crypto trading bots, and open-source automation tools. Sharing practical guides on how to build, deploy, and profit from AI and DeFi technology.
The AI + Smart Contract Stack
On-chain automation (smart contracts) and off-chain AI agents are a powerful combination:
- Smart contracts handle trustless, transparent execution on-chain
- AI agents handle complex reasoning and decision-making off-chain
Together, they create systems that are both intelligent and trustless.
Architecture Overview
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Off-chain AI Agent โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ LLM Reasoning Layer โ โ
โ โ โข Analyze market conditions โ โ
โ โ โข Generate strategy parameters โ โ
โ โ โข Risk assessment โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ ethers.js โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ RPC / Events
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ On-chain Smart Contracts โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Strategy Contract โ โ
โ โ โข Execute trades/swaps โ โ
โ โ โข Manage positions โ โ
โ โ โข Enforce safety limits โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Step 1: Monitor On-Chain Events with an AI Agent
import { ethers } from 'ethers'
import OpenAI from 'openai'
const provider = new ethers.JsonRpcProvider(process.env.RPC_URL)
const client = new OpenAI()
const UNISWAP_POOL_ABI = [
'event Swap(address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick)'
]
async function monitorAndAnalyze(poolAddress: string) {
const pool = new ethers.Contract(poolAddress, UNISWAP_POOL_ABI, provider)
pool.on('Swap', async (sender, recipient, amount0, amount1, sqrtPriceX96, liquidity, tick) => {
const swapData = {
amount0: ethers.formatEther(amount0),
amount1: ethers.formatUnits(amount1, 6),
tick: tick.toString()
}
// AI analyzes each significant swap
if (Math.abs(Number(swapData.amount0)) > 100) {
const analysis = await analyzeSwap(swapData)
if (analysis.action !== 'hold') {
await executeStrategy(analysis)
}
}
})
}
async function analyzeSwap(swapData: object): Promise<{ action: string; params: object }> {
const response = await client.chat.completions.create({
model: 'gpt-4o-mini',
messages: [{
role: 'user',
content: `Large swap detected: ${JSON.stringify(swapData)}. Should I react? Options: buy, sell, hold, rebalance. Return JSON.`
}],
response_format: { type: 'json_object' }
})
return JSON.parse(response.choices[0].message.content!)
}
Step 2: The Strategy Smart Contract
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol";
contract AIStrategyExecutor is Ownable {
ISwapRouter public immutable swapRouter;
// Only authorized AI agent can call execute
address public aiAgent;
// Safety limits set by owner
uint256 public maxTradeSize;
uint256 public dailyVolumeLimit;
uint256 public dailyVolume;
uint256 public lastVolumeReset;
event TradeExecuted(address tokenIn, address tokenOut, uint256 amountIn, uint256 amountOut);
modifier onlyAgent() {
require(msg.sender == aiAgent, "Not authorized agent");
_;
}
constructor(address _swapRouter, address _aiAgent) Ownable(msg.sender) {
swapRouter = ISwapRouter(_swapRouter);
aiAgent = _aiAgent;
maxTradeSize = 1 ether; // 1 ETH max per trade
dailyVolumeLimit = 10 ether; // 10 ETH max per day
}
function executeSwap(
address tokenIn,
address tokenOut,
uint256 amountIn,
uint256 minAmountOut,
uint24 fee
) external onlyAgent returns (uint256 amountOut) {
// Safety checks
require(amountIn <= maxTradeSize, "Exceeds max trade size");
// Reset daily volume if new day
if (block.timestamp > lastVolumeReset + 1 days) {
dailyVolume = 0;
lastVolumeReset = block.timestamp;
}
require(dailyVolume + amountIn <= dailyVolumeLimit, "Daily volume limit exceeded");
// Execute swap via Uniswap V3
ISwapRouter.ExactInputSingleParams memory params = ISwapRouter.ExactInputSingleParams({
tokenIn: tokenIn,
tokenOut: tokenOut,
fee: fee,
recipient: address(this),
deadline: block.timestamp + 15 minutes,
amountIn: amountIn,
amountOutMinimum: minAmountOut,
sqrtPriceLimitX96: 0
});
amountOut = swapRouter.exactInputSingle(params);
dailyVolume += amountIn;
emit TradeExecuted(tokenIn, tokenOut, amountIn, amountOut);
}
}
Step 3: The Agent Calls the Contract
async function executeStrategy(analysis: { action: string; params: Record<string, unknown> }) {
const signer = new ethers.Wallet(process.env.PRIVATE_KEY!, provider)
const strategyContract = new ethers.Contract(
STRATEGY_CONTRACT_ADDRESS,
STRATEGY_ABI,
signer
)
if (analysis.action === 'buy') {
const tx = await strategyContract.executeSwap(
USDC_ADDRESS,
WETH_ADDRESS,
ethers.parseUnits('100', 6), // 100 USDC
ethers.parseEther('0.03'), // Min 0.03 ETH out
3000 // 0.3% fee tier
)
await tx.wait()
console.log(`Trade executed: ${tx.hash}`)
}
}
Security Considerations
1. Agent Key Management
Never hardcode private keys. Use:
- AWS KMS for key management
- Hardware wallets (Ledger) for large positions
- Separate hot wallet with limited funds for the agent
2. Smart Contract Safety Limits
Always include:
- Maximum trade size per transaction
- Daily volume limits
- Emergency pause mechanism
- Time-locked upgrades (if upgradeable)
3. Slippage Protection
Always set minimum output amounts:
// Calculate minimum with 1% slippage tolerance
const minAmountOut = expectedOutput * BigInt(99) / BigInt(100)
4. Monitoring and Alerts
// Alert if gas prices spike (bot might be overpaying)
const gasPrice = await provider.getGasPrice()
if (gasPrice > ethers.parseUnits('50', 'gwei')) {
await sendAlert('High gas prices detected โ pausing trading')
return
}
Common Patterns
- Keeper Bots โ Trigger smart contract functions when conditions are met
- Liquidation Bots โ Monitor and liquidate undercollateralized positions
- Rebalancing Bots โ Keep portfolio weights in target range
- Harvest Bots โ Compound yield farm rewards automatically
Get the Template
Our DeFi automation template includes all the above patterns with full documentation, test suite, and deployment scripts for mainnet and testnet.