Building an Automated Yearn Vault Trading Agent with x402 Micropayments and SerenAI
I am a big believer in automated investment management. It's just too hard to figure out where to invest my money in W3. Even when using the vaults of the best strategy designers in the world, like Yearn, it's challenging to build something that works when I'm working on other things. AI has now made it possible for agents to do my work. However, there are so many tools and so many functions, so many services, and now so many LLMs. As a 0.5x developer, it's overwhelming. Given that SerenAI is coming online, I wrote an approach to use our SerenDB database so my agents can invest and manage my funds on Yearn.finance's vaults. Let's dive in!
Challenge: Create a Yearnv3 Trading Agent Using Vault Data
I needed to build an AI agent that continuously monitors Yearn v3 vault performance and executes rebalancing trades when opportunities arise. The challenge? Traditional API subscriptions and hosted databases create fixed costs for variable workloads. Instead, I built a pay-per-use architecture using x402 micropayments for both data extraction and storage.
Dual Payment Architecture
My agent makes two types of x402 payments: (1) to Yearn's GraphQL API for vault data queries, and (2) to SerenAI for database storage operations. SerenAI is the AI-agentic development stack. It provides persistent memory for stateful agents via SerenDB (our AI-native data layer). Both services accept USDC micropayments on the Base network, creating a fully crypto-native payment stack.

Payment Flow #1: Querying Yearn's API
Yearn vault data is accessible via an x402-enabled payment gateway at https://www.x402gateway.io/api/proxy/yearnv3. It charges $0.01 per query. My agent uses x402-axios to automatically handle USDC micropayments on Base:
1import { withPaymentInterceptor } from "x402-axios";
2import { createWalletClient, http } from "viem";
3import { base } from "viem/chains";
4
5// Setup agent wallet
6const account = privateKeyToAccount(process.env.AGENT_PRIVATE_KEY);
7const walletClient = createWalletClient({
8 account,
9 transport: http(),
10 chain: base, // Base mainnet for production payments
11});
12
13// Create axios instance with automatic x402 payments
14const yearnAPI = withPaymentInterceptor(
15 axios.create({ baseURL: "<https://www.x402gateway.io/api/proxy>" }),
16 walletClient
17);
18
19// Query vault performance - x402 Gateway handles payment transparently
20const vaultQuery = `
21 query {
22 vault(id: "0x00C8a649C9837523ebb406Ceb17a6378Ab5C74cF") {
23 apy { net }
24 tvl { totalAssets }
25 strategies { address name }
26 }
27 }
28`;
29
30const response = await yearnAPI.post("/yearnv3", { query: vaultQuery });
31// x402 Gateway automatically handles: 402 detection → payment → data retrievalWhen the agent calls yearnAPI.post(), the x402 Gateway detects the 402 Payment Required response, signs a USDC payment transaction on Base, submits it on-chain, then retrieves the vault data. The agent receives data only after the blockchain payment is verified.
Payment Flow #2: Storing Data in SerenAI
After extracting vault data from Yearn, the agent stores it in SerenDB with a second x402 payment. SerenAI charges $0.10 per compute-hour, and each storage operation consumes approximately 500ms of compute time. This translates to:
1Storage cost = $0.10/hour × (500ms ÷ 3,600,000ms/hour)
2 = $0.10 × 0.000139 hours
3 = $0.000014 per write operationThe agent writes vault snapshots to SerenDB using x402-protected endpoints:
1// SerenDB client with x402 payment handling
2const serenAPI = withPaymentInterceptor(
3 axios.create({ baseURL: "<https://api.serendb.com>" }),
4 walletClient
5);
6
7// Store vault snapshot - pays SerenAI $0.000014 per write
8await serenAPI.post("/database/agent_db/write", {
9 table: "yearn_vault_snapshots",
10 data: {
11 vault_address: "0x00C8a649C9837523ebb406Ceb17a6378Ab5C74cF",
12 apy: response.data.vault.apy.net,
13 tvl: response.data.vault.tvl.totalAssets,
14 strategy_address: response.data.vault.strategies[0].address,
15 timestamp: new Date().toISOString(),
16 }
17});Every SerenDB write operation creates two records: (1) the vault snapshot in your custom table, and (2) an x402 payment record in the built-in x402_payments table. This creates an immutable audit trail linking every data point to its payment transaction.
Querying Historical Data
To make trading decisions, the agent queries historical vault performance stored in SerenDB. Read operations require no additional x402 payment:
1// Query historical performance (read operations included in compute cost)
2const connection = await postgres(process.env.SERENAI_CONNECTION);
3const result = await connection.query(`
4 SELECT
5 vault_address,
6 apy,
7 tvl,
8 timestamp
9 FROM yearn_vault_snapshots
10 WHERE vault_address = '0x00C8a649C9837523ebb406Ceb17a6378Ab5C74cF'
11 AND timestamp > NOW() - INTERVAL '24 hours'
12 ORDER BY timestamp DESC
13`);
14When APY increases by more than 2%, the agent executes rebalancing trades directly on-chain via my Ethereum wallet.
Cost Analysis Delivers Savings
Traditional approach (Alchemy Pro + MongoDB Atlas Flex):
- Alchemy Pro: $199/month
- MongoDB Atlas Flex (Base tier, 0-100 ops/sec): $8/month
- Total: $207/month
x402 micropayment approach:
- Yearn API queries: ~3,000/month @ $0.01 = $30.00
- SerenDB writes: ~3,000/month @ $0.000014 = $0.042
- SerenDB reads: ~3,000/month @ $0.000014 = $0.042
- Total: $30.084/month (85.5% savings)
The pay-per-use model eliminates waste: I only pay for data I query and agent state I persist. No idle database costs, no unused API quota. Every expense traces back to a specific operation with on-chain payment verification in SerenAI's x402_payments ledger.
What SerenAI Does That No Other System Can
My Yearn agent demonstrates four unique capabilities that don't exist elsewhere:
1. Complete Agentic Workflow in One Platform (No Tool Sprawl)
- Problem: Building my Yearn AI agents required pulling a data storage and retrieval service for my AI agent that would require me to setup a separate database and separate blockchain indexing service. That takes time and more effort for setup and maintenance.
- SerenAI Solution: ONE platform where my agent can: acquire data (x402 payments), store data (SerenDB), query historical trends, and execute trades—all with one API, one authentication, one audit trail.
- Impact: I built my Yearn agent in less time and with less to setup. No integration glue code. No cross-service authentication. When debugging, everything is in one system with unified logging. I spend time on strategy logic, not infrastructure plumbing.
2. Agentic Audit (Agent Identity + Tamper-Proof Logs)
- Others: Traditional Postgres audit logs can be altered by database admins
- SerenAI: Every query tagged with
agent_idvia session variables, logged via pgAudit, written to Neon's Safekeeper quorum (immutable WAL storage) - Impact: I can prove my agent executed specific trades based on specific vault data—critical for compliance audits. Example:
1-- Show which agent queried which vault at what time
2SELECT agent_id, query_text, timestamp
3FROM agent_audit_logs
4WHERE vault_address = '0xABC...'
5 AND timestamp = '2025-10-28 14:30:00';3. Timeline Branching for Agent Debugging
- Others: No platform offers a point-in-time replay of agent behavior
- SerenAI: Create LSN-based timeline branches to debug agent decisions. When my agent made a bad trade, I branched at the exact LSN (Log Sequence Number) where the decision occurred, replayed queries against that immutable snapshot, and identified the APY calculation bug.
- Impact: Agent debugging without production disruption—no other system has this.
4. Complete AI Agentic Platform (No Tool Sprawl)
- Others: LangChain (logic) + Neon (data) + Vercel (hosting) + Auth0 (auth) = 4-5 separate services
- SerenAI: Data + orchestration + auth + storage + functions in ONE platform
- Impact: My Yearn agent's entire infrastructure is in one system—no integration complexity, no cross-service authentication, no tool sprawl.
Why This Matters For Blockchain & Crypto AI Agent Developers
For crypto developers building autonomous agents, SerenAI solves the infrastructure problem: traditional platforms were built for web apps, making 10 database calls per request. AI agents make 1,000+. SerenAI is purpose-built for agentic workloads with persistent memory, agent-specific auditing, and debugging tools that don't exist anywhere else.
My agent's wallet holds USDC, pays Yearn's API for data, pays SerenAI for persistent agent state, and executes trades on-chain—all without touching traditional payment systems. The entire stack is blockchain-native with transparent audit trails. I can now build multiple agents and offer my customers a service to manage their Yearn3 vaults as well. Blockchain agents are just easier with SerenAI
If you’ve reached this point and are curious about SerenAI, come chat with our AI at https://serendb.com/ and ask to submit a feature request. Feature requests submitted will get complimentary compute hours with SerenA. We want to know what you need to manage all your agentic back-end needs.

About Taariq Lewis
Exploring how to make developers faster and more productive with AI agents