import json
import time
import pandas as pd
import numpy as np
from web3 import Web3
from dataclasses import dataclass
from typing import List, Dict, Optional
# --- Configuration & Mocking ---
# In production, load these from .env
RPC_URL = "https://eth-mainnet.g.alchemy.com/v2/YOUR_KEY"
TREASURY_ADDRESS = "0x..." # Target DAO Treasury
# Mocking External Risk Databases
PROTOCOL_RISK_DB = {
"Aave": {"risk_score": 8.5, "audit_status": "Verified", "exploit_history": False},
"Lido": {"risk_score": 7.0, "audit_status": "Verified", "exploit_history": False},
"Uniswap": {"risk_score": 9.0, "audit_status": "Verified", "exploit_history": False},
"ShitCoinFarm": {"risk_score": 1.5, "audit_status": "Unauidited", "exploit_history": True}
}
# --- Data Models ---
@dataclass
class AssetPosition:
symbol: str
amount: float
usd_value: float
protocol_origin: str # Where is the asset held? (e.g., "Aave", "Wallet")
underlying_asset: str # For derivatives (e.g., stETH -> ETH)
price: float
@dataclass
class RiskReport:
total_exposure_usd: float
protocol_risk_score: float # 0-100 (Higher is better/safer)
diversification_hhi: float # 0-10000 (Lower is better)
exposure_breakdown: pd.DataFrame
counterparty_risk: Dict[str, str]
# --- Core Modules ---
class OnChainAnalyzer:
def __init__(self, rpc_url):
self.w3 = Web3(Web3.HTTPProvider(rpc_url))
if not self.w3.is_connected():
raise ConnectionError("Failed to connect to RPC")
def get_erc20_balance(self, token_address, wallet_address) -> float:
"""
Fetches balance and metadata for an ERC20 token.
"""
# Minimal ABI for ERC20
erc20_abi = '[{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"balance","type":"uint256"}],"type":"function"}, {"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint8"}],"type":"function"}]'
contract = self.w3.eth.contract(address=Web3.to_checksum_address(token_address), abi=json.loads(erc20_abi))
decimals = contract.functions.decimals().call()
balance_raw = contract.functions.balanceOf(Web3.to_checksum_address(wallet_address)).call()
return balance_raw / (10 ** decimals)
class RiskEngine:
"""
Aggregates Smart Contract Risk and Protocol Health.
"""
def __init__(self, risk_database):
self.db = risk_database
def assess_protocol_risk(self, protocol_name: str) -> dict:
"""
Returns risk metrics for a specific protocol.
Input: Protocol Name (e.g., 'Aave')
Output: {score, audit_flag, liquidity_risk}
"""
# In production: Query DeFiLlama SDK or Gauntlet API here
data = self.db.get(protocol_name, {
"risk_score": 0.0, "audit_status": "Unknown", "exploit_history": True
})
# Penalize for unaudited contracts
audit_modifier = 1.0 if data['audit_status'] == "Verified" else 0.5
# Penalize for history of exploits
exploit_modifier = 1.0 if not data['exploit_history'] else 0.2
final_score = data['risk_score'] * audit_modifier * exploit_modifier
return {
"raw_score": data['risk_score'],
"adjusted_score": final_score,
"status": data['audit_status']
}
class ExposureMonitor:
def __init__(self, on_chain_analyzer: OnChainAnalyzer, risk_engine: RiskEngine):
self.analyzer = on_chain_analyzer
self.risk = risk_engine
def _resolve_underlying(self, symbol: str, protocol: str) -> str:
"""
Logic to unwrap derivatives to base asset for diversification calc.
e.g., stETH -> ETH, USDC-ETH LP -> 50% USDC / 50% ETH
"""
# Simplified logic for this demonstration
if "stETH" in symbol: return "ETH"
if "rETH" in symbol: return "ETH"
return symbol
def generate_report(self, holdings: List[Dict]) -> RiskReport:
"""
Main aggregation logic.
"""
processed_positions = []
counterparty_scores = {}
total_treasury_value = 0
# 1. Enrich Data
for h in holdings:
# Simulate On-Chain Fetch
# amount = self.analyzer.get_erc20_balance(h['token_addr'], TREASURY_ADDRESS)
amount = h['amount'] # Using mock data
pos = AssetPosition(
symbol=h['symbol'],
amount=amount,
usd_value=amount * h['price'],
protocol_origin=h['protocol'],
underlying_asset=self._resolve_underlying(h['symbol'], h['protocol']),
price=h['price']
)
processed_positions.append(pos)
total_treasury_value += pos.usd_value
# 2. Calculate Protocol Risk
if h['protocol'] not in counterparty_scores:
risk_data = self.risk.assess_protocol_risk(h['protocol'])
counterparty_scores[h['protocol']] = risk_data
# 3. Calculate Diversification (HHI)
# We calculate HHI based on underlying assets to avoid masking risk
# (e.g., holding stETH and ETH is effectively 100% ETH exposure)
df = pd.DataFrame([vars(p) for p in processed_positions])
if total_treasury_value == 0: return None
# Calculate weights of underlying assets
df['weight'] = (df['usd_value'] / total_treasury_value) * 100
underlying_weights = df.groupby('underlying_asset')['weight'].sum()
# Herfindahl-Hirschman Index (HHI)
# Scale 0 to 10,000. < 1,500 is diversified. > 2,500 is highly concentrated.
hhi = (underlying_weights ** 2).sum()
# 4. Calculate Weighted Average Protocol Risk
# We weight the risk by how much money is in that protocol
total_risk_weight = 0
weighted_risk_sum = 0
for _, row in df.iterrows():
protocol = row['protocol_origin']
weight = row['usd_value']
score = counterparty_scores[protocol]['adjusted_score']
weighted_risk_sum += score * weight
total_risk_weight += weight
avg_protocol_risk = (weighted_risk_sum / total_risk_weight) * 10 # Scale to 100
return RiskReport(
total_exposure_usd=total_treasury_value,
protocol_risk_score=round(avg_protocol_risk, 2),
diversification_hhi=round(hhi, 2),
exposure_breakdown=df,
counterparty_risk=counterparty_scores
)
# --- Execution Simulation ---
def run_monitor():
# Initialize Systems
# chain = OnChainAnalyzer(RPC_URL)
risk_sys = RiskEngine(PROTOCOL_RISK_DB)
monitor = ExposureMonitor(None, risk_sys) # Passing None for analyzer to use mock data
# Mock Treasury Holdings (Simulating a DAO Treasury)
# Suppose we have $1M in stablecoins, $500k in Staked ETH, and $100k in a risky farm
mock_holdings = [
{'symbol': 'USDC', 'protocol': 'Wallet', 'amount': 1000000, 'price': 1.0},
{'symbol': 'stETH', 'protocol': 'Lido', 'amount': 300, 'price': 1650}, # ~$495k
{'symbol': 'DAI', 'protocol': 'Aave', 'amount': 500000, 'price': 1.0},
{'symbol': 'YIELD', 'protocol': 'ShitCoinFarm', 'amount': 100000, 'price': 0.001} # Risky exposure
]
print("--- Generating DeFi Treasury Risk Report ---\n")
report = monitor.generate_report(mock_holdings)
print(f"Total Treasury Value: ${report.total_exposure_usd:,.2f}")
print(f"Protocol Safety Score: {report.protocol_risk_score}/100 (Higher is Safer)")
print(f"Diversification HHI: {report.diversification_hhi} (<1500 is Healthy)\n")
print("--- Counterparty Analysis ---")
for proto, data in report.counterparty_risk.items():
print(f"Protocol: {proto:<15} | Risk Score: {data['adjusted_score']:<5} | Status: {data['status']}")
print("\n--- Asset Concentration ---")
print(report.exposure_breakdown[['symbol', 'underlying_asset', 'usd_value', 'weight']])
run_monitor()