Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
LABS
Guides

Setting Up Cross-Protocol Contagion Risk Analysis

This guide provides a methodology for mapping and analyzing financial linkages between DeFi protocols to assess contagion risk. It covers analyzing shared collateral assets, inter-protocol lending, and composable leverage to model failure cascades. The analysis helps protocols set exposure limits and design isolation mechanisms.
Chainscore © 2026
introduction
RISK ANALYSIS

Introduction to Cross-Protocol Contagion

A technical guide to understanding and analyzing the systemic risk of failure spreading between interconnected DeFi protocols.

Cross-protocol contagion refers to the systemic risk where a failure or exploit in one decentralized finance (DeFi) protocol triggers a cascade of failures across connected protocols. This risk is inherent in the composable nature of DeFi, where protocols like Aave, Compound, and Uniswap are deeply integrated. A vulnerability in a widely used lending pool or a sharp depeg of a major stablecoin can create a domino effect, leading to liquidations, insolvencies, and significant capital loss across the ecosystem. Analyzing these risks requires mapping the financial dependencies and smart contract integrations that link protocols together.

To set up a basic contagion risk analysis, you first need to identify the network of exposures. This involves tracing asset flows and collateral dependencies. For example, a protocol like MakerDAO may accept wrapped staked ETH (wstETH) from Lido as collateral. If wstETH experiences a price shock or a liquidity crisis, it directly impacts the solvency of MakerDAO vaults. You can query these relationships using on-chain data from The Graph subgraphs or directly via RPC calls to contracts to audit collateral types and their usage across major money markets.

The next step is stress-testing these connections. Create a model that simulates adverse scenarios, such as a 30% drop in ETH price or the failure of a major oracle. Using a scripting language like Python with web3.py, you can programmatically check the health of lending positions. Calculate key metrics like Loan-to-Value (LTV) ratios, liquidation thresholds, and available liquidity on decentralized exchanges for the affected assets. This simulation helps identify which protocols are most vulnerable to a specific shock and estimate the potential capital at risk.

Finally, monitoring real-time data is crucial for proactive risk management. Set up alerts for on-chain events that signal rising contagion risk, such as sudden large withdrawals from a lending pool, a spike in liquidation events, or significant deviations in stablecoin prices. Tools like Chainscore's Risk API or DefiLlama's TVL and lending data can provide aggregated metrics. By combining static dependency mapping with dynamic monitoring, developers and researchers can build a robust framework to understand and mitigate cross-protocol contagion risks in the DeFi landscape.

prerequisites
GETTING STARTED

Prerequisites and Tools

Before analyzing cross-protocol contagion risk, you need the right data sources, analytical frameworks, and development environment. This guide outlines the essential tools and knowledge required to build a robust risk model.

A foundational understanding of DeFi primitives is non-negotiable. You must be comfortable with concepts like liquidity pools, lending/borrowing mechanics, collateralization ratios, and oracle price feeds. Familiarity with major protocols such as Aave, Compound, Uniswap, and MakerDAO is essential, as their interconnectedness often forms the epicenter of systemic risk events. This analysis operates at the protocol and smart contract level, not just token prices.

Your primary tool will be a programming language for data processing and modeling. Python is the industry standard due to its extensive data science libraries (pandas, numpy), web3 interaction packages (web3.py, web3.js), and graphing capabilities (matplotlib, plotly). You will also need access to blockchain data. While running an archive node provides the most control, services like The Graph for indexed data or direct RPC calls to providers like Alchemy or Infura are practical starting points for querying state and historical transactions.

The core of contagion analysis is mapping the financial graph of DeFi. You need to programmatically discover and track connections: which protocols hold collateral in others, where liquidity is pooled, and how debt positions are linked. Tools like DeFi Llama's API can provide a snapshot of Total Value Locked (TVL) and protocol composition, but for dynamic stress-testing, you must build or use a graph model (e.g., using networkx in Python) to simulate cascading liquidations and insolvencies.

For smart contract interaction and deeper state analysis, proficiency with Ethereum tooling is required. This includes using the web3.py library to call contract functions, decode event logs to trace asset flows, and calculate real-time metrics like health factors or pool utilization. Understanding ERC-20 token standards and common contract architectures will help you write accurate data collectors. Always use testnets like Sepolia or Goerli for initial development to avoid cost and risk.

Finally, establish a framework for scenario analysis. Define your risk parameters: what constitutes a "shock" (e.g., a 30% ETH price drop, a specific oracle failure)? Your model should ingest live or historical data, apply the shock, and propagate the effects through your financial graph. The output should quantify the potential domino effect—estimating the cascade of bad debt and insolvent protocols. Start simple, validate against past events like the March 2020 crash or the UST depeg, and iteratively increase complexity.

methodology-overview
METHODOLOGY

Setting Up Cross-Protocol Contagion Risk Analysis

A systematic approach to modeling and simulating the cascading effects of a protocol failure across interconnected DeFi ecosystems.

Cross-protocol contagion risk analysis models how a failure in one DeFi protocol can propagate losses through the financial network. This requires mapping the on-chain exposure graph between protocols, which includes direct integrations like lending collateral, liquidity pool dependencies, and oracle price feeds. The analysis simulates a shock event, such as a smart contract exploit or a sudden depeg, and traces its impact through connected liabilities. Tools like Chainscore's Risk API and data from The Graph are essential for constructing an accurate, real-time map of these interconnections.

The core of the methodology involves defining and applying shock scenarios. Common scenarios include: a sharp decline in a major collateral asset's price (e.g., a 30% drop in stETH), a complete failure of a lending protocol (like a hypothetical MakerDAO vault insolvency), or the depeg of a widely used stablecoin. The simulation calculates the resulting insolvencies and liquidations step-by-step, accounting for over-collateralization ratios, liquidation thresholds, and the market impact of large-scale selling pressure. This process reveals critical failure paths and identifies which protocols act as central risk hubs.

To implement this analysis, you need to gather data on total value locked (TVL), collateral composition, and inter-protocol debt positions. A practical first step is querying a subgraph for a protocol like Aave to get user positions, then cross-referencing collateral addresses with their usage in other systems like Curve pools or Compound. Python libraries such as web3.py and pandas are used to process this data. The simulation logic must iterate, as the liquidation from one protocol can trigger a shortfall in another, creating a feedback loop.

Key metrics to output from the analysis include the Estimated Total Loss across the system, the Contagion Spread (percentage of protocols affected), and the identification of Systemically Important Protocols. Visualizing the results as a directed graph, with node size representing TVL and edge thickness representing exposure, makes the risk pathways clear. This analysis is not a one-time exercise; it must be run periodically or in response to major market events to monitor the evolving risk landscape in DeFi.

key-concepts
FOUNDATIONAL TOOLS

Key Concepts in Contagion Analysis

Understanding systemic risk requires analyzing the interconnectedness of protocols. These core concepts and tools form the basis for effective cross-protocol risk assessment.

01

On-Chain Exposure Mapping

The first step is identifying direct financial links between protocols. This involves tracing collateral dependencies, liquidity pool compositions, and debt positions across blockchains. For example, a stablecoin like DAI is backed by collateral on MakerDAO, which may include staked ETH (stETH) from Lido, creating a chain of exposure. Tools like Nansen and Arkham Intelligence provide dashboards to visualize these connections by tracking large wallet movements and asset holdings.

02

Liquidity & Slippage Analysis

Contagion often spreads via liquidity crunches. Analyze Total Value Locked (TVL) depth across DEX pools and lending markets. A key metric is the slippage impact of a large withdrawal or liquidation. If a protocol like Aave experiences mass exits, the subsequent sell pressure on its collateral assets (e.g., CRV, GMX) can cause cascading liquidations elsewhere. Monitoring real-time liquidity on DeFiLlama and using slippage calculators for large trades is essential for stress-testing scenarios.

03

Oracle Dependency Risks

Price oracles like Chainlink are critical infrastructure. A failure or manipulation can trigger incorrect liquidations across multiple protocols simultaneously. Assess:

  • Oracle latency and update frequency.
  • The concentration of price feeds (e.g., many protocols using the same ETH/USD feed).
  • Fallback mechanisms and their robustness. The May 2022 UST depeg demonstrated how oracle staleness during volatile events can exacerbate a crisis, as protocols were slow to reflect the true, collapsing price.
04

Smart Contract Interdependency

Protocols don't just hold assets; they integrate via smart contract calls. Composability creates risk vectors like:

  • Reentrancy attacks spreading through integrated contracts.
  • Governance token dependencies where one protocol's token secures another.
  • Upgrade risks where a change in one contract (e.g., Compound's Comptroller) affects all integrators. Auditing these call paths requires examining not just the main contracts but also their peripheral integrations and proxy admin privileges.
05

Stablecoin Depeg Scenarios

Stablecoins are the primary contagion vector. Model scenarios for both algorithmic (e.g., former UST) and collateralized (e.g., DAI, USDC) depegs. Key analysis includes:

  • Collateral quality and concentration (e.g., DAI's exposure to USDC).
  • Redemption mechanisms and their capacity during a bank run.
  • Regulatory risk impacting centralized assets like USDC. The March 2023 USDC depeg to $0.87 caused widespread instability in DeFi pools and lending markets that relied on it as primary collateral.
06

Network-Level Stress Analysis

Contagion is constrained by blockchain throughput. During crises, network congestion on Ethereum or high gas fees can prevent users from executing critical risk-mitigating transactions (like repaying loans), leading to unnecessary liquidations. Tools like Etherscan's Gas Tracker and Blocknative's Mempool Explorer help model transaction failure rates under stress. The collapse of Terra caused Ethereum gas prices to spike over 2,000 gwei, paralyzing many DeFi operations.

RISK VECTORS

Protocol Linkage and Exposure Matrix

Comparison of key metrics for analyzing cross-protocol contagion risk across major DeFi lending platforms.

Risk Metric / FeatureAave V3Compound V3MakerDAO

Total Value Locked (TVL)

$12.5B

$6.8B

$8.2B

Avg. Collateral Factor

75%

80%

150% (for ETH-A)

Native Bridge Dependencies

2
1
3

Oracle Centralization Risk

Governance Attack Surface

Large (AAVE token)

Medium (COMP token)

High (MKR token + PSM)

Liquidation Cascade Risk Score

High

Medium

Low

Direct Stablecoin Exposure (USDC/USDT/DAI)

$9.1B

$4.3B

$6.5B (via PSM)

Cross-Chain Debt Portability

data-collection-code
TUTORIAL

Code: Fetching On-Chain Exposure Data

This guide explains how to programmatically retrieve and structure on-chain data to analyze financial exposure and contagion risk across DeFi protocols.

Analyzing cross-protocol contagion risk requires a foundational dataset: the on-chain exposure between entities. This means identifying which smart contracts or wallets have deposited funds into others, creating a network of financial dependencies. For example, to assess the risk to a lending protocol like Aave, you need to know which other protocols (e.g., yield aggregators, other lending markets) are major depositors in its pools. This exposure data is not available in a single API call; it must be constructed by querying and correlating events and state from multiple sources, including RPC nodes, indexing services like The Graph, and block explorers.

The first step is to define the scope of your analysis. Are you tracking exposure for a specific protocol (e.g., Compound v3), a token (e.g., USDC), or a set of known entity addresses? Your target dictates the queries. For a protocol-centric view, you would fetch all Supply and Borrow events, mapping suppliers (often other smart contracts) to the protocol. Using an Ethers.js or Viem script, you can filter these events from the protocol's contracts over a defined block range. The key is to decode the event logs to extract the from (supplier) and amount or onBehalfOf fields, which reveal the exposure link.

For a more comprehensive and efficient analysis, especially across multiple chains, leveraging a structured data platform is essential. Services like Chainscore provide pre-computed exposure graphs via their API. A typical call to GET /v1/exposures/protocol/{protocolId} returns a structured JSON object detailing top depositors, their exposure amounts, and the associated tokens. This abstracts away the complexity of raw event parsing. When using such an API, your code focuses on interpreting the network graph—calculating total value locked (TVL) at risk, identifying concentrated dependencies, and modeling shock propagation.

Once you have the raw exposure pairs (creditor -> debtor, amount), you need to enrich the data. Anonymous wallet addresses are less informative than knowing if they belong to a major protocol like Curve Finance or MakerDAO. This requires cross-referencing addresses against public registries or labels. You can use the Ethereum Name Service (ENS), community-maintained lists like the Defillama Protocol Dictionary, or provider-specific labels. Enrichment transforms a list of hex addresses into a meaningful network map, allowing you to see that 'Protocol A's stability depends heavily on deposits from Protocol B' rather than '0xabc... depends on 0xdef...'.

Finally, with a cleaned and enriched dataset, you can begin the contagion risk analysis. This involves modeling scenarios: what happens if a major debtor (e.g., a large borrowing protocol) defaults? Your code can simulate the cascading effect by recursively tracing exposures. If Protocol B fails and cannot repay Protocol A, does Protocol A then become insolvent, affecting its own creditors? Implementing this requires building a directed graph (using a library like graphology) and applying logic to propagate losses. The output is a risk assessment highlighting systemic vulnerabilities and the most critical nodes in the DeFi ecosystem.

building-graph-model
GUIDE

Setting Up Cross-Protocol Contagion Risk Analysis

This guide explains how to build a graph model to analyze financial contagion risk across interconnected DeFi protocols.

A contagion graph model maps financial dependencies between DeFi protocols to simulate and quantify systemic risk. Nodes represent entities like lending pools, DEXs, or stablecoin issuers, while edges represent exposures such as collateral deposits, inter-protocol loans, or shared liquidity. The core analytical goal is to model how a default or depeg in one node propagates losses through the network, potentially triggering cascading liquidations. This is essential for risk managers and protocol designers to understand their vulnerability to external shocks.

To build the model, you first need to define the node set. Key node types include: major lending markets (Aave, Compound), decentralized exchanges (Uniswap, Curve), liquid staking derivatives (Lido stETH), and cross-chain bridges. For each node, you must collect on-chain state data: total value locked (TVL), debt levels, collateral factors, and liquidity depths. This data is typically sourced via protocol subgraphs on The Graph or direct RPC calls to archive nodes. The granularity of your node definition—whether modeling entire protocols or individual pools—directly impacts the model's resolution and computational cost.

Next, you define the edge set, which captures the financial links. Common edge types are: collateral deposits (e.g., USDC in Aave used as collateral for a loan), protocol-to-protocol lending (e.g., Compound DAI supplied to Yearn vaults), and shared liquidity pools (e.g., two protocols both providing liquidity to the same Curve pool). Edge weights quantify the exposure amount. You can extract this data by parsing inter-protocol transaction logs, monitoring ERC-20 token flows between contract addresses, or using specialized data platforms like Chainscore that aggregate these relationships.

With the graph structure defined, you implement the contagion algorithm. A common approach is a solvency shock propagation model. You start by applying an initial shock, such as a 30% drop in a collateral asset's price. The algorithm then iteratively checks each node: if a node's health factor (e.g., collateral value / debt) falls below a liquidation threshold, its debt is considered bad. The associated losses are propagated to its creditors (connected nodes) based on the edge weights, potentially pushing them into insolvency. This process continues until no new nodes fail. The final output is the set of defaulted nodes and the total value at risk.

Here is a simplified Python pseudocode structure for the contagion simulation:

python
# Pseudo-structure for contagion simulation
graph = load_protocol_graph()
default_set = set([initial_shock_node])
new_defaults = default_set

while new_defaults:
    propagating_losses = {}
    for node in new_defaults:
        for creditor, exposure in graph.get_creditors(node):
            propagating_losses[creditor] = propagating_losses.get(creditor, 0) + exposure * loss_given_default
    new_defaults = set()
    for node, loss in propagating_losses.items():
        if node.solvency_ratio - loss < node.min_solvency:
            if node not in default_set:
                new_defaults.add(node)
                default_set.add(node)

This loop captures the iterative nature of contagion.

For production analysis, integrate real-time data feeds and consider network dynamics. Prices and TVL change constantly, so your model should pull fresh data from oracles like Chainlink. Furthermore, model different shock scenarios: collateral depegs (e.g., USDC losing its peg), concentrated liquidity withdrawal (a DEX pool becoming illiquid), or a smart contract exploit. Tools like Chainscore's Risk API can provide pre-computed network graphs and exposure data, significantly accelerating development. The final model helps answer critical questions: what is the systemic impact of a major stablecoin failure, and which protocols are the most central and risky in the DeFi ecosystem?

simulating-shock-cascades
RISK ANALYSIS

Simulating Shock Propagation and Cascades

This guide explains how to model and simulate financial contagion across interconnected DeFi protocols to assess systemic risk.

Cross-protocol contagion risk analysis models how a shock—like a major price drop, smart contract exploit, or liquidity crisis—propagates through a network of interconnected financial protocols. The core concept is shock propagation, where the failure or stress of one protocol triggers a cascade of liquidations, insolvencies, or withdrawals in others. This is critical for understanding systemic risk in DeFi, where protocols are linked via shared collateral assets, oracle dependencies, and composable lending/borrowing positions. A simulation framework allows you to stress-test this network and identify critical failure points.

Setting up a basic simulation requires defining the network graph and the shock mechanism. First, map the protocol adjacency matrix. This is a data structure (often a Python dictionary or a graph using NetworkX) that defines connections: which protocols hold assets issued by others, which rely on the same price oracles, and which share liquidity pools. For example, a vault on MakerDAO might use wrapped staked ETH (wstETH) as collateral, which is intrinsically linked to Lido's staking protocol and its price feed. A shock to Lido's validator set or its oracle would propagate to MakerDAO.

Next, implement the shock propagation logic. A common model is the default cascade. You start by simulating an initial failure, like a 40% price drop in a major collateral asset (e.g., ETH). The script then iteratively checks all connected protocols for breaches in their health factors or collateral ratios. If breached, those positions are marked for liquidation. The simulation must account for the market impact of these liquidations—large sell-offs can further depress the asset's price, creating a feedback loop. Python libraries like pandas for data manipulation and networkx for graph algorithms are essential here.

For a concrete example, consider this simplified Python snippet that checks for insolvency cascades in a lending protocol network after a price shock:

python
import networkx as nx

def simulate_price_shock(G, shocked_asset, shock_percentage):
    """Simulates a price shock and propagates insolvency."""
    # Apply initial price shock
    for protocol in G.nodes():
        if shocked_asset in G.nodes[protocol]['collateral']:
            G.nodes[protocol]['collateral_value'] *= (1 - shock_percentage)
    
    # Cascade: check for insolvent protocols
    insolvent = True
    while insolvent:
        insolvent = False
        for protocol in G.nodes():
            if G.nodes[protocol]['collateral_value'] < G.nodes[protocol]['debt']:
                # Protocol is insolvent, liquidate collateral
                for neighbor in G.neighbors(protocol):
                    # Shock propagates to connected protocols
                    G.nodes[neighbor]['collateral_value'] *= 0.9  # Example impact
                    insolvent = True
    return G

This model is highly simplified; a robust simulation would incorporate liquidation penalties, oracle update delays, and protocol-specific parameters from their smart contracts.

To move from a toy model to a production-grade analysis, you need real-time or historical data. Sources include:

  • DeFi Llama's API for TVL and protocol composition.
  • The Graph subgraphs for on-chain state (e.g., user positions, health factors).
  • Chainlink Data Feeds or Pyth Network for historical price data. Integrating this data allows you to calibrate your model's initial conditions and validate its outputs against historical events, like the collapse of the Terra/LUNA ecosystem or the cascading liquidations during the November 2022 FTX crisis.

The final step is risk metric calculation. From a completed simulation, you can extract key indicators: the final default fraction (percentage of protocols that failed), the cascade depth (number of propagation rounds), and the system's resilience to shocks of varying magnitudes. Visualizing the cascade with a graph animation (using matplotlib or plotly) can powerfully illustrate how a localized failure spreads. This analysis helps in designing safer protocols, informing risk parameters, and creating early-warning systems for the entire DeFi ecosystem.

ANALYTICAL FRAMEWORK

Key Risk Metrics and Outputs

Core metrics and their outputs for assessing cross-protocol contagion risk, comparing on-chain data sources and analytical methods.

Metric / OutputOn-Chain Data AnalysisAgent-Based SimulationNetwork Theory Model

Liquidity Shock Propagation

Tracks real-time outflows >$10M

Simulates cascading liquidations

Models default probability contagion

Debt Exposure Mapping

Direct inter-protocol liabilities

Indirect exposure via common assets

System-wide interconnectedness score

Price Impact Sensitivity

Calculates slippage for large sells

Stress-tests oracle feed reliance

Derives asset correlation matrices

Protocol Health Score

TVL, utilization, collateral ratios

Resilience to simulated shocks

Centrality & dependency rankings

Contagion Speed (Time to Insolvency)

Measures via mempool & block time

Modeled under different gas price scenarios

Theoretical propagation through network hops

Estimated Loss Given Default

Based on live liquidation penalties

Simulated recovery rates from auctions

Network-adjusted loss amplification factor

Critical Vulnerability Surface

Smart contract upgrade dependencies

Shared oracle or keeper infrastructure

Single points of failure in topology

CROSS-PROTOCOL ANALYSIS

Frequently Asked Questions

Common questions and troubleshooting for developers implementing cross-protocol contagion risk analysis using Chainscore's data and APIs.

Cross-protocol contagion risk refers to the systemic threat where a failure or exploit in one DeFi protocol can cascade and trigger failures in other interconnected protocols. This matters because DeFi's composability creates dense networks of dependencies. For example, a major stablecoin depeg or a lending protocol hack can lead to mass liquidations, trigger bad debt in money markets, and drain liquidity from DEX pools across multiple chains. Analyzing this risk requires mapping the flow of assets, collateral, and governance tokens across protocols like Aave, Compound, Uniswap, and Curve. Chainscore's analysis tracks these interconnections in real-time, providing metrics like Protocol Interconnectedness Score and Contagion Impact Radius to quantify exposure.

conclusion-next-steps
CONTINUING YOUR ANALYSIS

Conclusion and Next Steps

You have now configured a foundational system for monitoring cross-protocol contagion risk. This guide covered the core setup; the next phase involves expanding your analysis.

Your deployed system provides a live view of interconnected risk, but its utility grows with refinement. To enhance your model, consider integrating more granular data sources. This includes real-time oracle price feeds from Chainlink or Pyth for asset valuation, on-chain governance proposal data to anticipate protocol changes, and detailed liquidity pool analytics from platforms like The Graph. Correlating these datasets will improve the accuracy of your risk_score calculations and help identify second-order effects, such as a governance vote that could destabilize a critical lending pool.

For ongoing monitoring, establish automated alerts. Configure your script to trigger notifications via Discord webhooks, Telegram bots, or email when a monitored protocol's health metrics breach predefined thresholds—like a sharp drop in total_collateral or a spike in bad_debt. Implementing a simple dashboard using a framework like Streamlit or Grafana can visualize these metrics, making trends and outliers immediately apparent. Regular backtesting against historical de-fi crises, such as the collapse of a major protocol, will validate and tune your model's sensitivity.

Finally, explore advanced analytical techniques. Move beyond single-protocol snapshots to simulate network-wide stress scenarios using agent-based modeling libraries. Investigate applying machine learning to predict cascading failures by training models on historical blockchain state data. The field of on-chain risk analysis is rapidly evolving; staying engaged with research from organizations like Gauntlet, Chaos Labs, and academic papers will provide cutting-edge methodologies to incorporate into your system.

How to Set Up Cross-Protocol Contagion Risk Analysis | ChainScore Guides | ChainScore Labs