How to Build AI Trading Agents with On-Chain Identity Guide
By Braincuber Team
Published on May 12, 2026
You build a trading bot. It runs, it trades, it makes decisions. But from the blockchain's perspective, it does not exist. There is just a wallet address, no identity, no record of what the agent is, who operates it, or what it is supposed to do. ERC-8004 solves this. It is a standard for AI Agent Identity Registry on Ethereum that defines a registry contract where agents can be registered with structured metadata, and every registration produces a unique, verifiable agentId. This complete beginner guide walks you through deploying the five smart contracts, registering your agent on-chain, connecting to the Kraken CLI, and building a verifiable trading agent with EIP-712 signed checkpoints and a live dashboard.
What You Will Learn:
- What ERC-8004 is and why on-chain agent identity matters for accountability
- How to deploy the five smart contracts: AgentRegistry, HackathonVault, RiskRouter, ReputationRegistry, and ValidationRegistry
- How to register your agent on-chain as an ERC-721 token with structured metadata
- How to install and configure the Kraken CLI for paper trading and live trading
- How the TradeIntent pattern works with EIP-712 cryptographic signing
- How the RiskRouter validates position size, drawdown, and trade frequency
- How to build the explanation layer with reasoning, checkpoints, and verifiable audit trails
- How to swap in your own trading strategy including LLM-powered agents
What Is ERC-8004 and Why Does It Matter?
ERC-8004 is a standard for AI Agent Identity Registry on Ethereum. It defines a registry contract where agents can be registered with structured metadata, and every registration produces a unique, verifiable agentId. Think of it like ENS (Ethereum Name Service), but for AI agents instead of human-readable names. Every agent registration stores the operator wallet, agent wallet, name, description, capabilities, registration timestamp, and active status.
| Field | Type | Purpose |
|---|---|---|
| operatorWallet | address | Owns the ERC-721 token, pays gas |
| agentWallet | address | Hot wallet the agent uses for signing trades |
| name | string | Human-readable agent name |
| capabilities | string[] | e.g. ["trading", "analysis", "eip712-signing"] |
Prerequisites
Node.js 20+
Node.js 20 or higher installed for running the trading agent template, Hardhat deployment scripts, and the live dashboard.
Sepolia ETH
Sepolia testnet ETH from a faucet like sepoliafaucet.com for deploying contracts and paying gas for agent registration.
Infura or Alchemy
A Sepolia RPC URL from Infura or Alchemy for deploying contracts and submitting on-chain transactions.
Kraken Account
A Kraken Pro account for API keys, or use sandbox mode for paper trading during development and testing.
Step 1: Clone the Repo and Install Dependencies
Clone the AI Trading Agent Template
Clone the repository from https://github.com/Stephen-Kimoi/ai-trading-agent-template, navigate into it, and run npm install. This installs Hardhat, ethers.js, the OpenAI-compatible client, and all other dependencies needed for the five smart contracts, the agent loop, and the dashboard.
git clone https://github.com/Stephen-Kimoi/ai-trading-agent-template
cd ai-trading-agent-template
npm install
cp .env.example .env
Step 2: Configure Your Environment
Fill In Your .env File
Fill in your SEPOLIA_RPC_URL from Infura or Alchemy and your PRIVATE_KEY for the operator wallet. Optionally provide a separate AGENT_WALLET_PRIVATE_KEY for the hot signing wallet. The operator wallet owns the ERC-721 token and pays gas. The agent wallet signs TradeIntents and checkpoints at runtime. For testing, the same key for both is fine.
SEPOLIA_RPC_URL=https://sepolia.infura.io/v3/YOUR_KEY
PRIVATE_KEY=0xYOUR_OPERATOR_WALLET_PRIVATE_KEY
AGENT_WALLET_PRIVATE_KEY=0xYOUR_HOT_WALLET_KEY
Step 3: Deploy the Five Smart Contracts
Deploy AgentRegistry, Vault, RiskRouter, Reputation, and Validation
Run npx hardhat run scripts/deploy.ts --network sepolia. The script deploys AgentRegistry (ERC-721), HackathonVault, RiskRouter, ReputationRegistry, and ValidationRegistry. It outputs all five contract addresses. Copy them to your .env file. If integrating with an existing shared deployment, use those addresses instead and skip this step.
Step 4: Register Your Agent On-Chain
Register Your Agent as an ERC-721 Token
Run npm run register. This mints an ERC-721 token with your agent metadata (name, agentWallet, capabilities) and returns a unique agentId that becomes the agent's permanent on-chain identity. The script also sets default risk params. Add AGENT_ID to your .env. Verify the registration on Sepolia Etherscan by checking the AgentRegistered event on the registry contract.
Why ERC-721 for Agent Identity
The agentId is a uint256 token ID that is stable, unique, and gas-efficient to store. The token is transferable: you can sell a well-performing agent along with its on-chain reputation. Standard ERC-721 interfaces mean wallets, marketplaces, and indexers understand it natively.
Step 5: Install and Configure the Kraken CLI
Install Kraken CLI and Generate API Keys
Install the Kraken CLI with the install script from GitHub. Log into kraken.com, choose Kraken Pro, go to Settings then API, and create a new key with Query, Create and modify orders, Query open orders, and Cancel and close orders permissions. Copy the key and secret into your .env. Set KRAKEN_SANDBOX=true to start with paper trading. Verify your setup with kraken --sandbox --json balance.
Step 6: Understanding the TradeIntent and RiskRouter Flow
The full trading flow works as follows: the strategy produces a TradeDecision, the agent builds a TradeIntent struct, signs it with EIP-712 using the agentWallet, submits it to the RiskRouter for validation, and if approved, executes the trade via the Kraken CLI. Every step is on-chain and every approval or rejection is a permanent event.
Strategy decision (TradeDecision)
↓
Build TradeIntent struct
↓
Sign with EIP-712 (agentWallet)
↓
RiskRouter.submitTradeIntent(intent, signature)
├── verifies EIP-712 signature
├── checks nonce (replay protection)
├── checks deadline
├── validates risk params
├── emits TradeApproved or TradeRejected
↓ (if approved)
Kraken CLI: placeOrder()
↓
Vault tracks capital
| RiskRouter Check | What It Validates |
|---|---|
| Deadline | Is the intent still valid or expired? |
| Nonce | Does it match the stored nonce (no replay)? |
| Signature | Does it recover to the registered agentWallet? |
| Position Size | Is amountUsdScaled at most maxPositionSize? |
| Trade Frequency | Are we within maxTradesPerHour? |
struct TradeIntent {
uint256 agentId;
address agentWallet;
string pair; // e.g. "XBTUSD"
string action; // "BUY" or "SELL"
uint256 amountUsdScaled; // USD * 100
uint256 maxSlippageBps; // max acceptable slippage
uint256 nonce; // replay protection
uint256 deadline; // Unix timestamp
}
Step 7: EIP-712 Signed Checkpoints
Every trade decision is cryptographically signed by the agent's private key over structured data that includes the agentId, timestamp, action, amount, price, reasoning hash, confidence, and intent hash. EIP-712 is the Ethereum standard for signing typed structured data as opposed to raw bytes. It produces human-readable signing prompts in wallets and prevents signature replay attacks across different contracts and chains. A signature proves the signer held the private key at signing time, the signed data has not been modified, and the signature was intended for this specific contract and chain.
const domain = {
name: "AITradingAgent",
version: "1",
chainId: 11155111, // Sepolia
verifyingContract: REGISTRY_ADDRESS,
};
const types = {
TradeCheckpoint: [
{ name: "agentId", type: "uint256" },
{ name: "timestamp", type: "uint256" },
{ name: "action", type: "string" },
{ name: "asset", type: "string" },
{ name: "pair", type: "string" },
{ name: "amountUsdScaled", type: "uint256" },
{ name: "priceUsdScaled", type: "uint256" },
{ name: "reasoningHash", type: "bytes32" }, // keccak256(reasoning)
{ name: "confidenceScaled", type: "uint256" },
{ name: "intentHash", type: "bytes32" },
],
};
The reasoningHash uses keccak256 of the reasoning string to keep the signed payload compact while still committing to the full explanation. The reasoning string is stored alongside the checkpoint in checkpoints.jsonl for full auditability. Anyone can verify a checkpoint signature using ethers.verifyTypedData and confirm the reasoning hash matches the original string.
Step 8: Run the Agent and Dashboard
Start the Agent Loop and the Live Dashboard
In Terminal 1 run npm run run-agent. The agent warms up for 5 ticks collecting price samples from Kraken, then starts making trading decisions every 30 seconds (configurable via POLL_INTERVAL_MS). In Terminal 2 run npm run dashboard and open http://localhost:3000 to see the live price, last decision, price chart, agent info, and checkpoint feed that auto-refreshes every 5 seconds.
Explanation Layer Is Built In
Every TradeDecision must include a reasoning string. The reasoning flows through the terminal, the signed checkpoint, checkpoints.jsonl, and the dashboard automatically. Example: "Price fell 1.2% over last 5 ticks while volume dropped 40% below average. Bearish divergence selling to reduce exposure." The reasoningHash inside the EIP-712 signature cryptographically commits to this explanation.
Step 9: Swap In Your Own Trading Strategy
Everything below the scaffolding layer is replaceable. The template provides three strategy options out of the box. The default MomentumStrategy uses price arithmetic. A ClaudeStrategy stub and a GroqStrategy stub are also included. Implement the TradingStrategy interface with your own analyze() method and swap the import in src/agent/index.ts. The identity layer, vault, risk checks, exchange client, checkpoints, and dashboard all run unchanged.
export class MyStrategy implements TradingStrategy {
async analyze(data: MarketData): Promise<TradeDecision> {
const action = data.price > data.vwap ? "BUY" : "SELL";
return {
action,
asset: "XBT",
pair: data.pair,
amount: 100,
confidence: 0.7,
reasoning: `Price (${data.price}) is ${action === "BUY" ? "above" : "below"} VWAP (${data.vwap}).`,
};
}
}
| Layer | Customizable? | How |
|---|---|---|
| Trading strategy | Yes | Implement TradingStrategy |
| Trading pair | Yes | TRADING_PAIR in .env |
| Poll interval | Yes | POLL_INTERVAL_MS in .env |
| Risk parameters | Yes | setRiskParams() call |
| ERC-8004 identity | Fixed | Same for all agents |
| Kraken API client | Fixed | src/exchange/kraken.ts |
| EIP-712 format | Fixed | src/explainability/checkpoint.ts |
Frequently Asked Questions
What is ERC-8004 and how is it different from ENS?
ERC-8004 is a standard for AI Agent Identity Registry on Ethereum. Like ENS gives human-readable names to wallets, ERC-8004 gives structured identities to AI agents with operatorWallet, agentWallet, capabilities, and on-chain metadata stored in a registry contract.
Why does the agent identity use an ERC-721 NFT?
The agentId is a uint256 ERC-721 token ID that is stable, unique, and gas-efficient to store. The token is transferable so you could sell a well-performing agent with its on-chain reputation. Standard ERC-721 interfaces mean wallets, marketplaces, and indexers understand it natively.
Can I use a different exchange instead of Kraken?
Yes, the KrakenClient in src/exchange/kraken.ts is the only exchange adapter layer. Swapping Kraken for another exchange only requires replacing this one file with the new exchange's API client.
Do I need an LLM API key to run the trading agent?
No. The default MomentumStrategy uses price arithmetic with no external API calls. LLM strategies (Claude, Groq) are optional and can be swapped in by uncommenting the stub in src/agent/strategy.ts and adding the relevant API key.
How do I switch from paper trading to live trading?
Set KRAKEN_SANDBOX=false in your .env, ensure your vault has allocated capital for your agent, set sensible risk params via setRiskParams(), and monitor the dashboard for live decisions and signed checkpoints.
Need Help with AI Trading Agents?
Our experts can help you build AI trading agents with on-chain identity, deploy smart contracts, implement custom strategies, and set up verifiable checkpoint systems for production trading.
