Autonomous On-Chain
Yield Management
WealthVille is an autonomous, non-custodial platform on Solana that discovers, scores, and allocates capital into the best risk-adjusted DeFi yield — and is hardened against the edge cases that sink naive automation. Pick an edition above: general, depositor, technical, or investor.
Architecture Overview
WealthVille is a five-layer system. Data flows left-to-right; capital flows top-to-bottom.
- Backend services run the pipeline, scoring, scheduler, and the vault engine.
- A Next.js frontend serves the public site, pool pages, and the admin dashboard; an Android app wraps the same UI via a Capacitor WebView shell.
- Process management is via PM2 with log rotation and memory-restart caps.
- State lives in PostgreSQL under a
wv.*schema (vaults, pools, signals, logics, positions, automation logs) plus anai.*model registry, with on-chain accounts as the source of truth for positions and permissions. - Telegram carries operational digests and alerts.
A core design tenet: on-chain reality is authoritative for position state. Databases drift; decoded on-chain NFTs and protocol metrics do not. The architecture reads chain state for anything that affects capital.
Data Pipeline
2.1 Discovery
Pools are enumerated across Raydium (AMM & CLMM), Orca (incl. Whirlpools), and Meteora (incl. DLMM), plus staking/lending venues. New pools are folded into wv.pools.
2.2 Collection
Per-pool TVL, APR/fees, volume, and structural metadata are fetched from DEX APIs and on-chain accounts, hardened against real endpoint behavior:
- Using the correct protocol-version endpoint for Orca so TVL is not inflated by orders of magnitude (a v1→v2 collector fix removed a multi-million-dollar phantom-TVL reading that had been fooling the scorer).
- Chunking batch requests to respect per-request result caps (e.g., the Raydium v3 ids endpoint caps results, so batches are chunked accordingly).
2.3 Enrichment
Raw metrics become normalized signals with explicit, consistent units. APR is normalized between fraction and percent representations; fee-APR is stored as a fraction (capped at a sane ceiling). Enrichment derives liquidity-depth and exit-impact estimates and the risk terms the scorer consumes.
2.4 Tiered cadence (T0–T6)
Pools are bucketed by staleness/importance into tiers T0–T6. T0 is every pool any live vault is allowed to touch — refreshed most aggressively and wired into scoring on every loop (ensureVaultPoolsAreT0). The scheduler rotates the enhancement queue by staleness so no pool starves; auto-tiering is an admin-triggered job, off by default.
2.5 Signals data model
The live snapshot lives in signals_latest. TVL/APR live in the payload under an empty model_key; scored/model rows carry a non-empty model_key. Joins must filter model_key — unfiltered joins duplicate pools. Enriched signals are the contract between the pipeline and the scorer.
2.6 Data-quality gates
When inputs are missing or self-inconsistent, the pool is flagged data-incomplete and a liveDataIncomplete guard blocks vault execution on that pool (with care taken not to false-positive on shell NFTs).
Scoring Engine
3.1 Current model: heuristic, transparent
Scoring is presently 100% heuristic — no ML, no LLM in the scoring path. Every term is inspectable. The model computes a risk-adjusted verdict per pool from enriched signals:
- Yield quality — fee APR and sustainability.
- Liquidity / exit impact — discounts pools by the slippage of exiting them, with correct token orientation and across DEX types; non-USDC-quote pools derive
quoteUsdfromtoken_prices. A liquidity-aware scout applies anexit_impactdiscount so capital is not sized into thin pools. - Volatility / stability — coefficient-of-variation, absolute and relative volume behavior.
- Trap detection — explicit terms for exit-depth collapse, abnormal absolute volume, TVL crash, and volatility dry-up, which sharply downgrade pools that are nominally high-APR but structurally dying.
3.2 Verdict reconciliation
Multiple historical signal systems are reconciled into a single wv.pool_verdicts store, which is the one source the Allocation Planner reads — preventing the decision layer from seeing inconsistent opinions of the same pool.
3.3 DEX fairness
The scorer is not structurally biased toward any DEX. Apparent skew in production traced to exit-impact coverage bugs (CLMM orientation, endpoint result caps, enhancement-queue starvation), all fixed. Vault-specific pain on a given DEX has been an execution-layer issue (shell/position-NFT handling), not a scoring bias.
3.4 ML roadmap (shadow-first)
A supervised gradient-boosted model trained on realized signal_outcomes is planned. It will run shadow-first — scored alongside the heuristic with no capital influence — and only promoted if it demonstrably beats the heuristic. The model registries are unified first; the deploy always rebuilds the ai-engine Docker image so scoring changes ship.
Vault Program & On-Chain Model
A vault is a non-custodial Solana program account holding user funds. Key on-chain concepts:
- Smart-vault account — fixed expected layout (≈1268 bytes); a size guard (
safeFetchSmartVault) rejects malformed/legacy-layout reads. This guard fixed a real, uncatchable multi-GB OOM where decoding legacy-layout vaults produced a garbage BorshVeclength and exhausted memory. Legacy vaults remain layout-incompatible and are explicitly excluded. - Allowed-pool PDAs — a vault may only touch pools whitelisted via PDAs derived from
['allowed_pool', vault, pool]. The DB mirror of whitelist status can desync from the on-chain PDA, so reconciliation matters; re-whitelist paths restorestatus='active'rather than no-op. - Feature flags — per-vault switches gate which actions are possible (LP, Jito, perp, Jupiter-enabled). Perp actions are hard-gated on
perpEnabled. - Share accounting — deposits are recorded with correct decimals and pricing; share accounting is verified consistent so each user’s cost basis and balance are accurate.
The Management Tick
Each vault runs a continuous management cycle (“tick”):
- 1Read state — decode on-chain positions (LP NFTs, hedge state), pull
dna_vault_metrics, read native/wrapped SOL balances, and load the latest scored pool data for the vault’s allowed pools (forced to T0). - 2Evaluate logic — run the vault’s programmable logic to produce conditions and targets.
- 3Plan — the Allocation Planner produces one consolidated plan.
- 4Gate — fixed safety gates admit or reject each action.
- 5Execute (if in wet mode and autonomy-enabled) — the execution layer submits transactions.
- 6Reconcile & account — reconcile on-chain results, self-heal cost basis, book realized PnL.
- 7Trace — emit a per-tick logic trace and update automation logs.
Cadence is interval-guarded; the canonical interval is 60 minutes. Position state is read from on-chain NFT decode + dna_vault_metrics, not from the position DB tables, which are currently unreliable.
Allocation Planner
6.1 Motivation
The original engine was a greedy loop: evaluate each pool in isolation, act, repeat — the root cause of most pathologies (over-investment, self-conflicting actions, churn, loop-invest). It was replaced by a unified AllocationPlanner: a holistic decision layer that ranks the entire opportunity set and emits a single consolidated plan across all capital uses.
6.2 Inputs
- 1Programmable logic — fund-distribution weights and method, Jito/perp reserve targets, entry/exit/rotation conditions.
- 2Optional AI — an LLM-assisted parameter-resolution layer (
useOpenai, default off) that refines action parameters strictly within hard bounds; it cannot escape the safety envelope, and AI-recommended actions are tagged and treated as discretionary vs. forced. - 3Allocation ranking — risk-adjusted scores combined with the vault’s aggressiveness profile (over-allocation threshold, APR score weight, rotation behavior).
6.3 Output
A deduplicated, gated plan: each (pool, action) appears once, each action must clear a minNetBenefitUsd floor and the safety gates. Rotation only fires when the APR gap justifies the cost. Over-allocation is measured on the correct basis (TVL-basis, not deployed-basis).
6.4 Rollout
Phase 1 (LP + Jito unified) is shipped and validated in wet mode, gated via a canary list (wv.config allocationPlannerVaults). Phase 2 folds perpetual hedging fully into the planner and retires the legacy _buildActionPlan.
Execution Layer
7.1 LP execution
- DLMM (Meteora) — bin-based; width is sized from
rangePctForPooland the pool’sbin_step. A protocol cap of ~70 bins is respected. - CLMM / Whirlpool — tick-range based; Whirlpool v2 token accounts supported. Invest sizing pins to existing positions when adding, and sizes for the intended range band.
- Single-sided deposits into straddling ranges on dead-token pools are a known impairment vector; a dead-token gate and exit path were added after a real loss event.
7.2 Jito stake/unstake
Stake/unstake is built into the planner (park idle SOL → JitoSOL; unstake-to-fund LP entries). On-chain balance clamps prevent staking more than native SOL, and unwrapWsol no-ops gracefully on a missing WSOL ATA.
7.3 Perp hedging (Jupiter)
Hedging is delegated to a dedicated hedge manager and hard-gated on perpEnabled. The hedge venue is Jupiter perps, not Drift. Production hedge handling includes pre-sync, retry, and force-sync escalation to break sync-revert deadlocks.
7.4 Harvest
Fee harvesting runs on a configurable cadence (collectIntervalHours, collectMinPositionUsd) as a sweep in the planner. Collect rediscovers the live position NFT on-chain when a stored NFT was rebalanced away.
7.5 Reconciliation & self-healing
- Shell-NFT auto-burn: failed/churned transactions leave empty-liquidity position NFTs that make every subsequent invest throw
EMPTY_POSITION_SHELL; the executor auto-burns and retries inline. - Cost-basis self-heal: cost basis is reconciled against on-chain reality on read (
getVaultPnl), eliminating phantom positions.
Safety Architecture
The engine wraps every plan in a fixed gate set that per-vault logic cannotdisable. Each gate exists because of a real production failure.
| Gate | Defends against |
|---|---|
| Capital-protection exits (on realized trailing APR) | Riding a structurally deteriorating pool to the bottom. Not a tick-by-tick stop-loss. |
| No-trade bands + hysteresis (symmetric) | Flip-flop churn from trivial price moves; asymmetric add-bands previously froze re-funding and stranded idle capital. |
| Cooldowns (keyed by correct tx_type) | Re-acting on the same lever every tick. A wrong-key cooldown was a no-op → free churn. |
| Circuit breaker | Repeated genuine failures. No-op ticks are explicitly not counted as failures, so quiet periods don’t trip it. |
| Slippage & size caps (incl. liquidity-aware) | Oversizing into thin pools; excessive slippage. |
| Re-entry quarantine (~6h) | EXIT→reinvest loops. |
| Data-quality / liveDataIncomplete guard | Acting on incomplete or inconsistent pool data. |
| minNetBenefitUsd floor | Churning for sub-economic gains. |
| (pool, action) dedup | Duplicated actions in a single plan. |
| Hedge force-sync escalation | On-chain sync-revert deadlock looping forever. |
| Smart-vault size guard | OOM from decoding malformed/legacy vault layouts. |
| Digest retry de-dup + frequency knobs | Telegram alert storms from re-sending failed rows. |
The design philosophy is fail safe / degrade to no-op. Many of these were discovered in wet mode with real capital — which is precisely why they are now structural.
Accounting & Reconciliation
- Realized PnL — booked from actual fee harvests and position exits; per-position cost basis self-healed against chain state.
- Unrealized PnL — NAV deltas, with care on dust-sized TVL where price noise dominates.
- Consolidated PnL cockpit — spans LP, Jito, and perp across dry and wet modes, enabling shadow comparison of intended vs. executed behavior.
- Fixed accounting bugs (representative): hardcoded decimals (JitoSOL read 1000×), unpriced-dust nulling whole
totalUsd, native-SOL sentinel mint → $0 cost basis. All fixed and historicaldeposit_eventsbackfilled.
Programmable Logic Engine
Vault behavior is defined by a rule-builder DSL stored in wv.vault_logics:
- Fund distribution — weights, method, and Jito/perp reserve targets folded into the unified plan.
- Conditions & actions — Jito staking bands, perp-hedge triggers (gated on
perpEnabled), rotation thresholds,rangePct(wired through to the planner), and collection cadence. - Global safety gates — editable platform-wide gates wrapping every vault regardless of custom logic.
- Per-tick
logic_trace— full observability of each decision. - Toggles —
useOpenai(default off), logging.
The default logic is the well-tested standard policy. Custom logic is always wrapped in fixed gates.
Infrastructure & Operations
- Process model — PM2-managed Node services (ESM, with a
createRequireshim for CJS interop).pm2-logrotateinstalled;max_memory_restartcaps tuned to avoid OOM-restart churn during verdict storms. - Deploy — CI rebuilds the ai-engine Docker image on every deploy so scoring changes ship; prod runs
origin/master. DB access is via Nodepg. - RPC — Helius with a rotating API-key pool; each request picks a random key to spread rate limits. A resilient pinned-key fetch with a
liveDataIncompleteguard prevents acting on partial reads. - Env hygiene —
.envfiles are never modified by tooling and are gitignored. - Admin — admin UI/knobs live on the Next.js
/solana-admin-dashboard/*.
Cross-Chain Data Layer
EVM-chain yield data is ingested into the same pipeline and scorer with chain context threaded through the shared scoring/reconciliation code, surfaced via /opportunities/evm, /yields, and /compare. It lives in isolated wv.evm_* tables and is informational only — there is no EVM execution path.
Security Model
Security is structural — it follows from how the system is built:
- Non-custodial by construction. Funds live in on-chain vault accounts; the protocol operates strictly within on-chain permissions and never takes custody.
- Deterministic on-chain permissioning. Allowed-pool PDAs and feature flags bound the action space to exactly what each vault has authorized.
- Supervised autonomy & safe degradation. Global dry-run plus per-vault autonomy controls; high-impact recovery actions require operator sign-off; when in doubt, the engine no-ops.
- On-chain truth as authority. Capital-affecting decisions read decoded on-chain state, not drifting DB mirrors — closing a whole class of phantom-state bugs.
- Hardened against its own failure modes. The safety architecture above is the structural defense against churn, flip-flop, phantom positions, cost-basis drift, OOM from malformed decoding, and alert storms.
Community & Token
WealthVille operates today as a complete non-custodial product with no token; none exists at the time of writing. A future token, if introduced, could provide governance over protocol parameters and the global safety gates, alignment/incentives for depositors and strategy authors, fee mechanics, and curation of a permissionless strategy marketplace.
Supply, emission, distribution, vesting, utility scope, and legal review would be specified and published before any launch. Forward-looking outlook, not a commitment, offer, or solicitation. See Disclaimers.
Disclaimers
This document is for informational purposes only and is not investment, financial, or legal advice, nor an offer or solicitation to buy or sell any asset or security. It describes a live system under active development; behavior and interfaces change. DeFi carries substantial risk including smart-contract risk, market risk, impermanent loss, and total loss of capital. Any performance figures may include simulated results; past or simulated performance does not guarantee future results. Forward-looking statements are subject to change. Consult your own advisors.




