Original title: "So you want to use a price oracle"
Original source: SAMCZSUN
Original compilation: 0x26
In late 2019, I published an article entitled "Taking undercollateralized loans for fun and for profit". In this post, I describe an economic attack on Ethereum dApps that rely on accurate price data for one or more tokens. Unfortunately, by the end of 2020, many projects had made very similar mistakes, the most recent example being the Harvest Finance hack arbitrage attack, which resulted in a collective loss of $33 million for protocol users.
While developers are familiar with vulnerabilities such as reentrancy, it is clear that people do not often think about oracle price manipulation. Conversely, the number of exploits based on reentrancy has declined in recent years, while the number of exploits based on price manipulation is on the rise. So I think it's about time someone puts out an authoritative resource on price manipulation.
This article is divided into three parts. For those unfamiliar with the subject, an introduction to price feed oracles and oracle manipulation is prepared in the article. Those already well-informed can skip straight to the case studies section, where we review past oracle-related vulnerabilities and exploits. Finally, we summarize some methods that developers can apply to their projects to avoid oracle price manipulation.
Wednesday, December 1, 2015. Your name is David Sparger and you are at the Peking Duk concert in Melbourne, Australia. You want to meet the band in person, but there are two security guards between you and the backstage aisle, and it's impossible for them to let normal people in.
You know how security reacts if you act like you belong here. Family members will definitely be allowed to visit backstage, so all you have to do is convince the security that you are their relative. You think about it for a while, and then come up with a plan that can only be described as genius or madman.
After quickly arranging everything, you confidently walk towards the security guard. You introduced yourself as David Sbago, from the Peking Duk family. When the guards ask for evidence, you show them irrefutable evidence - Wikipedia (you add your name, David Spagg, to the last line of the first paragraph of the Wikipedia entry).

The guard waved for you to pass, let You are waiting in the background. One minute passed, two minutes passed. Five minutes later, you're hesitant to run away before law enforcement shows up. When you were about to "break out," Reuben Styles (band member) came up and introduced himself. You walk with him to the green room, where the band is impressed by your intelligence, and you end up having a few beers together. Afterwards, they share what happened on their Facebook pages.

Price feed oracle, in general, is any price information you consult. When Pam asks Dwight about the cash value of the Schrute Buck, Dwight is predicting the price. (From the American drama "Office")

In the Ethereum network, everything is a smart contract, and so is the price feed oracle. Therefore, it is more useful to distinguish how a price feed oracle obtains its price information. First, existing off-chain price data can be simply fetched from a price api or exchange and brought on-chain. In another case, the instantaneous price can be calculated by querying an on-chain decentralized exchange.

Both options have their own advantages shortcoming. Off-chain data is generally slower to respond to volatility, which is only as good or bad depending on what you're trying to use it for. It typically requires a small number of privileged users to push data onto the chain, so they must be trusted not to do evil or be forced to push strange data updates. On-chain data does not require any privileged access and is always up-to-date, but this means it can be easily manipulated by attackers, leading to catastrophic failures.
Let’s look at some examples where poorly integrated price feed oracles caused DeFi projects to suffer In the event of loss of funds.
Synthetix sKRW’s oracle failure
Synthetix is a derivatives platform that allows users to stake assets into other assets. To facilitate this, Synthetix (at the time) relied on a custom off-chain price feed implementation, one of which was calculated from a secret set of price feeds and published on-chain at a regular interval. Users are then allowed to take long or short positions on the asset it backs at these prices.
On June 25, 2019, a price feed that Synthetix relied on incorrectly reported the price in KRW as higher than it actually was out 1000 times. Due to additional errors elsewhere in the price feed oracle system, this price was accepted by the system and posted on the sKRW chain where trading bots can quickly enter and exit the sKRW market for profit.

Although the Synthetix team is in contact with this trader Negotiate to exchange lost funds back in the form of bug bounties. But in theory, the robot could make more than $1 billion in profits this time around.
Synthetix correctly executed the oracle contract and lowered the price from multiple sources to prevent traders from Predict price changes before changes are released. However, one case of an upstream price feed failure turned out to be devastating. This illustrates the risks of price-feeding oracles using off-chain data: they don't know how to calculate prices, so the system must be carefully designed to ensure that all potential failure modes are properly handled.
Low collateral loans
As mentioned, I published an article in September 2019 outlining the risks of using price feed oracles that rely on on-chain data. Although I strongly recommend reading the original, but the article is long and full of technical details, which may be hard to follow. Therefore, I will provide a simple explanation here.
Imagine you use a decentralized lending platform. Users can deposit assets on the platform as collateral, and can also borrow other assets, but the maximum amount depends on the value of the assets they deposit. Let's assume a user wants to borrow USD using ETH as collateral, the current price of ETH is $400, and the collateralization ratio is 150%.
If a user deposits 375 ETH, it means that $150,000 of collateral is deposited. They can borrow $1 for every $1.50 in collateral, so they can borrow up to $100,000 from the system.

But of course, in blockchain On top of that it is not as simple as claiming that 1 ETH is worth $400, because a malicious user can simply claim that 1 ETH is worth $1,000 and then take all the money out of the system. Therefore, it is important for developers to find the most suitable price feed oracle, such as the current spot price of Uniswap, Kyber, or the price of another decentralized exchange platform.

At first glance, this appears to be the right way. After all, whenever you want to buy or sell ETH, the price on Uniswap is always roughly correct, because any deviation is quickly corrected by arbitrageurs. However, it turns out that spot prices on decentralized exchanges can be grossly incorrect during trades, as the example below demonstrates.
Think about how the Uniswap retained asset system works. The price is calculated based on the amount of assets held by the reserve, but the assets held by the reserve change as users trade between ETH and USD. What happens if a malicious user makes a transaction before and after taking a loan from your platform?
Before users can apply for a loan, they need to spend $2 million to buy 5000 ETH. The Uniswap exchange is now calculating the price as 1 ETH = $2,600. Now, their 375 ETH can be used as collateral to stake assets worth up to $650,000. In the end, they trade $2 million back to the original 5000ETH, which will reset the price back to normal. As a result, the lending platform lost $550,000.

This case study illustrates the use of The most common mistake when using decentralized exchanges as price feed oracles - attackers have almost complete control over the price during the transaction and try to manipulate it exactly like reading the weight on the scales before the balance settles. In this way, you may get wrong numbers, and in some cases, it may cause a lot of losses.
Synthetix MKR manipulation
In December 2019, Synthetix was attacked again due to oracle price manipulation. Notably, it crosses the barrier between on-chain price data and off-chain price data.
Reddit user u/MusaTheRedGuard has noticed that an attacker is doing some very suspicious things against sMKR and iMKR (anti-MKR) transaction. The attacker first bought a long position on MKR and then bought a large amount of MKR from the Uniswap eth/MKR pair. After waiting for a while, the attacker sold their MKR for iMKR and sold them back to Uniswap. Then they repeated the process.
Behind the scenes, the attackers’ transactions via Uniswap allowed them to adjust the price of MKR on Synthetix at will. This is likely because the off-chain price feed that Synthetix relies on is actually dependent on MKR's on-chain price, and there isn't enough liquidity for arbitrageurs to readjust the market to optimal conditions.

This incident illustrates a fact, Even if you think you are using off-chain price data, in fact you may still be using on-chain price data, and you may still be exposed to the complexities involved in using this data.
The bZx Hack
< p line="rXta">In February 2020, bZx was hacked twice within a few days, and the amount of attack was about 1 million US dollars. You can find palkeo support for this at here The technical analysis was given for both attacks, but now let's analyze the second hack.
In the second attack, the attacker first used ETH to purchase almost all sUSD on Kyber. The attacker then purchased a second batch of sUSD from Synthetix and deposited it on bZx. The attacker borrowed the maximum amount of ETH using sUSD as collateral. They then sold the sUSD back to Kyber.
If you have been paying attention, you will see that this is essentially the same undercollateralized loan attack, just using a different collateral and different decentralized exchanges.
Harvest Finance was arbitrage event
< p line="y4iM">On October 26, 2020, an anonymous user hacked Harvest Finance's funding pool using a technique you may have guessed by now. Available at here Read the official post-mortem, but let me summarize again: The attacker lowered the price of USDC in the Curve pool by executing a transaction, entered the Harvest pool at a manipulated price, recovered the price by reversing an earlier transaction, and returned it at a more High prices exit the Harvest pool. This caused more than $33 million in damages. (Artificially caused exchange rate deviation and profited from it)
By now I hope you have learned to recognize the commonality: it is not always obvious that you are Using a price feed oracle, if you don't follow the proper precautions, an attacker can spoof your protocol and withdraw all your money. While there is no one-size-fits-all solution, here are a few solutions that have worked for other projects in the past. Maybe one of these works for you too.
Shallow water market, don’t dive
  ;
Like diving headfirst into the shallow end of a swimming pool, diving headfirst into illiquid markets is painful and can lead to huge expenses that change your life forever. Before you consider planning to use a complex specific price oracle, consider whether the token has enough liquidity to warrant integration with the platform.
A bird in the hand is worth two in the bush
Seeing Uniswap’s potential token exchange rate can be fascinating, but it’s only final if you actually hit the trade and the token is in your wallet after the transaction succeeds result. Likewise, the best way to determine the exchange rate between two assets is to do a direct asset swap. This approach is good because there are no regrets and no assumptions. However, it may not apply to those agreements that require holding the original assets, such as lending platforms.
Almost a decentralized oracle
p>
To summarize, one way of saying the problem with oracle models that rely on on-chain data is that they are a bit too new. If that's the case, why not artificially delay it? Write a contract that updates with the latest price on a decentralized exchange like Uniswap, but only when requested by a small group of privileged users. Now, even if an attacker can manipulate the price, they can't make your protocol actually use it.
This method is very simple and fast to implement, but it also has some disadvantages - when the chain is congested , you may not be able to update prices as quickly as you would like, and still be vulnerable to internal and external attacks. Also, now your users need to trust that you will actually keep the prices updated.
speed bump
Manipulating price oracles is a time-sensitive operation because arbitrageurs are always on the sidelines and love to optimize any sub-optimal market opportunities. If the attacker wants to minimize risk, they will want to implement the entire transaction that manipulates the price feed oracle in one transaction, so that it is impossible for arbitrageurs to arbitrage in the middle. As a protocol developer, implementing a delay as short as 1 block between a user entering and exiting the system is sufficient if the system supports it.
Of course, this may affect composability, and cooperation between miners and traders is increasing. In the future, bad players could manipulate prices across multiple transactions, knowing that the miners they partner with will guarantee that no one can jump in the middle and take a cut of their profits.
Time-Weighted Average Price (TWAP)
Uniswap V2 introduces TWAP oracles for on-chain developers. The docs describe in more detail the exact security guarantees oracles provide, but in general TWAP oracles are highly resistant to oracle manipulation attacks for large pools of transactions over long periods of time without block congestion force. However, due to the nature of its implementation, it may not be able to react quickly enough to moments of high market volatility, and is only suitable for assets that already have liquidity on-chain.
M-of-N Quotation
Sometimes they say if you want to do the right thing, you better do it yourself. What if you call up N trusted friends and ask them to submit what they think is the correct on-chain price, with the best M answers being the current price?
Many large projects today take this approach: Maker runs a series of For price feeds, Compound created the Open oracle and provided quotation functions such as Coinbase, and Chainlink collected price data from Chainlink operators and published it on the chain. Remember, if you choose to use one of these solutions, you've now delegated trust to a third party, and your users must do the same. Requiring bidders to manually post updates online also means prices may not be updated in a timely manner during times of high market volatility and on-chain congestion.
Feed price Oracles are a vital yet often overlooked component of DeFi. Using price feed oracles safely is difficult, and there are many ways to screw yourself and your users. In this post, we discuss past examples of price oracle manipulation and determine that reading price information during a transaction can be unsafe and can lead to catastrophic financial losses. We also discussed some techniques that other projects have used in the past to combat price feed oracle manipulation. Ultimately though, every situation is unique and you may find yourself unsure if you are using the price feed oracle correctly. If so, go ahead and seek advice!
Welcome to join the official BlockBeats community:
Telegram Subscription Group: https://t.me/theblockbeats
Telegram Discussion Group: https://t.me/BlockBeats_App
Official Twitter Account: https://twitter.com/BlockBeatsAsia