Live Demo: frontend-nine-theta-22.vercel.app Β |Β GitHub: github.com/dddd86971-cloud/yield-agent
Built for OKX Build X AI Hackathon β Season 2, X Layer Arena Track.
YieldAgent is an autonomous AI liquidity strategist that manages Uniswap V3 concentrated-liquidity positions on X Layer. A user describes their intent in one sentence; the AI parses it, runs three parallel analysis brains (Market Β· Pool Β· Risk), deploys a real V3 LP position via the OnchainOS Agentic Wallet TEE, and continuously monitors / rebalances / compounds β all without human intervention, with every reasoning step permanently anchored on-chain.
Core Value Proposition:
- One-sentence deploy: "Deploy 100 USDT as LP, conservative" β real V3 NFT minted on X Layer
- Three-Brain AI: Market + Pool + Risk brains evaluate every 5 minutes
- TEE-signed execution: All DEX transactions signed inside OnchainOS Agentic Wallet (ERC-4337)
- On-chain audit trail: Every AI decision (including "do nothing") is recorded on-chain via
DecisionLogger - Copy-trading: FollowVault lets anyone mirror agent strategies with one click
- Per-wallet PnL tracking: Historical value + fees curves scoped to each connected browser wallet
- Cross-protocol yield aggregator: Live opportunities via OnchainOS
defi searchacross every X Layer DEX - Restart-survival persistence: File-based JSON snapshots for strategies, history, and PnL points (no SQLite native-dep headaches)
- Proactive AI chat: PnL / Position / History / Suggest quick-commands generate grounded recommendations on demand
What makes YieldAgent different: Unlike chatbot wrappers that only suggest trades, YieldAgent is a fully autonomous agent that plans, executes, monitors, rebalances, and compounds real on-chain positions β with every reasoning step permanently anchored on-chain for verifiability, and every snapshot recoverable across restarts.
This build pushed the project past the v1 demo into a production-ready feature set. What landed in the latest round:
| Area | Delta |
|---|---|
| Persistence | New PersistenceService β debounced JSON writes to data/strategies.json, data/history.json, data/pnl-snapshots.json. Full restart survival; no native deps. |
| Multi-tenant state | AgentCoordinator.getStateForWallet(address) + per-wallet WebSocket filtering. Every browser wallet sees only its own strategy. |
| PnL tracking | New /app/pnl dashboard with pure-SVG dual-axis chart (position value + fees). capturePnLSnapshot() writes on every full evaluation. |
| Pool catalogue | New /app/pools page β live on-chain state for every supported pool + cross-protocol opportunities from OnchainOS defi search. |
| Proactive AI chat | Quick-command handlers for pnl / position / history / suggest (EN + δΈζ). getProactiveSuggestion() generates grounded recommendations. |
| Richer system prompt | buildChatSystemPrompt() replaces JSON.stringify(state) dumps with a tight context block (strategy, market, pool, risk, PnL, quick-command hints). |
| CLI footprint reduction | Generic TTL read-cache in OnchainOSAdapter (LRU-bounded at 128 entries). Cuts subprocess spawn count by ~90% under frontend polling load. |
| New REST endpoints | /api/strategies, /api/pnl/:strategyId, /api/pnl, /api/pnl/refresh, /api/defi/opportunities β all wallet-scoped where relevant. |
| Fix: WETH/USDT typo | Corrected fB β fC in 5th byte of WETH/USDT pool address across backend config. |
| Fix: IntentInput dead UI | Removed misleading pool selector whose state was never propagated. |
Inspired by the Build X AI Season 2 winners β Helios (Most Active Agent, multi-agent x402 economy) and XSight (Best x402 Implementation, API-as-revenue) β v3 turns YieldAgent from "automated LP" into "an agent economy that pays its own ops".
| Upgrade | Status | What Changes |
|---|---|---|
| x402 micropayments | π Designed | Coordinator pays each Brain ~0.0001 USDG per call via EIP-3009. After seed funding, the economy is self-sustaining. |
| Brain-per-wallet | π Designed | Each Brain (Market / Pool / Risk / Lending) gets its own sovereign TEE wallet. Coordinator becomes the orchestrator routing payments. |
| Aave V3 Lending Brain | π Designed | New 4th brain β idle USDT auto-supplies to Aave V3 for baseline yield while LP cycles complete. |
| All 14 OnchainOS skills | π§ In Progress | Currently using 6/14. Adding defi-invest, defi-portfolio, dex-signal, dex-token, security, audit-log, onchain-gateway, dex-ws. |
| Stdio MCP server | π Designed | Expose deploy / analyze / status / pnl as MCP tools so Claude Code / Cursor / Claude Desktop can plug in directly. |
| Explicit FSM + 4 hard circuit breakers | π Designed | Take-profit β₯+30%, drawdown β€-20%, time stop β₯30 days, IL beyond user tolerance. |
| CLI deploy wizard | π Designed | npx yield-agent init β auto-runs OnchainOS login Γ 4, scaffolds .env, runs self-check. |
x402PaymentLog contract |
π Designed | Per-payment on-chain audit trail β every brain micropayment emits a PaymentSettled event. |
Full v3 spec: ARCHITECTURE_V3.md β includes target architecture diagram, x402 economy detail, cycle state machine, and 7-14 day implementation plan.
Visual asset: docs/v3-architecture.svg β 1600Γ900 image suitable for blog posts and social media.
Where AI agents bet on themselves.
| Contract | Address | OKLink |
|---|---|---|
| AgentRegistry | 0x93F88966879E2AcaE3FdDEC08DAb6CbD4ab8d141 |
view β |
| AgentArenaHook | 0x25ff94A5E694343F2919A693E5ab9AFF2E825AC0 |
view β |
| V4 Pool (USDT/WOKB, dynamic fee) | PoolId 0xae2fec12631fc349f8d96e203f19f68d92f3d20eca53c5aee4dcb2ca4a9916e7 |
bound to PoolManager 0x360Eβ¦fb32 |
Hook permission verification: lower-14 bits of 0x25ff94A5β¦825AC0 = 0x1AC0 β exactly matches AFTER_INIT | BEFORE_ADD_LIQ | BEFORE_REMOVE_LIQ | BEFORE_SWAP | AFTER_SWAP β V4 PoolManager accepted the hook because the bits in the address mathematically prove which callbacks it implements.
| # | Operation | Tx |
|---|---|---|
| 1 | AgentRegistry deploy | 0x47602β¦85888 |
| 2 | AgentArenaHook deploy (CREATE2 mined) | 0x62374β¦ee986 |
| 3 | Authorize hook in registry | 0x58001β¦38002 |
| 4 | V4 Pool initialize (afterInitialize fired) | 0xfd23aβ¦d7748 |
| 5 | USDT approve for stake | 0xe358aβ¦4dbd4 |
| 6 | YieldAgent registration | 0x1efabβ¦30ff0 |
| 7 | First StrategyBond submission | 0x3f1c4β¦328dd |
| 8 | runElection β YieldAgent is Active Manager | 0x1a1b9β¦31627 |
| 9 | settleEpoch β SLASH 1.25 USDT to LP sink, Epoch 1 β 2 β | 0x097d6β¦d51f |
Phase 1 (Bid): YieldAgent β 2.5 USDT bond, 18% APR commitment
Phase 2 (Election): YieldAgent wins (only bidder, score = highest)
Phase 3 (Operation): 4 hours elapsed, 0 real swaps β 0 fees
Phase 4 (Settle): actualAPR (0%) << promisedAPR (18%) β slash 1.25 USDT
Phase 5 (Payout): LP sink received 1.25 USDT β performance floor honored
Phase 6 (Rep): 10000 β 9251 (matches integration test prediction exactly)
Phase 7 (Advance): Epoch 2 auto-opened, bidding restarts
This is the first complete on-chain Agent Performance Bond cycle in DeFi history β verifiable end-to-end via the 9 tx hashes above.
cast call 0x25ff94A5E694343F2919A693E5ab9AFF2E825AC0 \
"getActiveManager(bytes32)(address)" \
0xae2fec12631fc349f8d96e203f19f68d92f3d20eca53c5aee4dcb2ca4a9916e7 \
--rpc-url https://rpc.xlayer.tech
# β 0x2E2FC9d6daf5044F53412eb49dF5e82a9cFB3838 (YieldAgent)YieldAgent's first StrategyBond commits to: 18% APR Β· fee 30β80 bps Β· max 6 rebalances Β· Β±200 tick range Β· 2.5 USDT staked. Settlement (slash or reward) runs automatically 4 hours after epoch start.
Built for Hook the Future Hackathon (X Layer Γ Uniswap Γ Flap, 5/22β5/28 2026) β a Uniswap V4 hook that creates an open marketplace for AI agents to compete for the right to manage V4 LP positions.
Each epoch (4 hours):
- AI agents submit TEE-signed StrategyBonds (stake + signed commitment of fee range, max rebalances, promised APR)
- Hook elects winner via
score = stake Γ promisedAPR Γ reputation / committed_bandβ tighter band β higher confidence β higher score - Active Manager controls dynamic fee + LP modifications for the epoch
- Hook enforces every committed parameter in real-time via
beforeSwap/beforeAddLiquiditycallbacks - Failure to meet bond triggers automatic slashing β slashed funds go directly to LPs as a hard performance floor
This is the first on-chain Agent Performance Bond. Other DEXes let humans speculate on prices; AgentArena lets LPs speculate on AI strategy quality, with cryptographic enforcement.
| Path | Lines | Role |
|---|---|---|
hook/src/AgentArenaHook.sol |
470 | V4 hook β 5 callbacks + bid auction + election + epoch settlement + spec enforcement |
hook/src/AgentRegistry.sol |
230 | Agent registration, stake escrow, reputation tracking, slashing |
hook/src/libraries/StrategyBond.sol |
80 | Bond struct + EIP-712 hash + bid score formula + spec validation |
hook/src/interfaces/IAgentArena.sol |
70 | Shared errors + events |
hook/script/DeployHook.s.sol |
90 | HookMiner CREATE2 mining + mainnet deploy + registry authorization |
hook/script/InitPool.s.sol |
70 | Initialize V4 USDT/WOKB pool with dynamic fee + hook attached |
hook/script/RegisterAgent.s.sol |
90 | Register YieldAgent + submit first StrategyBond |
hook/test/AgentArenaHook.t.sol |
200 | Smoke tests β 5/5 passing |
Build:
cd hook && ./setup.sh # installs Uniswap V4 + V4 Hooks Public + OZ + forge-std + compiles
forge test --fork-url https://rpc.xlayer.tech # 15/15 passing on LIVE X LayerHeadline test: forked X Layer mainnet, block 60735890 β our hook is accepted by the real V4 PoolManager 0x360Eβ¦fb32:
=== Fork Deployment ===
Chain ID: 196
PoolManager: 0x360E68faCcca8cA495c1B759Fd9EEe466db9FB32 (real V4)
Hook: 0xA40AeA0b8cD8Fe8029a9d3a948376D1D49359ac0 (mined CREATE2)
Lower-14 flags: 0x1AC0 (matches required permissions exactly)
--- PoolManager.initialize() on LIVE X Layer ---
Initial tick: 0
currentEpoch: 1
epochStartTime: 1779504926
PROOF: V4 PoolManager on X Layer accepted our hook.
PROOF: afterInitialize callback executed.
--- Full Pipeline on Fork ---
2 agents bid β AgentA wins β epoch runs β settled
Slashed: 250 USDT
LP sink: 250 USDT (received slash flow)
Reputation: 10000 β 9251
Integration test (MultiAgentEpoch.t.sol):
test_FullEpochLifecycle_3AgentsCompete_AggressiveWinsAndGetsSlashed:
Confident score: 42,857,142,857
Cautious score: 3,508,771,929
Aggressive score: 59,523,809,523 β winner
Stake slashed: 250 USDT β LP sink received: 250 USDT
Reputation: 10000 β 9251
Now in Epoch 2 -- bidding open for next round
Deploy:
DEPLOYER_PK=0x... forge script script/DeployHook.s.sol --rpc-url xlayer --broadcast
HOOK_ADDR=0x... forge script script/InitPool.s.sol --rpc-url xlayer --broadcast
AGENT_PK=0x... HOOK_ADDR=0x... POOL_ID=0x... forge script script/RegisterAgent.s.sol --rpc-url xlayer --broadcastThis section exists to give evaluators (human or AI) a fast path from each scoring dimension to concrete, verifiable evidence in this repo.
| Dimension | Where to Look | Why It Scores |
|---|---|---|
| OnchainOS / Uniswap Integration | agent/src/adapters/OnchainOSAdapter.ts, agent/src/services/V3PositionManager.ts, agent/src/adapters/UniswapSkillsAdapter.ts |
Uses 6 OnchainOS commands as the primary execution path (not a fallback): wallet contract-call, swap execute, wallet login/status/addresses/balance, defi search/detail/positions. Both official Uniswap AI Skills (liquidity-planner@0.2.0, swap-planner@0.1.0) are ported verbatim and invoked every cycle. Routes real V3 NPM.mint() / collect() / decreaseLiquidity() through the TEE β verifiable via NFT #962 and tx 0x0856912bβ¦. |
| X Layer Ecosystem Contribution | contracts/, on-chain deployments (Β§ Deployment Addresses) |
Three contracts live on X Layer mainnet (chain 196): DecisionLogger, StrategyManager v2, FollowVaultFactory. Ultra-low gas enables logging every AI decision (including HOLD) β preserving the complete audit invariant. Two-signer split-key architecture proves anti-gaming: TEE signs DEX, audit EOA signs records, cross-referenceable 1:1. FollowVault brings copy-trading natively to X Layer. |
| AI / User Experience | frontend/src/components/AgentChat.tsx, agent/src/services/AgentCoordinator.ts (buildChatSystemPrompt, getProactiveSuggestion), frontend/src/app/app/pnl/page.tsx |
Three-Brain ensemble (Market + Pool + Risk) feeds GPT-4o-mini synthesis with on-chain TWAP, liquidity-planner ranges, and IL math. SSE streaming surfaces per-brain progress live in the UI. 8 quick-commands (deploy / analyze / status / pnl / position / history / suggest / why) in both EN + δΈζ. Proactive AI chat generates grounded recommendations via a richer context-block prompt (not a JSON.stringify(state) dump). Pure-SVG PnL dashboard, per-wallet state isolation, restart-survival persistence. |
| Product Completeness | Whole repo | 6 frontend routes (Landing, Dashboard, PnL, Pools, Decisions, Follow). 19 REST + SSE + WebSocket endpoints. 85 automated tests (68 Hardhat unit + 17 Playwright E2E). Full lifecycle proven on mainnet: deploy β mint β monitor β rebalance β compound β audit. Multi-tenant wallet-scoped state. Cross-protocol yield aggregator. JSON-based persistence with debounced writes. Live demo + verified tx hashes + end-to-end documentation. |
Key Differentiators (for at-a-glance scoring):
- Real V3 LP lifecycle, not just swaps β
NPM.mint(),collect(),decreaseLiquidity(), full rebalance, fee compounding β all signed by TEE. - Split-key anti-gaming proof β TEE signer physically cannot fabricate DEX transactions; audit records must match on-chain reality 1:1.
- Every decision is an on-chain event β including
HOLD, preserving a tamper-proof AI reasoning trail. - Both Uniswap AI Skills ported verbatim β not "inspired by", the actual methodology from the Uniswap AI repo.
- Multi-tenant ready today β per-wallet state, per-wallet WebSocket filtering, per-wallet PnL curves.
- OpenAI-optional β the three-brain snapshot endpoint works without any LLM; deterministic fallbacks everywhere.
Two architectures live in this README: v2 (current shipping) is what's deployed and verifiable on-chain right now. v3 (next sprint) is the multi-brain x402 economy designed in
ARCHITECTURE_V3.md.
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Frontend (Next.js 14 + Vercel) β
β Intent Input Β· Agent Chat (SSE) Β· Three-Brain Panel Β· V3 Positions β
β PnL Dashboard Β· Pool Catalogue Β· Decision Log Β· Follow Leaderboard β
ββββββββββββββββββββββ¬βββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ
β HTTP + SSE + WS β wagmi v2 (injected connector)
βΌ βΌ
ββββββββββββββββββββββββββββββββββββββββ βββββββββββββββββββββββββββββββββββ
β Agent Backend (Node.js + TS) β β X Layer Mainnet (196) β
β β β β
β ββββββββββββββββββββββββββββββββ β β βββββββββββββββββββββββββββββ β
β β IntentParser (GPT-4o-mini) β β β β YieldAgent Contracts β β
β β MarketBrain (on-chain TWAP) β β β β Β· DecisionLogger β β
β β PoolBrain (liquidity-plannerβ β β β Β· StrategyManager v2 β β
β β + swap-planner) β β β β Β· FollowVaultFactory β β
β β RiskBrain (IL math) β β β βββββββββββββββββββββββββββββ β
β β V3PositionManager ββββββΌβββΌβββΆ Uniswap V3 (X Layer) β
β β Β· mintViaTEE() β β β Β· Factory 0x4B2aβ¦ β
β β Β· collectViaTEE() β β β Β· NPM 0x315eβ¦ β
β β Β· rebalanceViaTEE() β β β Β· Router 0x4f0cβ¦ β
β β OnchainOSAdapter ββββββΌβββΌβββΆ OnchainOS TEE Signer β
β β Β· wallet contract-call β β β Agentic Wallet 0x6ab2β¦ β
β β Β· swap execute β β β β
β β AgentCoordinator (5min loop) β β β βββββββββββββββββββββββββββββ β
β ββββββββββββββββββββββββββββββββ β β β V3 LP NFT Positions β β
β β β β Β· NFT #962 (TEE mint) β β
β 19 REST endpoints + SSE + WebSocket β β β Β· NFT #966 (Strategy #9) β β
ββββββββββββββββββββββββββββββββββββββββ β βββββββββββββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β YieldAgent v3 β Multi-Brain x402 Economy on X Layer β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β User Layer (Next.js + Vercel) β
β Intent Β· Chat (SSE) Β· 3-Brain Panel Β· PnL Β· Pools Β· FollowVault β
βββββββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββ
β HTTP / SSE / WebSocket
βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β π§ Coordinator Agent (Orchestrator Β· TEE Wallet #1) β
β Β· 5-min cycle loop Β· GPT-4o-mini synthesis β
β Β· Pays brains via x402 USDG (EIP-3009 Β· ~0.0001 USDG / call) β
β Β· Wallet: 0x6ab2β¦ (Curator) β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β β β
β πΈ x402 β πΈ x402 β πΈ x402 β πΈ x402
β 0.0001 USDG β 0.0001 USDG β 0.0001 USDG β 0.0001 USDG
βΌ βΌ βΌ βΌ
βββββββββββββββ βββββββββββββββ βββββββββββββββ βββββββββββββββ
β π Market β β π Pool β β π‘οΈ Risk β β π¦ Lending β
β Brain β β Brain β β Brain β β Brain β
β β β β β β β (NEW v3) β
β TEE Wlt #2 β β TEE Wlt #3 β β TEE Wlt #4 β β TEE Wlt #5 β
β 0xMrkβ¦ β β 0xPolβ¦ β β 0xRskβ¦ β β 0xLndβ¦ β
ββββββββ¬βββββββ ββββββββ¬βββββββ ββββββββ¬βββββββ ββββββββ¬βββββββ
β TWAP β liquidity- β IL math β supply APR
β volatility β planner β health 0-100 β borrow rate
β trend state β swap-planner β exit trigger β idle-USDT
βΌ βΌ βΌ βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β X Layer Mainnet (chainId 196) β
β β
β βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββββββββββ β
β β Uniswap V3 β β Aave V3 β β OKX DEX (aggregator) β β
β β Β· NPM.mint β β Β· supply β β Β· cross-DEX routing β β
β β Β· collect β β Β· withdraw β β Β· best-price exec β β
β β Β· rebalance β β Β· borrow β β β β
β βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββββββββββ β
β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β YieldAgent Audit Contracts β β
β β Β· DecisionLogger β every decision (incl. HOLD) β β
β β Β· StrategyManager v2 β deploy + execution records β β
β β Β· FollowVaultFactory β ERC20 copy-trading vaults (90/10) β β
β β Β· x402PaymentLog β every brain micropayment (NEW in v3) β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Legend:
πΈ x402 micropayment β· Coordinator β Brain per-call settlement
π§ Coordinator β· pays its operators in real USDG (EIP-3009)
πππ‘οΈπ¦ Brain β· sovereign agent Β· independent TEE wallet
Why v3? The Build X AI Season 2 winners aligned on one thesis: "x402 + multi-agent". v3 closes that gap while keeping every v2 differentiator (real V3 LP lifecycle, verbatim Uniswap AI Skills port, DecisionLogger, FollowVault). Full design + cycle state machine + x402 economy detail in
ARCHITECTURE_V3.md.
| Signer | Address | Responsibility | Cannot Do |
|---|---|---|---|
| OnchainOS Agentic Wallet (TEE) | 0x6ab27b82890bc85cd996f518173487ece9811d61 |
All DEX txs: V3 mint, swap, approve, rebalance | Cannot write to audit contracts |
| Audit EOA | 0x2E2FC9d6daf5044F53412eb49dF5e82a9cFB3838 |
Audit records: deployStrategy, logDecision | Cannot sign DEX transactions |
This split-key design means a judge can cross-reference StrategyManager.getExecutions(strategyId) against the Agentic Wallet's on-chain activity β the tx hashes must match 1:1, because the audit signer physically cannot fabricate DEX transactions.
YieldAgent uses three distinct wallets, each with a clear responsibility:
| Wallet | Role | What It Does | What It Cannot Do |
|---|---|---|---|
Agentic Wallet (TEE) 0x6ab27b82... |
Executor | Signs all DEX txs: V3 mint, swap, approve, collect fees, rebalance | Cannot write audit records |
Audit EOA 0x2E2FC9... |
Recorder | Writes strategy records + decision logs to on-chain contracts | Cannot sign DEX transactions |
| User's Browser Wallet | Observer | Identity binding β records "who initiated this strategy" in the frontend | Does not sign any transaction, does not spend any funds |
The user's browser wallet connects via RainbowKit/wagmi but never signs transactions or spends tokens. All on-chain execution is handled by the Agentic Wallet inside the OnchainOS TEE.
The hackathon demo runs a single Agentic Wallet that manages all LP positions. This proves the core capability: an AI agent that autonomously deploys, monitors, rebalances, and compounds real V3 LP positions via TEE-signed transactions, with every decision permanently recorded on-chain.
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Current Demo (Hackathon) β
β β
β Any wallet βββ Connect to frontend βββ Initiate strategy β
β β β
β Shared Agent Backend βββ Single Agentic Wallet β
β 0x6ab27b82... β
β β β
β LP NFTs owned by Agentic Wallet, managed autonomously β
β Users observe their strategies via frontend (localStorage) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
The architecture is designed to scale from single-agent to full multi-tenant without code changes:
Phase 1 β Self-Hosted Agent (Available Now)
Any user can run their own isolated agent instance today:
- Create your Agentic Wallet:
onchainos wallet login --force - Get API keys from OnchainOS Dev Portal
- Clone this repo, fill
.envwith your own keys - Fund your Agentic Wallet with USDT + OKB on X Layer
- Run
cd agent && npm startβ your LP positions belong to your wallet
Each instance is fully self-contained. Zero code changes required.
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Phase 1: Self-Hosted (Available Now) β
β β
β User A βββ Own Backend βββ Own Agentic Wallet A β
β (.env: own keys) LP NFTs owned by Wallet A β
β β
β User B βββ Own Backend βββ Own Agentic Wallet B β
β (.env: own keys) LP NFTs owned by Wallet B β
β β
β Fully isolated. Each user controls their own funds. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Phase 2 β Managed Multi-Tenant Platform (Planned)
A hosted platform that provisions per-user Agentic Wallets automatically:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Phase 2: Managed Platform (Planned) β
β β
β User connects browser wallet β
β β β
β Platform creates Agentic Wallet via OnchainOS SDK β
β β β
β User funds their own Agentic Wallet (USDT + OKB) β
β β β
β Platform provisions isolated agent worker β
β β β
β AI manages LP using user's own Agentic Wallet β
β β β
β LP NFTs owned by user's TEE wallet β fully self-custodied β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Key features planned for Phase 2:
- One-click onboarding: connect wallet β auto-create Agentic Wallet β fund β deploy
- Per-user agent isolation: each user gets a dedicated agent worker with their own TEE signer
- Cross-strategy leaderboard: compare performance across all users' strategies on-chain
- Vault-based delegation: users who prefer not to run their own agent can deposit into FollowVault to mirror top-performing agents
Phase 3 β Decentralized Agent Network (Vision)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Phase 3: Decentralized Network (Vision) β
β β
β Agent operators stake OKB to run yield management nodes β
β β β
β Users delegate funds to agents via smart contract vaults β
β β β
β On-chain reputation system ranks agents by verified ROI β
β β β
β DecisionLogger provides transparent, auditable track recordβ
β β β
β Revenue sharing: agent takes performance fee, user keeps β
β the rest β enforced by smart contract, no trust required β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
| Contract | Address | Explorer |
|---|---|---|
| DecisionLogger | 0x5989f764bC20072e6554860547CfEC474877892C |
OKLink |
| StrategyManager v2 | 0x2180fA2e3F89E314941b23B7acC0e60513766712 |
OKLink |
| FollowVaultFactory | 0x9203C9d95115652b5799ab9e9A640DDEB0879F85 |
OKLink |
| Item | Value |
|---|---|
| Wallet Address | 0x6ab27b82890bc85cd996f518173487ece9811d61 |
| Account ID | 04c9d299-9e85-4c20-98c5-8f1f2a4bba36 |
| Type | ERC-4337 (OnchainOS TEE Signer) |
| Explorer | OKLink |
| Contract | Address |
|---|---|
| UniswapV3Factory | 0x4B2ab38DBF28D31D467aA8993f6c2585981D6804 |
| NonfungiblePositionManager | 0x315e413a11ab0df498ef83873012430ca36638ae |
| SwapRouter02 | 0x4f0c28f5926afda16bf2506d5d9e57ea190f9bca |
| Quoter | 0x976183ac3d09840d243a88c0268badb3b3e3259f |
| TickLens | 0x661e93cca42afacb172121ef892830ca3b70f08d |
| Operation | Tx Hash | Signed By |
|---|---|---|
| USDT approve β NPM | 0x6cf923cbβ¦ |
OnchainOS TEE |
| WOKB approve β NPM | 0xbcf17edeβ¦ |
OnchainOS TEE |
| NPM.mint() β NFT #962 | 0x0856912bβ¦ |
OnchainOS TEE |
| Swap Deploy (Strategy #1) | 0x8204ad49β¦ |
OnchainOS TEE |
Verify NFT #962 ownership:
cast call 0x315e413a11ab0df498ef83873012430ca36638ae \
"ownerOf(uint256)(address)" 962 --rpc-url https://rpc.xlayer.tech
# β 0x6ab27b82890bc85cd996f518173487ece9811d61 (Agentic Wallet)| Item | URL |
|---|---|
| Live Demo | frontend-nine-theta-22.vercel.app |
| Platform | Vercel (auto-deploy on git push) |
YieldAgent deeply integrates 6 OnchainOS core commands as the primary execution layer. All DEX transactions are routed through the Agentic Wallet TEE β the agent's local private key never signs DEX operations.
| OnchainOS Command | Where Used | Purpose |
|---|---|---|
onchainos wallet contract-call |
V3PositionManager.mintViaTEE(), collectViaTEE(), decreaseLiquidityViaTEE() |
Primary execution path β routes encoded calldata (V3 mint, approve, collect) through TEE signer |
onchainos swap execute |
AgentCoordinator.rebalanceViaOnchainOS() |
DEX swap via OKX aggregator for token rebalancing |
onchainos wallet login/status |
OnchainOSAdapter.checkWalletStatus() |
Agentic Wallet authentication and health check |
onchainos wallet addresses |
OnchainOSAdapter.getAddresses() |
Retrieve TEE wallet addresses |
onchainos wallet balance |
OnchainOSAdapter.getBalance() |
Query wallet balances on X Layer (chain 196) |
onchainos defi search/detail/positions |
OnchainOSAdapter.defiSearch(), defiDetail() |
Pool discovery, position tracking, market data |
Implementation: agent/src/adapters/OnchainOSAdapter.ts β wraps OnchainOS CLI as a spawned subprocess with structured JSON parsing.
Three-tier execution priority (code: AgentCoordinator.ts):
Priority 1: OnchainOS TEE β wallet contract-call β NPM.mint() β anti-gaming β
Priority 2: Direct PRIVATE_KEY β NPM.mint() β fallback
Priority 3: OnchainOS swap execute β legacy swap path
Both official Uniswap AI Skills are ported verbatim into the agent and invoked on every deploy/rebalance cycle:
| Skill | Version | Source | Where Called | Function |
|---|---|---|---|---|
| liquidity-planner | 0.2.0 |
Uniswap AI GitHub | PoolBrain.analyze() β UniswapSkillsAdapter.computeRangeCandidates() |
Pair classification (stable/correlated/major/volatile), tick-spacing table, range width recommendations, TVL assessment |
| swap-planner | 0.1.0 |
Uniswap AI GitHub | AgentCoordinator.rebalanceViaOnchainOS() β UniswapSkillsAdapter.planRebalanceSwap() |
Slippage ladder by pair type, price-impact k-factor estimation, minimum output calculation, split-swap for large orders |
Implementation: agent/src/adapters/UniswapSkillsAdapter.ts β runtime-callable port with methodology citation for every output.
Key integration points:
classifyPairType()β categorizes token pairs (stablecoin Β±0.5%, major Β±5-15%, volatile Β±30-100%)computeRangeCandidates()β generates optimal tick ranges for V3 LP positionsplanRebalanceSwap()β calculates slippage tolerance and split-swap strategy for rebalancing
| V3 Operation | Method | Signed By | Code |
|---|---|---|---|
| Mint LP position | NPM.mint() via TEE |
Agentic Wallet | V3PositionManager.mintViaTEE() |
| Collect trading fees | NPM.collect() via TEE |
Agentic Wallet | V3PositionManager.collectViaTEE() |
| Remove liquidity | NPM.decreaseLiquidity() via TEE |
Agentic Wallet | V3PositionManager.decreaseLiquidityViaTEE() |
| Full rebalance | remove β collect β re-mint | Agentic Wallet | V3PositionManager.rebalance() |
| Optimal token split | sqrtPrice-based ratio | Local compute | V3PositionManager.calculateOptimalAmounts() |
1. User Input
"Deploy 100 USDT as LP in OKB pool, conservative"
β
2. IntentParser (GPT-4o-mini)
β { principal: 100, riskProfile: "conservative", preferredPairs: ["USDT/OKB"] }
β
3. Three-Brain Parallel Analysis
βββββββββββββββ βββββββββββββββ βββββββββββββββ
β Market Brain β β Pool Brain β β Risk Brain β
β On-chain TWAPβ β liquidity- β β IL math, β
β volatility, β β planner β β health 0-100 β
β trend state β β range recs β β rebalance β
ββββββββ¬ββββββββ ββββββββ¬ββββββββ ββββββββ¬ββββββββ
βββββββββββββββββββΌββββββββββββββββββ
β
4. GPT-4o-mini Synthesis
β Action: DEPLOY | REBALANCE | HOLD | COMPOUND | EMERGENCY_EXIT
β Reasoning: "Market ranging, vol 0.94%, Pool APR 12.5%, Health 87%"
β Confidence: 95%
β
5. Execution (OnchainOS TEE)
V3PositionManager.deployLPViaTEE()
β approve USDT β approve WOKB β NPM.mint() β real V3 NFT
β
6. On-Chain Audit
StrategyManager.recordExecution(strategyId, txHash)
DecisionLogger.logDecision(strategyId, reasoning, confidence)
β
7. Continuous Monitoring
Every 5 min: Quick edge-proximity check
Every 30 min: Full three-brain re-analysis
Every 6 hours: Fee collection heartbeat
β
8. Auto-Rebalance (when triggered)
decreaseLiquidity β collect β re-mint at new optimal range
All via TEE, all logged on-chain
| Brain | Data Source | Output | Key Computation |
|---|---|---|---|
| Market Brain | On-chain TWAP, 2016-snapshot price buffer (~7 days) | Volatility, trend state, price momentum | Realised volatility (ATR-style), trend classification (trending_up/down/ranging/high_vol), whale detection |
| Pool Brain | slot0, liquidity, tick spacing, oracle observations + liquidity-planner methodology |
Recommended LP ranges, fee APR, IL estimate | Pair classification, tick-spacing snapping, TVL assessment, DexScreener data integration |
| Risk Brain | Current tick vs entry tick vs range bounds | Health 0-100, IL%, rebalance urgency | Concentrated-liquidity IL formula, edge proximity vs risk-profile threshold, per-profile (conservative/moderate/aggressive) calibration |
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Agent Monitor Loop β
β β
β Every 5 min: Quick check β
β β Is price near range edge? (>80% of range used) β
β β If urgent β trigger full evaluation immediately β
β β
β Every 30 min: Full three-brain evaluation β
β β Market + Pool + Risk analysis in parallel β
β β GPT-4o-mini synthesizes recommendation β
β β Execute if needed: REBALANCE / COMPOUND / EXIT β
β β Log decision on-chain (even HOLD) β
β β
β Every 6 hours: Fee compound heartbeat β
β β NPM.collect() via TEE β reinvest fees β
β β Record as COMPOUND audit entry β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
- Browse: Leaderboard ranks strategies by on-chain decision count with search, filter, sort, and pagination
- Follow: Connect browser wallet β approve USDT β deposit into FollowVault β receive vault shares (ERC20)
- Auto-mirror: Vault mirrors the agent's LP positions automatically
- Withdraw: Redeem shares anytime β agent takes 10% of profit, follower keeps 90%
| Method | Path | Purpose |
|---|---|---|
GET |
/api/health |
Full health probe: OnchainOS status, Uniswap Skills, chain info |
GET |
/api/state |
Current agent state (monitoring/idle/rebalancing) β wallet-scoped |
GET |
/api/strategies |
List active strategies owned by the connected wallet |
GET |
/api/history |
Evaluation history for the connected wallet |
GET |
/api/latest |
Latest three-brain evaluation |
GET |
/api/brains/snapshot |
Three-brain snapshot (no OpenAI required) |
POST |
/api/intent |
Natural language β structured UserIntent |
POST |
/api/analyze |
Run three-brain analysis |
POST |
/api/deploy |
Deploy strategy + mint V3 LP via TEE |
POST |
/api/monitor/start |
Start 5-min monitoring loop |
POST |
/api/monitor/stop |
Stop monitoring |
POST |
/api/chat |
Structured chat response |
POST |
/api/chat/stream |
SSE streaming chat with brain progress |
GET |
/api/v3/positions |
Real V3 NFT positions owned by agent |
GET |
/api/v3/pool/:address |
Real-time pool state (tick, liquidity, price) |
GET |
/api/pnl/:strategyId |
PnL time-series for a specific strategy (value + fees curve) |
GET |
/api/pnl |
Aggregate PnL across every strategy owned by the wallet |
POST |
/api/pnl/refresh |
Force a PnL snapshot capture outside the monitor loop |
GET |
/api/defi/opportunities |
Cross-protocol yield opportunities via OnchainOS defi search |
SSE |
/api/chat/stream |
Server-Sent Events for live token streaming + brain progress |
WS |
/ws |
Real-time state + evaluation + alert push (per-wallet filtered) |
| Page | Route | Features |
|---|---|---|
| Landing | / |
Hero, three-brain features, interactive chat widget, comparison, FAQ |
| Agent Dashboard | /app |
Intent input, deploy controls, V3 positions with range visualization, three-brain panel, agent chat (SSE streaming with 8 quick-commands), decision history |
| PnL Dashboard | /app/pnl |
Per-wallet historical value + fees time-series, pure-SVG dual-axis chart, ROI and annualized APR stats, cross-strategy aggregation |
| Pools | /app/pools |
Live on-chain state for every supported X Layer V3 pool + cross-protocol yield opportunities via OnchainOS defi search; one-click pre-fill flow into /app?pool=β¦ |
| Decision Log | /app/decisions |
Full on-chain decision history, action type breakdown, confidence stats, tx links |
| Follow Leaderboard | /app/follow |
Strategy ranking with TOP badges, search/filter/sort, pagination, one-click follow with USDT deposit, "How Copy-Trading Works" guide |
| Suite | Count | Coverage |
|---|---|---|
| Hardhat unit tests | 68 passing | DecisionLogger (23) + StrategyManager (25) + FollowVault (20) |
| Playwright E2E tests | 17 passing | Landing (5) + Dashboard (5) + Decisions (3) + Follow (4) |
| Total | 85 tests | Smart contracts + frontend UI |
npm test # 68 hardhat tests in ~1s
cd frontend && npm run test:e2e # 17 Playwright testsSolo developer β responsible for all aspects of the project:
- Solidity smart contract development (DecisionLogger, StrategyManager, FollowVault)
- TypeScript agent backend (Three-Brain architecture, V3PositionManager, OnchainOS integration)
- Next.js 14 frontend (Agent Dashboard, Decision Log, Follow Leaderboard)
- OnchainOS CLI integration (TEE-signed wallet contract-call, swap execute)
- Uniswap AI Skills porting (liquidity-planner, swap-planner)
- Uniswap V3 NonfungiblePositionManager discovery and integration on X Layer
- X Layer mainnet deployment and on-chain activity verification
YieldAgent runs a single AgentCoordinator process that manages multiple strategies. It is not multi-agent; instead, it uses a three-brain ensemble within one agent:
| Component | Role | Type |
|---|---|---|
| AgentCoordinator | Orchestrator β runs monitor loop, coordinates brains, executes trades, handles chat quick-commands, captures PnL snapshots, keeps per-wallet state | Core agent process |
| MarketBrain | Analyzes market conditions (price, volatility, trend) | Analysis module |
| PoolBrain | Analyzes pool state (liquidity, fees, optimal ranges) | Analysis module |
| RiskBrain | Assesses position health and rebalance urgency | Analysis module |
| IntentParser | Converts natural language to structured intent | NLP module |
| V3PositionManager | Manages real V3 LP positions (mint/collect/rebalance) | Execution module |
| OnchainOSAdapter | Interfaces with OnchainOS TEE for signed transactions; TTL-cached reads to cut subprocess load | Signing module |
| PersistenceService | Debounced JSON snapshots for strategies, history, PnL β restart survival with zero native deps | Storage module |
-
Gas-free monitoring loop: The agent evaluates positions every 5 minutes and logs every decision on-chain β including HOLD decisions. This generates thousands of transactions per month. Only X Layer's ultra-low gas cost makes this economically viable, enabling a truly transparent AI audit trail.
-
Native OnchainOS integration: The Agentic Wallet TEE, ERC-4337 account abstraction, and OKX DEX aggregator are all natively available on X Layer. YieldAgent leverages
wallet contract-callfor V3 LP operations andswap executefor token rebalancing β capabilities that don't exist on other chains. -
Official Uniswap V3 deployment: X Layer hosts a fully verified Uniswap V3 deployment (Factory, NPM, Router, Quoter, TickLens). YieldAgent is the first project to route V3 NonfungiblePositionManager calls through OnchainOS TEE on X Layer.
-
On-chain AI audit trail: Every AI decision β including the reasoning and confidence score β is permanently stored on X Layer via
DecisionLogger. The low transaction cost means we never need to drop HOLD logs, preserving the complete audit invariant.
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β X Layer DeFi Ecosystem β
β β
β Users βββ YieldAgent βββ Uniswap V3 LP Positions β
β β β
β ββββ OnchainOS TEE (signed execution) β
β ββββ DecisionLogger (verifiable AI reasoning) β
β ββββ FollowVault (copy-trading for followers) β
β ββββ OKX DEX Aggregator (swap optimization) β
β β
β Value: Autonomous LP management, transparent AI decisions, β
β copy-trading access, on-chain verifiability β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
YieldAgent brings autonomous DeFi intelligence to X Layer β users who lack the expertise or time to manage V3 concentrated liquidity can delegate to an AI agent that operates transparently, with every decision verifiable on-chain. The copy-trading system (FollowVault) further democratizes access, allowing anyone to benefit from the agent's strategies by simply depositing USDT.
yield-agent/
βββ contracts/
β βββ DecisionLogger.sol # On-chain AI decision audit trail
β βββ StrategyManager.sol # Strategy registry + execution records
β βββ FollowVault.sol # ERC20 copy-trading vaults + factory
βββ test/ # 68 hardhat unit tests
βββ agent/
β βββ src/
β βββ config/index.ts # X Layer V3 addresses, chain config
β βββ adapters/
β β βββ OnchainOSAdapter.ts # CLI wrapper: wallet contract-call, swap, defi
β β β # + LRU-bounded TTL read-cache (~90% CLI cut)
β β βββ UniswapSkillsAdapter.ts # liquidity-planner@0.2.0 + swap-planner@0.1.0
β βββ engines/
β β βββ IntentParser.ts # Natural language β structured intent
β β βββ MarketBrain.ts # Market analysis (TWAP, volatility, trend)
β β βββ PoolBrain.ts # Pool analysis (ranges, APR, IL)
β β βββ RiskBrain.ts # Risk assessment (health, rebalance urgency)
β β βββ ExecutionEngine.ts # On-chain audit writes
β βββ services/
β β βββ AgentCoordinator.ts # Core orchestrator + 5-min monitor loop
β β β # + multi-tenant wallet state + proactive chat
β β βββ V3PositionManager.ts # Real V3 LP: mint/collect/rebalance via TEE
β β βββ PersistenceService.ts # Debounced JSON snapshots (strategies/history/pnl)
β βββ index.ts # Express + WebSocket + SSE server (19 endpoints)
βββ frontend/
β βββ src/
β βββ app/
β β βββ page.tsx # Landing page
β β βββ app/
β β βββ page.tsx # Agent Dashboard (SSE chat + V3 positions)
β β βββ pnl/page.tsx # PnL Dashboard (value + fees time-series)
β β βββ pools/page.tsx # Pool catalogue + cross-protocol opportunities
β β βββ decisions/page.tsx # Decision Log
β β βββ follow/page.tsx # Follow Leaderboard + Copy-Trading
β βββ components/
β β βββ AgentChat.tsx # SSE streaming chat β 8 quick-commands, brain progress
β β βββ IntentInput.tsx # Natural-language intent parser UI
β β βββ V3Positions.tsx # Real-time V3 NFT display
β β βββ PnLChart.tsx # Pure-SVG dual-axis chart (no chart library)
β β βββ ThreeBrainPanel.tsx # Brain status (cascading: WSβAPIβRPC)
β β βββ DeployControls.tsx # Strategy deployment UI
β β βββ AlertBanner.tsx # Price alerts
β βββ lib/
β β βββ api.ts # Backend client + types
β β βββ hooks.ts # Shared agent state context (WebSocket)
β β βββ brainRpc.ts # Direct on-chain data fallback
β β βββ onchainDecisions.ts # Read DecisionLogger events
β βββ config/contracts.ts # Contract addresses per chain
β βββ e2e/ # 17 Playwright tests
βββ data/ # JSON snapshots (gitignored β created at runtime)
β βββ strategies.json # Active strategies + deployerWallet ownership
β βββ history.json # Evaluation history per wallet
β βββ pnl-snapshots.json # PnL time-series for every strategy
βββ hardhat.config.ts
βββ SUBMISSION.md # Hackathon submission evidence
βββ README.md
- Node.js 20+
- OKB-funded wallet on X Layer
- OpenAI API key (for IntentParser + reasoning synthesis)
- OnchainOS CLI:
curl -fsSL https://raw.githubusercontent.com/okx/onchainos-skills/main/install.sh | sh - OnchainOS API keys from web3.okx.com/onchainos/dev-portal
git clone https://github.com/dddd86971-cloud/yield-agent.git
cd yield-agent
npm install # Root (contracts + hardhat)
cd agent && npm install && cd .. # Agent backend
cd frontend && npm install && cd .. # Frontendcp .env.example .env
cp frontend/.env.example frontend/.env.local
# Edit .env: PRIVATE_KEY, OPENAI_API_KEY, OKX_ACCESS_KEY, OKX_SECRET_KEY, OKX_PASSPHRASEonchainos wallet login --force
onchainos wallet status # Should show loggedIn: truenpm run compile && npm run deploy:xlayercd agent && npm start # Backend: http://localhost:3001
cd frontend && npm run dev # Frontend: http://localhost:3000curl http://localhost:3001/api/health | jq # OnchainOS + Skills status
curl http://localhost:3001/api/v3/positions | jq # Real V3 NFT positions
npm test # 68 hardhat tests
cd frontend && npm run test:e2e # 17 Playwright testsMIT. Built for OKX Build X AI Hackathon β Season 2, X Layer Arena Track.