Skip to content

[backend] [ai-agent] Build the 24/7 Autonomous Rebalancing Agent Loop #4

@robertocarlous

Description

@robertocarlous

🤖 Summary

Build the core AI agent that runs continuously in the background.

Every hour it:

Scans stablecoin yield sources on Stellar

Compares against current deployed APY

Rebalances if a better yield is found (> 0.5% improvement)

Snapshots all user balances for chart history

Logs all activity

This is the automation engine that makes NeuroWealth autonomous.

🧠 Agent Responsibilities
Hourly Tasks

Scan all available USDC yield protocols

Compare best APY vs current on-chain APY

If improvement > 0.5%, trigger on-chain rebalance

Snapshot all user balances

Event-Based

On deposit → route funds to best protocol immediately

Log every action to AgentLog table

📂 Files to Create
src/agent/
├── loop.ts
├── scanner.ts
├── router.ts
├── snapshotter.ts
└── types.ts
🛠 What You Need to Implement
1️⃣ loop.ts

Use node-cron

Rebalance check every hour at :00

Snapshot job every hour at :30

Run both immediately on startup

Log all activity

Graceful shutdown on SIGTERM

2️⃣ scanner.ts

Fetch real APY rates from:

Blend (testnet)

Stellar DEX pools

Return sorted protocols (highest APY first)

Handle failures gracefully (use Promise.allSettled)

Never crash if one protocol fails

3️⃣ router.ts

Compare:

Current on-chain APY

Best available APY

Only rebalance if:

Different protocol

Improvement > 0.5%

Trigger on-chain rebalance

Log transaction hash

4️⃣ snapshotter.ts

Snapshot all user positions hourly

Save to DB for chart history

Must not block rebalance loop

5️⃣ Integration Tasks

Install node-cron

Wire startAgentLoop() into src/index.ts

Add endpoint:

GET /api/agent/status

Should return:

Last rebalance timestamp

Current protocol

Current APY

Agent health status

🧪 Testing Requirements

Integration tests with mocked protocol rates

Verify threshold logic works correctly

Test:

No rebalance if improvement < 0.5%

Rebalance triggers if > 0.5%

Ensure agent survives thrown errors

Test full rebalance cycle on Stellar testnet

✅ Acceptance Criteria

Agent starts automatically with the server

Cron jobs fire at correct times

Rebalance only triggers when improvement > 0.5%

All actions logged to AgentLog

Agent never crashes on error

Graceful shutdown works

Snapshot data stored hourly

Status endpoint returns correct data

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions