AI-Powered DeFi Portfolio Optimization in Mobile Applications
A DeFi portfolio comprises positions across multiple protocols: liquidity in Uniswap v3, staking in Lido, lending in Aave, yield farming in Convex. Each position offers distinct returns, risks, and conditions. Optimization finds the asset allocation that maximizes returns for a given risk level.
Architecture: Reading from Blockchain
Web3 Providers and Data Aggregators
Direct RPC calls to protocol contracts are slow and require knowledge of each ABI. Aggregators simplify the process:
- DefiLlama API — TVL, APY for hundreds of protocols, free
- The Graph — GraphQL queries to protocol subgraphs (Uniswap, Aave, Compound)
- Moralis / Alchemy — wallet balances, transaction history, decoded events
import requests
class DeFiDataProvider:
def get_protocol_yields(self, protocols: list[str]) -> dict:
# DefiLlama yields API
response = requests.get("https://yields.llama.fi/pools")
all_pools = response.json()["data"]
filtered = [
pool for pool in all_pools
if pool["project"] in protocols
and pool["tvlUsd"] > 1_000_000 # minimum TVL $1M
and pool["apy"] is not None
and pool["apy"] > 0
]
return {pool["pool"]: pool for pool in filtered}
def get_wallet_positions(self, wallet_address: str, chain: str) -> list[dict]:
# Alchemy DeFi positions via Enhanced APIs
response = requests.post(
f"https://{chain}.g.alchemy.com/v2/{ALCHEMY_KEY}",
json={
"id": 1,
"jsonrpc": "2.0",
"method": "alchemy_getTokenBalances",
"params": [wallet_address]
}
)
return response.json()["result"]["tokenBalances"]
The Graph for Uniswap v3 position history:
query GetPositions($owner: String!) {
positions(where: { owner: $owner, liquidity_gt: "0" }) {
id
pool { token0 { symbol } token1 { symbol } feeTier }
liquidity
depositedToken0
depositedToken1
collectedFeesToken0
collectedFeesToken1
}
}
DeFi Risks: What Models Must Account For
Optimizing purely on APY is a mistake. 100% APY on an unknown protocol with $50k TVL and unaudited contract is nearly guaranteed to end in a rug pull or exploit.
Key Risks:
Smart contract risk — code vulnerabilities. Indicators: audit presence (Certik, Trail of Bits, OpenZeppelin), audit recency, severity of findings.
Impermanent loss (IL) in AMM positions — value loss compared to simple holding when token price ratios change. For Uniswap v3 with concentrated liquidity, IL can be severe when price exits the set range.
def calculate_impermanent_loss(price_ratio_change: float) -> float:
"""
price_ratio_change: current price ratio / initial
Returns IL as a fraction of holdings
"""
k = price_ratio_change
il = 2 * (k**0.5) / (1 + k) - 1
return il # negative number = loss
At price_ratio_change = 2 (one token price doubles), IL ≈ -5.7%. At price_ratio_change = 4, IL ≈ -20%.
Liquidity risk — inability to exit positions without significant slippage. Positions > 1% of protocol TVL face this problem.
Oracle manipulation risk — protocols using stale or manipulable price oracles are vulnerable to flash loan attacks.
Portfolio Optimization Model
Adapt classical Modern Portfolio Theory (MPT) for DeFi. Goal: find weights w for each position maximizing Sharpe Ratio within constraints:
import numpy as np
from scipy.optimize import minimize
class DeFiPortfolioOptimizer:
def optimize(
self,
expected_returns: np.ndarray, # APY for each protocol
risk_scores: np.ndarray, # risk 0-1 for each
correlation_matrix: np.ndarray,
max_protocol_weight: float = 0.40,
max_risk_score: float = 0.60
) -> np.ndarray:
n = len(expected_returns)
def neg_sharpe(weights):
portfolio_return = np.dot(weights, expected_returns)
portfolio_risk = np.dot(weights, risk_scores)
portfolio_vol = np.sqrt(weights @ correlation_matrix @ weights)
sharpe = (portfolio_return - 0.03) / (portfolio_vol + 1e-6)
# Penalty for high risk
risk_penalty = max(0, portfolio_risk - max_risk_score) * 10
return -sharpe + risk_penalty
constraints = [
{"type": "eq", "fun": lambda w: np.sum(w) - 1}, # weights sum to 1
]
bounds = [(0.0, max_protocol_weight)] * n
result = minimize(
neg_sharpe,
x0=np.ones(n) / n,
method="SLSQP",
bounds=bounds,
constraints=constraints
)
return result.x
risk_scores aggregate: TVL (higher = lower risk), audit score, protocol age, exploit history. Correlation between DeFi protocols is high during market-wide events (all decline together) but lower in normal conditions.
Automatic Rebalancing
When conditions shift (APY drops 20%+, protocol loses 30% TVL, new audit finds critical issues), the system suggests rebalancing.
Rebalancing in DeFi incurs gas and slippage. The optimizer must verify: benefit from reallocation > gas cost + slippage.
struct RebalanceProposal {
let currentAllocation: [ProtocolPosition]
let proposedAllocation: [ProtocolPosition]
let estimatedGasCost: Decimal // in USD
let expectedYieldImprovement: Double // APY delta
let breakEvenDays: Int // when gas pays for itself
let warnings: [RiskWarning]
}
breakEvenDays = gasCost / (annualYieldImprovement / 365). If breakEven > 30 days, rebalancing is not worthwhile.
Web3 Integration in Mobile
For read-only position viewing, no Web3 provider is needed. For executing rebalancing transactions, use WalletConnect v2:
import WalletConnectSign
class WalletConnectManager {
func connectWallet() async throws {
let uri = try await Sign.instance.connect(
requiredNamespaces: [
"eip155": ProposalNamespace(
chains: [Blockchain("eip155:1")!],
methods: ["eth_sendTransaction", "eth_sign"],
events: ["accountsChanged", "chainChanged"]
)
]
)
// Show QR code or deep link for MetaMask/Rainbow/etc
presentWalletConnectURI(uri.absoluteString)
}
}
WalletConnect v2 is supported by all major wallets (MetaMask, Rainbow, Coinbase Wallet). Private keys never leave the user's wallet.
Real-Time Position Monitoring
Push notifications for important events:
- APY drops 15%+ → suggest rebalancing
- Protocol TVL falls 30% in 24h → risk alert
- Uniswap v3 position out-of-range → IL accelerating
Monitor via WebSocket to Alchemy (eth_subscribe for relevant contract events) or server-side scheduled jobs with polling.
Process Overview
Define supported protocols and chains. Build data pipeline (DefiLlama, The Graph, on-chain). Develop protocol risk scoring model. Build portfolio optimizer with constraints. Integrate WalletConnect for mobile. UI: display current positions, rebalancing suggestions, risk monitoring.
Timeline Estimates
Read-only dashboard with current positions and basic scoring: 2–3 weeks. Complete system with optimizer, automatic alerts, and WalletConnect integration: 4–8 weeks.







