# Ensuring Safe Oracle Usage in DeFi: Best Practices for a Secure and Reliable Ecosystem
## The Risks of Relying on Chainlink as the Sole Source of Truth for DeFi Price Feeds
Chainlink has emerged as a popular decentralized oracle network for many DeFi projects, providing secure and reliable off-chain data, including price information. However, relying solely on Chainlink as the single source of truth for your project's price feed can introduce potential risks and challenges. In this article, we will discuss the concerns associated with relying exclusively on Chainlink and explore the benefits of diversifying your price feed sources.
1. **Dependency on a single protocol**: While Chainlink is known for its robust security features and reliable data sources, relying on it as the sole price feed exposes your entire business model to the risks associated with a single protocol. In the DeFi ecosystem, where millions of dollars are at stake, this dependency could prove to be a point of vulnerability.
2. **Centralization concerns**: One of the core principles of DeFi is decentralization, and relying exclusively on Chainlink might be seen as a deviation from this principle. By diversifying your price feed sources, you can reduce the potential centralization risks and create a more resilient ecosystem.
3. **Potential for manipulation**: Although Chainlink employs various measures to prevent price manipulation, no oracle solution is completely immune to attacks. By using multiple oracle solutions, you can mitigate the risks associated with manipulation and ensure a more accurate representation of the market.
4. **Customizability**: Projects like Compound have opted for solutions like the Open Price Feed to allow for greater customization and control over their price feed mechanism. By using a combination of oracles, you can tailor your price feed to your project's specific needs and requirements.
## What's the best practices using Chainlink price feeds?
* **Check for non-zero prices**: Ensure the returned price is greater than zero to avoid any issues related to invalid data.
* **Check staleness**: Verify that the price data is not stale or outdated by comparing the timestamp of the last update to the current time. You can set a threshold for acceptable staleness based on your specific use case.
* **Implement circuit breakers**: Establish circuit breakers or emergency stop mechanisms to halt operations if the price data becomes unreliable, preventing any potential negative consequences.
* **Stay up to date**: Regularly review the Chainlink documentation and stay informed about updates, improvements, or best practices to ensure you are using the price feeds most effectively.
This snippet below is a good example of handling Chainlink price feeds. However, we can further enhance security by incorporating an additional price oracle and comparing the two, as seen in the practices of some DeFi protocols.
In addition to these measures, it is crucial to carefully monitor the Chainlink price oracle for any updates or changes that may impact the accuracy or reliability of the price feed. This includes being vigilant for news about price feed migrations, token contract changes, or any other significant developments from the Chainlink team. Staying informed about these changes will help ensure the continued effectiveness of your price feed integration and maintain the overall security of your protocol.
```
function _getLatestPrice(string memory symbol)
internal
view
returns (uint256, uint256)
{
require(address(priceFeeds[symbol]) != address(0), "missing priceFeed");
(
,
//uint80 roundID
int256 price, //uint256 startedAt
,
uint256 timeStamp, //uint80 answeredInRound
) = priceFeeds[symbol].latestRoundData();
require(price > 0, "price cannot be zero");
// Check for staleness
uint256 stalenessThreshold = 1 hours; // Set your staleness threshold
uint256 currentTime = block.timestamp;
require(currentTime - timeStamp <= stalenessThreshold, "stale price data");
uint256 uPrice = uint256(price);
return (uPrice, timeStamp);
}
```
## An alternative, TWAP Oracles
TWAP, or Time-Weighted Average Price, is a type of price oracle used in the DeFi ecosystem. It calculates the average price of an asset over a specified time period, taking into account the price and the duration for which that price was valid. The primary goal of TWAP oracles is to reduce the impact of price manipulation and sudden price swings in decentralized finance applications. By considering the historical prices and their respective durations, TWAP oracles provide a more stable and less volatile representation of an asset's value, making them an attractive option for DeFi protocols and projects. Here are some pros and cons of using TWAP oracles:
**Pros**:
1. **Reduces price manipulation**: By calculating the average price over a period, TWAP oracles mitigate the impact of sudden or manipulated price spikes.
2. **Smooths out price fluctuations**: TWAP oracles help minimize the impact of short-term market volatility, making them suitable for applications that require stable price data.
3. **Simple to implement**: TWAP oracles can be relatively easy to integrate into DeFi protocols, as they only require historical price data and a calculation method.
4. **Customizable time frame**: The time period for calculating the average price can be adjusted according to the specific needs of the DeFi application.
**Cons**:
1. **Delayed response to rapid market changes**: While TWAP oracles help reduce the impact of short-term price fluctuations, they may not react quickly to significant market movements that could be relevant for some DeFi applications.
2. **Historical data requirements**: To calculate the time-weighted average price, a TWAP oracle needs access to historical price data, which could be a challenge for some DeFi protocols or projects.
3. **Potential inaccuracies**: The accuracy of a TWAP oracle depends on the quality and frequency of the price data it uses. If the data source is compromised or experiences issues, the oracle's output might not accurately represent the asset's value.
## TWAP powered Chainlink price feeds
In a DeFi protocol, it is possible to use Chainlink price feeds as the primary source for instant and accurate spot prices, while incorporating TWAP price feeds as a fallback mechanism or a validation tool. This approach combines the strengths of both oracles, enhancing the reliability and security of the price data used in the protocol.
By setting the TWAP price as a minimum threshold for Chainlink's validation, the protocol can ensure that the primary price feed remains accurate and resistant to manipulation. In cases where the Chainlink price feed is compromised or deviates significantly from the TWAP price, the protocol can switch to the TWAP price feed as a fallback mechanism. This helps to maintain the integrity of the price data used in the protocol, providing an additional layer of security against potential manipulation or issues with the primary price feed.
Using Chainlink and TWAP price feeds together in this manner allows a DeFi protocol to achieve a balanced and robust price discovery mechanism, benefiting from the instant and accurate data provided by Chainlink, while also leveraging the time-weighted averages offered by TWAP to minimize the impact of short-term price fluctuations and protect against potential vulnerabilities.
## How do some DeFi protocols handle their price feeds?
### GMX:
GMX employs a combination of price feeds from different sources to ensure accurate pricing. Chainlink serves as the primary price feed, while Uniswap V2 provides an additional layer of validation. By utilizing both price oracles, GMX can maintain reliable pricing even if one source experiences issues, ensuring the reported price is consistently accurate and trustworthy.
**Referred code**: https://github.com/gmx-io/gmx-contracts/blob/master/contracts/core/VaultPriceFeed.sol
### Compound:
Compound leverages open price feeds, incorporating more sophisticated processes to determine accurate prices. External feeds, such as Coinbase, provide initial price data, which is then validated through TWAP oracles, similar to GMX’s approach. This method allows Compound to maintain accurate and reliable pricing by cross-referencing multiple sources.
#### Compound Oracle Mech in Detail
Compound Labs has developed a new oracle solution called the Open Price Feed, aiming to create a permissionless, upgradable price feed for the Compound protocol and other DeFi projects. The Open Price Feed differs from Chainlink in several ways, which are outlined below:
1. **Reporter and Poster mechanism**: The Open Price Feed allows Reporters (such as Coinbase Pro) to sign price data using a known public key. Posters (any Ethereum address) can then submit this signed data on-chain. This mechanism separates the data providers (Reporters) from the parties that submit the data on-chain (Posters), allowing for more decentralization and potentially reducing the cost of maintaining the oracle.
2. **Permissionless and upgradable**: The Open Price Feed is designed to be permissionless, meaning any exchange or data provider can become a Reporter and contribute to the price feed. This approach promotes decentralization and allows the community to add or remove Reporters through governance, potentially enhancing the reliability and accuracy of the data.
3. **Anchor price**: The Open Price Feed uses an on-chain "Anchor price" as a sanity check for the prices reported by the Reporters. In Compound's proposal, the Anchor price is derived from a 30-60 minute TWAP (time-weighted average price) using the asset/ETH pair on Uniswap v2. The reported price is accepted only if it is within 20% of the Anchor price, providing an additional layer of protection against price manipulation.
4. **Community governance**: The Open Price Feed is designed to be governed by the community, allowing for upgrades and modifications through community decisions. This approach aims to reduce reliance on a single party or closed-source processes, ensuring that the protocol remains decentralized and adaptable to the community's needs.
Compound Labs developed the Open Price Feed to reduce reliance on their team and closed-source processes and to enable the community to maintain and upgrade the price feed. By adopting this new oracle solution, Compound aims to promote decentralization, improve the security and reliability of the price feed, and give the community more control over the protocol's development.
**Referred code**: https://github.com/compound-finance/open-oracle/tree/master/contracts
## Conclusion
The best way of using an oracle in the DeFi space depends on the specific needs and goals of the project. However, in many cases, a combination of TWAP and Chainlink can offer significant advantages over using Chainlink alone or Chainlink with Uniswap V2.
By incorporating TWAP oracles alongside Chainlink, DeFi protocols can benefit from the stability provided by time-weighted average prices while maintaining the security and accuracy of Chainlink's decentralized price feeds. This approach can mitigate the risk of price manipulation and reduce the impact of sudden price fluctuations, resulting in a more reliable and stable pricing mechanism.
In comparison, using Chainlink with **Uniswap V2 might be more vulnerable to price manipulation due to the possibility of front-running and liquidity pool manipulation on decentralized exchanges**. While Uniswap V2 can still provide valuable on-chain price data, combining Chainlink with TWAP oracles can offer an additional layer of protection against potential vulnerabilities, making it a more optimal choice for many DeFi projects.
## Appendices
https://www.comp.xyz/t/migrating-to-the-open-price-feed/34
https://docs.compound.finance/v2/prices/
https://blog.openzeppelin.com/compound-open-price-feed-uniswap-integration-audit/
https://blog.chain.link/levels-of-data-aggregation-in-chainlink-price-feeds/
https://smartcontentpublication.medium.com/twap-oracles-vs-chainlink-price-feeds-a-comparative-analysis-8155a3483cbd
https://www.immunebytes.com/blog/what-are-twap-oracles-and-how-are-they-different-from-uniswap/
https://medium.com/@bytetradelab/the-inner-workings-of-gmx-part-1-548ef7528592
https://gmxio.gitbook.io/gmx/