Inspiration
DeFi portfolios fail quietly. Positions drift, health factors slip, yield opportunities evaporate, and by the time you check your dashboard, capital has already bled. The tools exist (PancakeSwap, Venus, yield aggregators), but no single agent watches all of them simultaneously, reasons over the combined state, and decides when to act.
We built Portfolio Guardian to solve this: an autonomous agent that monitors four distinct DeFi operations (rebalancing, grid trading, yield optimization, and health factor monitoring) on BNB Chain, uses Gemini 3.5 Flash to reason over live chain data, and produces actionable verdicts with a full audit trail. The agent runs in the background, handles complex multi-step financial workflows, and operates asynchronously — exactly the kind of agent this hackathon asks for.
What it does
Portfolio Guardian runs a continuous observe-reason-act cycle:
Observe: Four specialized engines read real on-chain state via BSC RPC:
- Rebalancer: Reads PancakeSwap V3 pool prices and liquidity to detect portfolio drift from target allocations
- Grid Trader: Monitors price levels against grid trading parameters to identify grid entry/exit points
- Yield Router: Scans liquidity across multiple PancakeSwap V3 fee tiers (0.01%, 0.05%, 0.25%, 1%) to find the highest-yield venues
- Health Monitor: Queries Venus Protocol's ComptrollerLens to read real account liquidity and health factors
Reason: A Google ADK agent (LlmAgent backed by Gemini 3.5 Flash) receives all four engine outputs as structured tool calls. The model reasons over the combined portfolio state and produces a verdict: action type, urgency, reasoning, and parameters.
Act (when justified): Verdicts land in an immutable audit ledger with timestamps, latencies, and model reasoning. The system defaults to
holdwhen positions are healthy — capital preservation outranks yield chasing.
Key insight: The agent's restraint IS the product. In 3 live E2E cycles against BSC testnet, Gemini chose hold each time, citing real Venus health factor data (HF=99.0). An autonomous financial agent should be boring exactly until the moment it matters.
How we built it
Architecture:
guardian/agent.py— Google ADK LlmAgent definition with tool-calling forobserve_all_lanesandrecord_verdictguardian/cycle.py— One-cycle orchestrator (ADK path with fallback to direct Gemini API)guardian/deploy/main.py— Cloud Run FastAPI entrypoint (POST /cycle, GET /healthz)guardian/deploy/Dockerfile— Python 3.11-slim container for Cloud Run
Tech stack:
- Gemini 3.5 Flash — Reasoning brain (via Gemini API, OpenAI-compatible endpoint)
- Google ADK 2.7.1 — Agent framework with real LlmAgent and InMemoryRunner
- Cloud Run — Serverless deployment target (code complete, HTTP-verified locally)
- PancakeSwap V3 — On-chain DEX for price/liquidity data
- Venus Protocol — On-chain lending for health factor monitoring
- BSC Testnet — Live blockchain (chain 97) for real data reads
Development process: The four observation engines were built first, each verified against live BSC testnet RPC. The ADK agent layer was added on top, with tool-calling proven through repeated E2E cycles. Two production bugs were caught and fixed during deploy preparation:
- An asyncio event loop conflict in the FastAPI entrypoint (fixed with
anyio.to_thread.run_sync) - A truncated-JSON parser failure when Gemini responses hit
max_tokens(fixed with balanced-brace parsing + retry)
Challenges we ran into
On-chain address verification: Initial guesses for PancakeSwap V3 router and quoter addresses had ZERO deployed code. We adopted a "guess-first, verify always" discipline — every address is now verified on-chain with
eth_getCodeevidence before being used.RPC reliability on free endpoints: BSC testnet public RPCs rate-limit aggressively. We handle transient failures gracefully (6/10 wallets returned clean reads in first reconciliation; 4 hit rate limits but audit chain integrity was preserved).
Agent reasoning consistency: The model must reason over 4 distinct data sources and produce structured JSON verdicts. We found Gemini 3.5 Flash handles this reliably when tool declarations are well-typed and the prompt emphasizes restraint ("hold is a valid and often correct action").
Async lifecycle in serverless: Running a full agent cycle (observe -> reason -> record) inside a Cloud Run request handler required careful async orchestration. The ADK's InMemoryRunner blocks, so we offload to a thread pool to avoid starving the uvicorn event loop.
Accomplishments that we're proud of
- 4 engines, live chain data, zero mocks: Every observation reads real PancakeSwap pool state and real Venus Protocol health factors from BSC testnet. No fixtures, no simulation.
- Agent reasoning with receipts: Every verdict includes model-written reasoning text that is distinct across cycles — the brain reasons fresh each time, not cached.
- Full audit trail: Every cycle and every verdict lands in
state/metrics.dbas timestamped events with latency evidence. Judges can audit every decision the system ever made. - Latency improvement: First cycle 60.7s -> warm cycles ~33s, showing effective cache utilization.
- 10/10 test suite green: Covers verdict validation, JSON extraction with edge cases, engine observation shapes, and production bug regression tests.
- Cloud Run ready: Container code complete, HTTP layer verified locally, deploy runbook included.
What we learned
- Autonomous agents should have a bias toward inaction. The most important design decision was making
holdthe default when data is healthy. An agent that acts unnecessarily in financial contexts destroys capital. - On-chain verification is non-negotiable. Smart contract addresses from documentation can be wrong. Always verify with
eth_getCodebefore building on top of them. - Gemini 3.5 Flash is capable of structured financial reasoning. Given well-typed tool declarations and clear constraints, the model produces reliable JSON verdicts with reasoning that cites actual data values.
- Google ADK's tool-calling model works for real workflows. The LlmAgent + InMemoryRunner pattern scales from local testing to Cloud Run deployment with minimal changes.
What's next
- Execution layer: Engines currently observe only. The next step is adding scoped transaction execution behind the Altana session gate (requires BSC testnet faucet funding for gas).
- Mainnet readiness: All code paths work on both testnet and mainnet RPC. Switching is a config change.
- Portfolio onboarding: Allow users to register their BNB Chain wallet addresses and Venus positions for personalized monitoring.
- Alert system: Push notifications (Telegram, email) when health factors drop below thresholds.
- Multi-chain expansion: The engine architecture generalizes to Ethereum, Arbitrum, and other EVM chains.
Built with
- Gemini 3.5 Flash — Agent reasoning brain
- Google ADK 2.7.1 — Agent framework (LlmAgent, tool-calling)
- Cloud Run — Serverless deployment
- PancakeSwap V3 — On-chain DEX data
- Venus Protocol — On-chain lending data
- Python 3.11 — Runtime
- FastAPI — HTTP layer
Try it
# Clone the repo
git clone https://github.com/zyphonOS/portfolio-guardian
cd portfolio-guardian
# Install dependencies
pip install -r requirements.txt google-adk==2.7.1
# Set your Gemini API key
export GOOGLE_API_KEY=your_key_here
# Run a live cycle against BSC testnet
python -m guardian.cycle testnet
# Run the test suite
python -m pytest guardian/tests -q
Proof trail
Every claim above is machine-verifiable. See PROOF.md for:
- Live cycle history from
state/metrics.db(3 cycles, all ADK path, distinct model reasoning) - Test suite results (10/10 passing)
- Reproduction commands
- Honest boundaries and constraints
Log in or sign up for Devpost to join the conversation.