Jagadish Writes Logo - Light Theme
Published on

How AI Can Model DeFi Contagion Risk

Listen to the full article:

Authors
  • avatar
    Name
    Jagadish V Gaikwad
    Twitter
Source

Decentralized finance, or DeFi, is not a collection of isolated applications. Lending markets, decentralized exchanges, stablecoins, bridges, derivatives protocols, and liquid staking systems often share collateral, liquidity, price feeds, smart contracts, and users. A failure in one part of that system can therefore create losses elsewhere.

AI can model DeFi contagion risk by combining blockchain data, network analysis, machine learning, and scenario simulation. It can identify important connections, detect unusual changes, estimate how shocks may spread, and rank protocols by their potential contribution to a wider cascade. It cannot reliably predict every failure or remove the need for human judgment.

The Financial Stability Board identifies familiar financial vulnerabilities in DeFi, including leverage, liquidity and maturity mismatches, operational fragility, and interconnectedness. DeFi’s programmable and composable structure can cause these vulnerabilities to develop and spread through different channels than in traditional finance.The Financial Stability Board’s DeFi risk assessment

What DeFi contagion risk means

DeFi contagion is the transmission of financial or operational stress from one protocol, asset, blockchain, or market participant to another. The transmission may happen through direct contractual links or through changes in prices, liquidity, incentives, and user behavior.

Consider a simplified chain:

  1. A collateral asset loses value quickly.
  2. Borrowers become undercollateralized.
  3. Lending protocols liquidate positions.
  4. Liquidations increase selling pressure.
  5. Liquidity providers withdraw or suffer losses.
  6. A stablecoin, bridge, or derivative product loses its expected value.
  7. Other protocols that use the same asset or infrastructure experience stress.

This process does not require every affected protocol to hold a direct claim on the original failing asset. Shared dependencies can be enough. A price oracle can connect otherwise separate applications. A bridge can carry representations of an asset to another blockchain. A widely used lending market can become a source of forced selling during a sharp decline.

Research from the Federal Reserve on the Terra collapse found evidence that blockchain bridges increased the potential for spillovers between programmable blockchain environments after a major shock.Federal Reserve research on Terra and DeFi interconnections

Why AI is useful for this problem

Traditional risk models often begin with a defined balance sheet, a known set of counterparties, and relatively stable reporting intervals. DeFi offers much more observable transaction data, but the system is also more dynamic and technically complex.

AI is useful because it can process several forms of information at once:

  • On-chain transactions and token transfers
  • Lending positions and liquidation events
  • Pool reserves and trading volumes
  • Smart-contract call relationships
  • Bridge deposits, withdrawals, and issued representations
  • Oracle updates and price deviations
  • Governance proposals and parameter changes
  • Market prices, volatility, and liquidity
  • Security alerts and protocol status information

The goal is not simply to forecast the price of a token. A contagion model asks a broader question: If this component becomes impaired, which other components are exposed, through which channels, and under what conditions might losses accelerate?

Build a DeFi dependency graph

The first major task is representing DeFi as a graph. In this graph, nodes can represent protocols, pools, assets, blockchains, contracts, or entities. Edges represent relationships between them.

Examples of edges include:

  • A lending protocol accepts a token as collateral.
  • A decentralized exchange supplies the liquidity used for liquidation.
  • A stablecoin is used in several lending and trading markets.
  • A bridge creates a cross-chain version of an asset.
  • A protocol relies on a particular oracle.
  • Several applications depend on the same smart-contract library.
  • A governance-controlled parameter affects multiple markets.

A basic graph can show whether two protocols are connected. A more useful graph records the type, size, direction, and timing of each connection.

For example, an edge could indicate that Protocol A has substantial exposure to the collateral issued by Protocol B. Another edge could indicate a weaker operational dependency, such as both applications relying on the same oracle. These relationships should not be treated as equivalent.

AI can help infer and update this graph from transaction histories. Graph machine learning models can learn patterns in connected data, while graph neural networks can represent how information or risk moves between neighboring nodes. However, a model is only as useful as the definitions behind its nodes and edges. If a bridge, proxy contract, or governance relationship is missing, the resulting risk map may be misleading.

Source

Detect abnormal conditions before a cascade

Contagion often develops through a sequence of smaller changes rather than one obvious event. AI-based anomaly detection can monitor for deviations from a protocol’s normal behavior.

Potential signals include:

  • An unusually rapid fall in pool liquidity
  • A concentration of collateral in a small number of wallets
  • Large borrow positions approaching liquidation thresholds
  • Sudden changes in stablecoin redemption or pool composition
  • A bridge experiencing unusual inflows or outflows
  • Repeated oracle updates that diverge from market prices
  • Abnormally high transaction failures or contract reverts
  • Governance changes that materially alter risk parameters
  • A sharp increase in correlated activity across protocols

Unsupervised learning is particularly relevant when labeled examples of contagion are scarce. Instead of requiring a large set of known failures, an anomaly model can learn typical patterns and flag observations that differ from them.

That approach has an important limitation: unusual does not mean dangerous. A protocol launch, scheduled migration, or legitimate rebalancing can look like an attack or liquidity crisis. Alerts therefore need context, explanations, and human review.

Estimate propagation with stress scenarios

The most practical use of AI may be scenario analysis rather than point prediction. A scenario model applies a defined shock and estimates how the system could respond.

Possible scenarios include:

  • A major collateral asset falls sharply
  • A stablecoin trades below its intended reference value
  • A bridge is paused or compromised
  • A price oracle becomes delayed or inaccurate
  • A lending market experiences rapid withdrawals
  • A smart-contract exploit freezes or drains a pool
  • A large liquidity provider exits several markets
  • Gas costs rise enough to delay liquidations

A propagation model can then simulate second-order effects. If collateral values decline, how many positions become eligible for liquidation? Is the liquidation liquidity deep enough? Would liquidators sell into the same pool used by other protocols? Which assets would experience the next price impact?

A simple model might use historical relationships and fixed rules. A more advanced system could use agent-based simulation, in which simulated borrowers, lenders, traders, liquidators, and protocols react to changing conditions. Reinforcement learning may help explore possible responses, but it should not be treated as proof that real participants will behave in the same way.

A useful output is a range of scenarios rather than one supposedly precise forecast. Estimated net damage should be expressed with assumptions, confidence limits, and the conditions that produced the result.

Combine several modeling approaches

No single AI method captures every contagion channel. A robust monitoring system can combine models with different purposes.

Modeling approachBest use in DeFi contagion analysisMain limitation
Graph analysisMapping dependencies, central nodes, and shared infrastructureA graph may omit hidden, off-chain, or newly created relationships
Anomaly detectionFlagging unusual liquidity, transaction, or oracle behaviorNormal changes can produce false alarms
Time-series modelsEstimating volatility, liquidity changes, and correlated movementsHistorical relationships can break during crises
Supervised learningClassifying known risk patterns when labeled data existsDeFi has relatively few comparable, well-labeled crisis events
Agent-based simulationExploring borrower, trader, liquidator, and protocol responsesResults depend heavily on behavioral assumptions
Stress testingComparing predefined shocks and resilience conditionsIt cannot cover every possible failure path

The strongest design is usually an ensemble. For example, a graph model can identify exposed protocols, a time-series model can estimate market conditions, and a stress simulator can test whether those conditions create cascading liquidations.

Measure more than total value locked

Total value locked, or TVL, is a useful descriptive metric, but it is not a complete measure of contagion risk. Two protocols with identical TVL can have very different risk profiles.

An AI risk model should consider several dimensions:

  • Concentration: How much exposure is linked to one asset, wallet, oracle, bridge, or counterparty?
  • Leverage: How many layers of borrowing or rehypothecation depend on the same collateral?
  • Liquidity depth: How much can be sold before prices move materially?
  • Maturity mismatch: Can users withdraw immediately while assets are difficult to liquidate?
  • Composability: How many downstream applications rely on the same contract or asset?
  • Cross-chain exposure: Does stress need to cross a bridge or affect multiple blockchains?
  • Operational dependency: Which systems rely on the same oracle, keeper, sequencer, or code library?
  • Governance responsiveness: Can risk parameters be changed quickly during stress?
  • Recovery mechanisms: Are pauses, reserves, insurance funds, or upgrade controls available?

The FSB specifically highlights liquidity and maturity mismatches, leverage, operational fragilities, and interconnectedness as important DeFi vulnerabilities.FSB report on financial stability risks in DeFi

A useful model should distinguish between a protocol that is large but isolated and one that is smaller yet positioned at the center of several dependency chains.

Source

Use blockchain data carefully

Public blockchains provide detailed records, but raw transparency does not automatically produce clean data. Analysts must decide how to identify protocols, contracts, wallets, assets, and economic relationships.

Important data challenges include:

  • Proxy contracts can obscure the implementation that actually changes.
  • One protocol may use many addresses and deployment versions.
  • Wallets can represent users, market makers, liquidators, or automated contracts.
  • Token transfers do not always reveal the economic purpose of a transaction.
  • Price data can differ across exchanges and oracle systems.
  • Cross-chain activity may arrive with delays or incomplete attribution.
  • Governance and off-chain operations may not appear fully on-chain.
  • Historical labels for attacks, failures, and recoveries can be inconsistent.

Models trained on unverified labels may learn superficial correlations. A system might associate a particular contract type or chain with danger simply because those examples were easier to label, not because the feature causes contagion.

Data pipelines should therefore preserve provenance. Each risk signal should record its source, timestamp, transformation, and confidence. Analysts should also be able to inspect why a protocol was flagged.

Avoid false precision

AI outputs can look authoritative even when the underlying evidence is weak. A probability score such as “0.82 risk” is not meaningful unless users know what it measures, how the model was trained, and how often comparable events occurred.

Several sources of uncertainty deserve explicit treatment:

  • Regime change: Market behavior during calm periods may not describe crisis behavior.
  • Reflexivity: A public risk warning can cause withdrawals and create the event it predicts.
  • Adversarial behavior: Attackers may deliberately manipulate signals or evade detection.
  • Sparse crisis data: Major contagion events are uncommon and structurally different.
  • Model drift: Protocol code, incentives, liquidity, and user behavior change over time.
  • Hidden exposure: Centralized services, private agreements, and off-chain operations may be absent.
  • Intervention effects: Governance votes, emergency pauses, arbitrage, or regulators can change outcomes.

A model should communicate assumptions and alternative scenarios instead of presenting one number as a fact. Backtesting is useful, but a successful historical fit does not establish that the system will forecast an unprecedented event.

A practical workflow for building a model

A defensible DeFi contagion system can be developed in stages:

  1. Define the unit of analysis. Decide whether nodes represent contracts, protocols, assets, pools, chains, or a combination.
  2. Map exposure types. Separate collateral, liquidity, oracle, bridge, governance, and code dependencies.
  3. Create time-stamped data. Preserve historical states instead of overwriting current values.
  4. Validate entity labels. Review protocol addresses, upgrade paths, wrappers, and known integrations.
  5. Build baseline indicators. Start with concentration, leverage, liquidity depth, and liquidation pressure.
  6. Train models against historical episodes. Use confirmed incidents and stress periods where evidence is available.
  7. Run counterfactual scenarios. Test collateral losses, liquidity withdrawals, oracle failures, and bridge interruptions.
  8. Measure false positives. An alerting system that constantly flags normal activity will be ignored.
  9. Add human review. Analysts should challenge model assumptions and investigate high-impact alerts.
  10. Monitor model drift. Reassess performance after major upgrades, new assets, and structural market changes.

This workflow favors transparent and testable systems over a single opaque prediction engine.

How teams should act on model outputs

Risk scores are most useful when connected to specific controls. Depending on the protocol, an alert could trigger:

  • A review of collateral caps
  • A temporary reduction in borrowing limits
  • Additional liquidity reserves
  • More conservative liquidation parameters
  • A pause on new deposits or integrations
  • Manual verification of oracle data
  • A bridge exposure review
  • A governance proposal with documented assumptions

These actions should be proportionate to the signal and the potential damage. Automatically shutting down a protocol based on one anomaly can create unnecessary losses. Ignoring a cluster of independent warnings can allow a manageable problem to become systemic.

Model governance should cover access controls, audit logs, retraining, incident review, and responsibility for final decisions. AI does not replace protocol governance; it changes the information available to governors and operators.

What current evidence can and cannot show

Research and official assessments support the view that DeFi’s interconnected structure can create meaningful transmission channels. The FSB notes that spillover potential depends partly on the links between DeFi, traditional finance, and the real economy, and that those links could become more significant as adoption grows.FSB assessment of DeFi financial stability risks

Academic work has also examined dynamic downside-risk relationships between digital assets and traditional financial assets. One study reports that market stress and broader uncertainty measures can increase observed tail-risk spillovers, but such results describe statistical relationships rather than a complete causal prediction system.Research on tail-risk networks across digital and traditional assets

Network simulation can illustrate how collateral collapse or liquidity stress might propagate through connected protocols. Yet simulations depend on their chosen nodes, dependencies, shock sizes, and behavioral rules. Their results should therefore be used for structured stress testing, not presented as forecasts of a specific future crisis.

Conclusion

AI can model DeFi contagion risk by turning a changing ecosystem into a monitored network of exposures, dependencies, and possible transmission paths. Graph analysis reveals connections, anomaly detection highlights unusual conditions, time-series models measure changing market relationships, and simulations test how shocks could spread.

The central challenge is not generating a sophisticated score. It is building a model that represents the right dependencies, uses traceable data, exposes its assumptions, and remains useful when conditions change. DeFi risk teams should treat AI as an early-warning and scenario-analysis layer, not as an oracle of certainty.

A practical approach combines transparent network maps, multiple stress scenarios, human review, and conservative responses to concentrated exposure. That combination can help identify contagion pathways earlier while preserving the caution required in a financial system where code, liquidity, incentives, and market behavior interact continuously.

Source

You may also like

Comments: