Building an on-chain AI agent is one thing. Making sure it has a secure, manageable wallet that can interact with smart contracts autonomously? That’s a whole other ballgame. If you’re asking, "how to build an onchain AI agent" with a robust, safe wallet architecture, you’re in the right place.
In this guide, I’ll share concrete steps and code snippets for setting up your AI agent’s crypto wallet, managing keys securely, and leveraging account abstraction standards like ERC-4337 to enable session keys and spending limits. We’ll look at real trade-offs and common gotchas from my experience building deployed agents with spending limits and smart approvals.
Ready to give your AI agent a blockchain wallet that won’t get drained overnight? Let’s get started.
Unlike human wallets controlled by manually held private keys or hardware devices, an AI agent’s wallet needs design for autonomy while limiting risks. The agent holds private keys off-chain (either on a secure node or MPC network), signs transactions programmatically, and interacts with chains without human approval each time.
But what happens if an agent’s wallet is compromised? That unchecked private key can drain your funds at lightning speed. And many builders overlook this in early development.
I believe wallet setup is the foundation of sustainable agent deployment. It’s not just about "give AI agent a blockchain wallet;" it’s how you architect keys, sessions, and spending behaviors for real-world resilience.
Several wallet paradigms exist for AI agent integration, but these stand out:
Smart accounts combined with account abstraction standards are becoming the norm. They let you deploy session keys—temporary or scoped keys that sign on behalf of the agent wallet within strict limits.
| Wallet Type | Language Support | Chains | Maturity | Pros | Cons |
|---|---|---|---|---|---|
| EOA | Any | All EVM | Stable | Simple, widely supported | No spending limits, all keys must be secured |
| Smart Contract | Solidity | EVM + L2s | Growing adoption | Custom logic for approvals | Gas overhead, can be attacked if poorly designed |
| ERC-4337 / EIP-7702 | Solidity + client SDKs | EVM chains | Beta / tested on testnets | Session keys, modular security | Complex setup, evolving spec |
The best choice depends on your agent’s role. If your AI agent is only signing small batch trades or low-value ops, EOAs with tight off-chain controls might pass. Larger on-chain agents almost always benefit from session keys and spending limits.
Every AI agent wallet starts with private keys held off-chain, accessible to your signing system. Protect these like gold. Use encrypted storage, hardware wallets (or HSMs), or multi-party computation (MPC) schemes if possible.
Session keys are a game-changer.
They’re ephemeral or scoped keys authorized by the main wallet smart contract to execute transactions on the agent’s behalf. You might limit:
An example is ERC-4337’s UserOperation format that enables off-loading authorization logic to paymasters or bundlers.
Setting explicit spending limits is essential. Even if a session key is compromised, the wallet contract enforces limits on token amount or frequency.
In my last deployment, I wired up per-session spending caps tied into the smart contract wallet-based agent. This prevented runaway gas fees and unauthorized token transfers even when the off-chain key server was briefly exposed.
Here’s a simplified session key approval snippet in Solidity:
mapping(address => SessionKey) public sessionKeys;
struct SessionKey {
uint256 expires;
uint256 spendingLimit;
bool active;
}
function approveSessionKey(address key, uint256 limit, uint256 duration) external onlyWalletOwner {
sessionKeys[key] = SessionKey(block.timestamp + duration, limit, true);
}
function validateSessionKey(address key, uint256 amount) internal view {
require(sessionKeys[key].active, "Key not active");
require(block.timestamp <= sessionKeys[key].expires, "Session key expired");
require(amount <= sessionKeys[key].spendingLimit, "Over spending limit");
}
ERC-4337 has made account abstraction accessible without a consensus-layer protocol change. It allows wallets to be smart contracts that process externally created "UserOperations."
This means your AI agent wallet can accept session keys signed off-chain, verify them on-chain, and impose strict rules before execution.
Practical benefits include:
Start by deploying a smart account contract following the ERC-4337 standard; then use a bundler (like OpenGSN or custom MCP server) to relay agent transactions.
Be aware: the standard is still evolving, and tooling maturity varies by chain and provider.
Here’s a minimal example using a smart account with session keys. Assume using Hardhat + Solidity for local testing.
// SmartAccount.sol (simplified)
pragma solidity ^0.8.0;
contract SmartAccount {
address public owner;
mapping(address => bool) public sessionKeys;
constructor(address _owner) {
owner = _owner;
}
modifier onlyOwnerOrSessionKey() {
require(msg.sender == owner || sessionKeys[msg.sender], "Unauthorized");
_;
}
function addSessionKey(address _key) external {
require(msg.sender == owner, "Only owner");
sessionKeys[_key] = true;
}
function exec(address to, uint256 value, bytes calldata data) external onlyOwnerOrSessionKey returns (bool) {
(bool success,) = to.call{value: value}(data);
require(success, "Tx failed");
return success;
}
}
// deploy.js
async function main() {
const [owner, sessionKey] = await ethers.getSigners();
const SmartAccount = await ethers.getContractFactory("SmartAccount");
const wallet = await SmartAccount.deploy(owner.address);
await wallet.deployed();
console.log("SmartAccount deployed to:", wallet.address);
await wallet.connect(owner).addSessionKey(sessionKey.address);
console.log("Added session key:", sessionKey.address);
}
main();
async function sendTx() {
const [owner, sessionKey] = await ethers.getSigners();
const wallet = await ethers.getContractAt("SmartAccount", "<deployed_wallet_address>");
// Session key calls exec to send ETH to some address
let tx = await wallet.connect(sessionKey).exec("0xRecipientAddress", ethers.utils.parseEther("0.01"), "0x");
await tx.wait();
console.log("Transaction sent by session key");
}
Note: This basic example lacks spending limits or expiration. That’s left as an exercise — many ERC-4337 wallets embed these controls in session key validation.
For production, plug into an ERC-4337 bundler framework and review gas and replay protections.
Security often feels like a never-ending war.
Here’s a practical checklist for any AI agent wallet setup:
In my experience, the biggest leak risks come from off-chain key exposure and unlimited token approvals. Don’t underestimate these attack surfaces.
Often this means session keys are expired, not yet approved, or trying to perform disallowed actions. Double-check your contract’s session key map state and expiration timestamps.
Smart contract wallets with complex validation sometimes break gas estimate tooling. Use manual gas limits or inspect bundle transactions via RPC directly.
If you skip nonce or replay protection mechanisms, attackers can reuse signed operations. ERC-4337 generally handles this, but your custom wrappers must too.
ERC-4337 adoption differs across chains and SDKs. Test your agent wallet contract on your target chain’s testnets and consult the latest docs.
Gotchas like these caused me to shift from vanilla EOAs to smart account session keys with enforced spending limits.
| Tool / SDK | Language | Features | Chains Supported | Maturity |
|---|---|---|---|---|
| ElizaOS | Rust | AI agent runtime & wallet mgmt | EVM, Polkadot | Early / evolving |
| AgentKit | TypeScript | Wallet abstraction + AI agents | Ethereum, Layer2 | Stable |
| GOAT SDK | Python | Smart wallet + MEV optimizations | EVM | Beta |
| Slither | Solidity | Static analyzer (security) | N/A | Mature |
| Aderyn | Solidity | Smart contract security linting | N/A | Growing |
I’ve worked with ElizaOS and AgentKit—the tradeoffs I’ve noticed relate mostly to language ecosystem preferences (Rust vs TS) and documentation detail. Whichever you pick, integrate security checks and key management early.
For more about choosing frameworks, see the framework comparison page.
Giving your AI agent a blockchain wallet isn’t just a technical step—it’s the foundation of your agent’s autonomy and security.
Start by picking the right wallet type—smart contracts with ERC-4337 account abstraction make session keys and spending limits manageable. Securely handle private keys off-chain, set scoped session key permissions, and test everything thoroughly on testnets.
Remember, wallet security is an ongoing process. Use tools like Slither or Aderyn to catch contract risks early and handle approvals cautiously.
Ready to move deeper? Check out detailed tutorials on building agents with ElizaOS or AgentKit, or get into audit pipelines and MCP server integrations next:
Got questions or errors running your wallet? The FAQ addresses common developer pain points.
Building secure on-chain AI agents is challenging but possible. Add spending limits and session keys early, and you’ll save yourself from painful headaches later. Happy coding!