Back to Blog
Moving Averages in DeFi: Security Vulnerabilities and Attack Prevention
DeFiDeFi SecurityWeb3 Security

Moving Averages in DeFi: Security Vulnerabilities and Attack Prevention

February 10, 2026
14 min
3 views

1. Introduction: What are moving averages?

Ever wondered how traders seem to have a crystal ball when it comes to price movements? They don't — but they do have some powerful tools up their sleeves. One of the most popular is the moving average.
Imagine you're trying to figure out if the temperature is getting warmer over time. Instead of looking at each day's temperature, which can swing wildly, you might look at the average temperature over the past week. As each day passes, you drop the oldest day and add the newest — that's your "moving" average.
In finance, we do the same with prices. A moving average smooths out price data over a specified period, helping to filter out noise and reveal the underlying trend.
The two most common types are:
  1. Simple Moving Average (SMA): The straightforward average over a set period. Add up the prices, divide by the number of periods.
  2. Exponential Moving Average (EMA): Gives more weight to recent prices, making it more responsive to new information.
Moving averages aren't just for traditional finance anymore. In DeFi, they're being used in exciting — and sometimes risky — new ways. From helping set prices in decentralized exchanges to managing risk in lending protocols, moving averages are becoming a crucial part of the DeFi toolkit.
But here's the thing: implementing them in smart contracts isn't as straightforward as it might seem. It comes with its own set of challenges, pitfalls, and potential exploits.

2. Moving averages in traditional finance vs. DeFi

In traditional finance, moving averages are primarily used for technical analysis. Traders use them to identify trends, support and resistance levels, and potential buy or sell signals. When a short-term moving average crosses above a long-term moving average, it might signal a bullish trend.
In DeFi, moving averages take on a whole new dimension. They're not just tools for analysis — they become active components of smart contracts and protocols. Here are the key differences:
  1. Real-time execution: In DeFi, moving averages can trigger automatic actions. A lending protocol might adjust interest rates based on a moving average of utilization rates, with no human intervention required.
  2. On-chain vs. off-chain: Traditional finance calculates moving averages off-chain. In DeFi, these calculations often need to happen on-chain, which presents unique challenges.
  3. Data availability: Traditional markets have closing prices. In DeFi, the market never sleeps. This continuous data flow makes moving average calculations more complex.
  4. Manipulation risks: DeFi's composability and sometimes lower liquidity can make moving averages more vulnerable to intentional skewing.

3. Use cases for moving averages in smart contracts

Price oracles

Many DeFi protocols use moving averages to smooth out price fluctuations and provide more stable price data.
Chainlink's Price Feeds often use a Time-Weighted Average Price (TWAP) model, which is a type of moving average. This helps mitigate the impact of short-term price spikes or dips, providing a more reliable price feed for DeFi protocols.
The tradeoff? This can make the price feed less responsive to real market changes. That's why many protocols use multiple timeframes or combine moving averages with other metrics — it's all about finding the right balance between stability and responsiveness.

Automated market makers (AMMs)

AMMs like Uniswap and Curve use liquidity pools to facilitate trading. Some newer AMM designs use moving averages to dynamically adjust their bonding curves or fee structures.
For instance, imagine an AMM that uses a moving average of trading volume to adjust its fees. During periods of high volatility (indicated by higher than average volume), it could increase fees to protect liquidity providers from impermanent loss.

Lending protocols

In DeFi lending, moving averages play a crucial role in risk management:
  • Interest rate calculation: Protocols like Aave use moving averages of utilization rates to dynamically adjust interest rates. As the average utilization increases, interest rates go up to incentivize more deposits and fewer borrows.
  • Collateralization ratios: Some protocols use moving averages of asset prices to determine safe collateralization ratios. This helps smooth out short-term price fluctuations that could otherwise trigger unnecessary liquidations.

Algorithmic stablecoins

Algorithmic stablecoins are the high-wire acts of the crypto world, and moving averages are part of their balancing mechanism. Ampleforth (AMPL), for example, uses a moving average of its exchange rate to determine whether to expand or contract the money supply.
While moving averages can help stabilize these systems, they also introduce lag which can lead to interesting — and sometimes volatile — situations.

Yield farming and liquidity mining

Some yield farming protocols use moving averages to determine reward rates. A protocol might adjust its reward emissions based on a moving average of Total Value Locked (TVL).
This can help create more sustainable yield farming ecosystems by automatically adjusting rewards based on long-term trends rather than short-term fluctuations.

Derivatives and synthetic assets

In on-chain derivatives, moving averages are used for everything from determining funding rates in perpetual futures to calculating the price of synthetic assets.
Synthetix uses an Exponential Moving Average (EMA) for its exchange rates. This helps protect against price manipulation while still allowing synthetic assets to track their underlying assets accurately.

Governance mechanisms

Even in DAO governance, moving averages have found a home. Some protocols use moving averages of token holder participation to dynamically adjust quorum requirements. If participation has been low (based on the moving average), the quorum requirement might be lowered to ensure proposals can still pass.
All these uses of moving averages in smart contracts introduce potential vulnerabilities. An attacker who understands how a protocol uses moving averages might be able to manipulate the system to their advantage.

4. Pitfalls and vulnerabilities

Oracle manipulation

Oracle manipulation is one of the most critical risks in DeFi, and moving averages can sometimes make it easier for attackers:
  • An attacker notices a protocol using a moving average for price data.
  • They calculate how much they need to move the price to significantly shift the average.
  • Through a series of trades (often facilitated by flash loans), they push the price in their desired direction.
  • The moving average shifts, and the attacker exploits this shift for profit.
With flash loans, attackers can borrow massive amounts of capital, execute their attack, and repay the loan — all in a single transaction.

Flash loan attacks

Flash loans are the nitro boost in the engine of many DeFi exploits. Here's how they can target moving averages:
  • An attacker takes out a flash loan for a large amount of an asset.
  • They use this to make a series of trades that manipulate the price on a DEX.
  • If the protocol calculates its moving average using recent price data from that DEX, the average shifts.
  • The attacker then exploits this shift — perhaps by taking out an under-collateralized loan or manipulating a synthetic asset's price.
  • They profit, repay the flash loan, and walk away with the difference.

Staleness and latency issues

Moving averages are only as good as the data they're based on. If that data is stale, it can lead to dangerous outcomes:
  • A lending protocol uses a 24-hour moving average to determine collateralization ratios.
  • The price of the collateral asset suddenly drops, but the moving average hasn't caught up yet.
  • The protocol continues to treat the collateral as more valuable than it actually is.
  • Users can take out loans that are effectively under-collateralized, putting the entire protocol at risk.

Precision loss and rounding errors

Solidity doesn't handle decimal numbers natively. This can lead to precision loss when calculating moving averages:
  • You're calculating a simple moving average of 10 periods.
  • You add up the 10 values and divide by 10.
  • If the sum isn't evenly divisible by 10, you lose some precision.
  • Over time, these small rounding errors can compound, leading to increasingly inaccurate moving averages.
This is especially problematic for assets with low decimal places, like USDC (6 decimals) compared to ETH (18 decimals).

Time-Weighted Average Price (TWAP) manipulation

TWAP is a popular form of moving average in DeFi, but it's not immune to manipulation:
  • An attacker executes a large trade just before and after a TWAP measuring period.
  • This "sandwich" attack can skew the TWAP without requiring the attacker to maintain a position during the entire period.
  • If a protocol uses this TWAP for critical operations (like loan collateralization or synthetic asset pricing), it could lead to exploitable situations.

Governance parameter attacks

Using moving averages in governance opens up a new attack surface:
  • An attacker could manipulate token holder participation over time to affect the moving average.
  • This could lower quorum requirements, making it easier to pass malicious proposals.
  • Alternatively, they might inflate participation metrics to make it harder for legitimate proposals to pass.

Liquidity shifting attacks

Some AMMs use moving averages to adjust their parameters. This can be exploited:
  • An attacker observes the period over which the moving average is calculated.
  • They temporarily shift a large amount of liquidity into the pool just long enough to affect the average.
  • Once the parameters adjust based on this manipulated average, they remove their liquidity.
  • This could result in mispriced trades or suboptimal fee structures, which the attacker can then exploit.

5. Best practices

Use multiple data sources

Don't trust a single oracle with your protocol's security:
  • Implement a median price feed from multiple reliable oracles.
  • Consider using a combination of centralized (like Chainlink) and decentralized (like Uniswap TWAP) oracles.
  • Weight the sources based on their historical accuracy and manipulation resistance.

Implement circuit breakers

Circuit breakers are the airbags of your DeFi protocol:
  • Set up thresholds for acceptable price movements within a given time frame.
  • If these thresholds are breached, pause the affected functions of your protocol.
  • Make sure your circuit breakers can't be easily gamed by attackers.

Use median prices instead of averages

Medians are less easily swayed by extreme values:
  • Instead of a simple moving average, consider a moving median.
  • This can help mitigate the impact of short-term price manipulations.

Regular audits and stress testing

Your smart contract is like a ship, and audits are your maintenance checks:
  • Conduct regular third-party audits of your smart contracts.
  • Perform extensive stress testing, simulating various attack scenarios.
  • Consider implementing a bug bounty program to incentivize white-hat hackers.

Implement time delays

Slowing things down can be a defense against attacks:
  • For critical operations that rely on moving averages, consider implementing a time delay.
  • This gives time for any manipulated prices to correct and for circuit breakers to kick in if needed.

Use Exponential Moving Averages (EMAs)

EMAs can be more responsive to recent price changes while still smoothing out noise:
  • Consider using EMAs instead of simple moving averages for more timely data.
  • Be aware that this increased responsiveness can be a double-edged sword and adjust your other safeguards accordingly.

Conclusion

Moving averages are far more than just lines on a chart. In DeFi, they're the invisible gears turning behind lending protocols, AMMs, oracles, and even governance systems.
Here are the key takeaways:
  1. Moving averages are foundational infrastructure in DeFi — from price oracles to interest rate models and algorithmic stablecoins.
  2. Vulnerabilities are real and can have multi-million dollar consequences. Oracle manipulation, flash loan attacks, precision loss, and TWAP manipulation are all active threats.
  3. Best practices are essential safeguards. Multiple data sources, circuit breakers, and regular audits aren't just buzzwords — they're the life jackets keeping DeFi protocols afloat.
  4. The design space is still evolving. From AI integration to cross-chain implementations, the future of moving averages in DeFi is as exciting as it is unpredictable.

FAQ: Moving averages in DeFi

1. What is the difference between SMA and EMA in DeFi protocols?
A Simple Moving Average (SMA) gives equal weight to all data points in the period, while an Exponential Moving Average (EMA) gives more weight to recent data. In DeFi, EMAs are often preferred because they react faster to price changes, which is critical in 24/7 markets where delayed responses can lead to exploitable situations. However, EMAs can also be more vulnerable to short-term manipulation.
2. Why are moving averages vulnerable to flash loan attacks?
Flash loans allow attackers to borrow massive amounts of capital with no collateral, execute trades that manipulate prices on DEXs, and repay the loan — all in a single transaction. If a protocol calculates its moving average using recent on-chain price data, the attacker can skew that average temporarily and exploit the resulting mispricing before the average corrects.
3. How does TWAP differ from a standard moving average?
A Time-Weighted Average Price (TWAP) weights each price observation by how long it persisted, rather than treating all observations equally. This makes it more resistant to momentary price spikes but still vulnerable to sustained manipulation over the measurement period. TWAP is commonly used by Uniswap and other major DEXs.
4. What is the best defense against oracle manipulation in protocols using moving averages?
The most robust defense is a layered approach: use multiple independent data sources (both centralized and decentralized oracles), implement circuit breakers that pause operations when price deviations exceed thresholds, prefer median prices over averages, and apply time delays to critical operations that rely on moving average calculations.
5. Which DeFi protocols commonly use moving averages?
Major protocols include Chainlink (for price feeds), Uniswap (TWAP oracles), Aave (interest rate calculations), Synthetix (exchange rates), Ampleforth (rebase calculations), and many AMMs for dynamic fee adjustment. Any protocol dealing with price data or risk management likely uses some form of moving average.
6. How do precision errors affect moving average calculations in Solidity?
Solidity doesn't handle decimals natively, only integers. When calculating moving averages, division operations can lose precision through rounding, and these small errors compound over time. This is especially problematic for assets with fewer decimal places. Best practices include using larger decimal precision in intermediate calculations and implementing proper rounding strategies.

Glossary

TermDefinition
Moving averageA calculation that smooths price data over a specified period by continuously updating the average as new data arrives.
Simple moving averageAn average computed by summing values over a fixed number of periods and dividing by that count, giving equal weight to each observation.
Exponential moving averageA weighted moving average that gives exponentially decreasing weight to older observations, making it more responsive to recent data.
TWAPTime-Weighted Average Price — a moving average that weights each price by the duration it persisted.
OracleAn external data feed that provides off-chain information to smart contracts.
Flash loanAn uncollateralized loan that must be borrowed and repaid within a single transaction.
Automated market makerA protocol that uses mathematical formulas and liquidity pools to facilitate token trading without traditional order books.
Circuit breakerA safety mechanism that pauses protocol operations when abnormal conditions are detected.
Precision lossCumulative inaccuracy caused by integer arithmetic and rounding in smart contract calculations.
Rounding errorSmall inaccuracies from truncating decimal values in Solidity's integer-only arithmetic.

oog
zealynx

Subscribe to Our Newsletter

Stay updated with our latest security insights and blog posts

© 2024 Zealynx