Prices and oracles

Doug Hoyte
Euler Labs

--

Euler builds upon Uniswap’s time-weighted average price (TWAP) oracles to allow users to lend and borrow almost any fungible token. This is part 1 of a series of articles in which we describe how these TWAP oracles work and the advantages they bring to users of our decentralised lending protocol.

The concept of ‘price’

Sometimes identical assets can be sold at different prices in different markets. For example, the price of a widget is going to increase as it moves through the supply chain from the factory through wholesalers through to your neighbourhood retailer. Since people are paying different amounts for the exact same thing, it suggests that it doesn’t really make sense to talk about the single price of something.

Of course there is nothing stopping you from travelling to the factory, buying a bunch of the widgets and standing outside the retailer selling them directly to customers at a discount. If you do this you’d be practising what is known as arbitrage, and would likely force the retailer to lower its widget prices (or get you arrested for loitering).

Arbitrage is the guiding force that causes markets around the world to converge on common prices. The beautiful thing about it is that no coordination is required. As long as the transaction costs and trading risks aren’t too high, enough entities acting in their own self-interest is enough to ensure that the price of, say, gold moves at approximate lock-step in New York, London, and elsewhere.

Trade sizes

So maybe arbitrage is what creates the price of an asset. On the other hand, have you ever bought a widget from the neighbourhood retailer rather than going direct to a factory in China? Of course you have. If you’re buying small quantities it’s natural to expect the unit price to be higher due to transportation costs and middle-men.

Somewhat confusingly, unless you have studied economics or interacted with financial markets in practice, the natural state of prices is in fact the opposite: If you are buying a small quantity of a financial instrument, you can typically expect a better price than if you are buying a large quantity.

To recognise that price is somehow a function of trade size, economists refer to the “marginal” price. This is simply the best available price for an infinitesimally small amounts of an asset. Naturally you can’t buy an infinitesimally small amount of widgets: price curves are rarely the nice, smooth, differentiable functions that economists study. Instead, they are usually either free-for-all orderbooks populated by whoever has shown up to trade (like a stock exchange), or a more regular pricing band structure (like the foreign exchange market). On the other hand, systems like Uniswap are closer to smooth pricing functions, but we’re getting ahead of ourselves.

Competition or collusion?

There is a lot of information embedded in a price. This is one way that financial markets help society. Even if you have no intention of buying or selling widgets, being able to observe in real time that their price on the other side of the world is increasing can be one of many valuable signals that will help you plan your economic activities.

But keep in mind that prices are abstractions, and are missing important context. Consider the gas stations in your town: Their gasoline prices are nearly identical and they move up and down together nearly in lock-step. This is clearly an example of competitive market forces converging prices to their common minimum viable level, right?

Not so fast. Couldn’t it also be the case that the gas station operators are colluding to move their prices together to avoid the negative effects of competition? Yes, and given the price alone it is impossible to tell which it is.

Oracles

Just like in the so-called real world, many blockchain systems need access to prices of assets:

  • A system that is buying or selling some good or service needs to ensure that it is using accurate market rates, either for its product pricing, its input costs, or both.
  • Derivative trading systems enable participants to effectively bet with one another about whether the prices will go up or down.
  • Lending systems must monitor the values of loans and collateral to ensure that loans are never under-collateralised.

Systems that provide prices to smart contracts are referred to as Oracles. Broadly speaking there are two classes of oracles: off-chain and on-chain. Each has advantages and disadvantages.

Off-chain oracles

In this design, prices are collected from sources external to the blockchain such as trading exchanges, and then these prices are embedded on the blockchain by trusted parties.

A well-known off-chain oracle today is Chainlink. At a high level, Chainlink works by assigning special privileges to nodes that control a certain amount of LINK tokens. These nodes coordinate to create an on-chain price in a series of time-bounded rounds. Every round, each node submits a price and then a smart contract takes the median of these prices and makes this value available to on-chain smart contracts.

One very powerful advantage of this approach is that the collected information can be anything at all. In fact, on Chainlink it is possible to bring data such as real-world weather statistics, or even pure randomly generated numbers, onto the chain.

On the other hand, some blockchain users are uncomfortable with this approach, because such systems do not provide what is called “objective” data. Objective in this sense means this is that it is possible for a user to verify how the data was arrived at purely by looking at the operation of the blockchain.

As an example, you can objectively verify the balance of an address’s wallet by downloading the history of the blockchain and (after making sure you aren’t on a malicious fork) replaying all the transactions up until the present. The wallet’s balance is now a self-evident, objective truth that you have determined without making any additional security assumptions beyond the security of the blockchain itself.

LIBOR

Aside from theoretical purity, is this concept of objectivity important? I believe so. Let’s consider a real-world example.

LIBOR stands for “London Inter-bank Offered Rate” and is supposed to represent the current interest rate that will be applied when borrowing money for a short period of time. In a sense, this value can be considered the price of money. It is one of the most important numbers in the entire financial system. Whenever you take out a mortgage, carry a credit card interest, or interact with the financial system at all, you are likely affected by this number. But how is this number actually generated?

LIBOR can itself be thought of as an oracle. Every day, each of a group of major banks create estimates of how much it would cost them to borrow money, supposing they wanted to. The banks are supposed to go take a look at the prices their brokers are quoting and aggregate them in some way, although it is largely at their discretion how they do so. Once each bank has come up with its number, it submits it to an association tasked with aggregation. The association throws out the highest and lowest estimate under the assumption they may be unrepresentative outliers, and then averages the remaining estimates. This average is then published as the daily LIBOR.

Banks have a large amount of influence over their prices and they aren’t held financially accountable for the rates they submit in any way. In a pure market-driven system, if a bank published a “bad” price, then counterparties would trade on that price until such time as prices had converged through arbitrage.

Even worse than allowing banks to be sloppy with their price submissions, as was revealed in a major 2008 scandal, many of the banks submitting prices had significant exposure to derivatives based on the published LIBOR value. Traders at the banks would coordinate with the people at the bank tasked with making the LIBOR submissions and with traders at other banks to push the LIBOR in directions beneficial to their trading positions.

The problem is two-fold: First of all, there is no such thing as the single price of an asset, beyond what can be supplied by a market-driven arbitrage system, and any attempt to compile such a value is to some degree a fiction. But more seriously, the origins of the prices comprising LIBOR are not transparent, and there are no market-driven consequence to a bank for publishing incorrect data.

On-chain oracles

With smart contracts, trading systems can be built entirely on-chain. This naturally gives rise to the notion that asset prices could be accessible as objective truths to other smart contracts. By using the quoted prices as signals, systems that need prices can be entirely hermetic and self-contained within the scope of the blockchain. (Whether such systems should even be called “oracles” is a debate we’ll ignore.)

The most well-known trading system that exists purely on-chain is Uniswap. Uniswap’s smart contract implements an Automated Market Maker which allows liquidity providers to deposit two assets into a smart contract, and a trader to exchange one asset by supplying the other. The price of this exchange depends on how depleted each component of the pool is at the time of the trade.

Price snapshots

Since the current marginal price of assets in a Uniswap pool can be determined at any time by looking at the relative quantities of assets, it is tempting to use this as a source for price information. However, this should be done with care. Snapshots of the pool quantities at any particular moment in time can be manipulated.

Of course this isn’t a problem with Uniswap, or even really unique to blockchains. Note the phenomenon of year-end “window dressing” by mutual funds. Since funds are commonly assessed by their year over year performance, there is a strong incentive to end the year with a high net asset value, even if it will revert right back the following morning. There are many other examples of unusual trading activity at the end of a quarter, or on the last ticks before market close, that suggest people are manipulating prices in order to influence snapshots.

Flash loans

Consider your chequing account. You can write a cheque even if you don’t have the funds in your account to cover it. As long as you deposit those funds into your chequing account before the cheque clears, your payment will process successfully. (Traditionally, at the end of each day banks apply all the daily credits first before moving on to the debits — there are fewer bounced cheques that way).

You can think of using cheques like this as a short-term uncollateralised loan. Suppose somebody wants to sell a car quickly and is asking a very low price. You write a cheque to buy the car, immediately take it over to a dealership, and sell it for a higher price. You then deposit the cheque the dealership gives you before your original cheque clears, netting yourself a profit on the transaction. You could have done it with an entirely empty chequing account.

On Ethereum this is taken one step further: By employing the model of atomic database transactions, operations can be undone once they are detected to be unprofitable. In the case above it would be as if the dealership didn’t want to buy the car you could be guaranteed to give back the car to the original seller, get your cheque back, and pretend nothing ever happened. (Although tempting to describe this as unique to blockchains, that isn’t entirely true either — many broker platforms offer contingency orders that resemble atomic transactions).

Time-weighted average prices

The price snapshot problem gets worse in the presence of flash loans. With large loans, the pool sizes in Uniswap markets can be altered enough to seriously distort price snapshots.

Because of this, Uniswap version 1 was unsuitable for use as a price oracle (although many projects did/do use it as such, often disastrously). Fortunately, Uniswap version 2 includes a building block of a solution to the snapshot problem: Time-Weighted Average Prices (TWAP).

Instead of using the current price, TWAPs let us compute what the average price has been over an interval of time. The way they works is that each Uniswap pool keeps a running sum that has the current price added to it every second. Given two of these records you subtract them and divide by the number of seconds elapsed to get the average price over that interval.

  • Short-term price spikes don’t move the price significantly because the averaging adds a dampening effect. Not only do would-be price manipulators need to spike the price, but they also need to hold it at the spiked levels for a duration of time.
  • Because flash loans must be repaid within the same transaction they are granted, from the blockchain’s perspective they take no time at all. This means they cannot be used to manipulate the TWAP: They change the price for 0 seconds, so nothing is added to the running sum.

Challenges with TWAP

Although Uniswap 2 is very popular, its TWAP support is not as widely used as some had expected. It turns out that using it in a production system has several challenges.

Most importantly, the Uniswap smart contract does not keep historical values of the running price sum in its storage — just the current values. This means that to retrieve a price, contracts must record a value in one transaction and then wait for some time before recording the next. As well as costing extra gas, this means there may be periods of time where prices are unavailable because the recorded values are too old.

At Euler we have been working on some ways to use Uniswap’s TWAP more effectively, and we’ll be describing our system in more detail soon, so please subscribe to be notified when part 2 of this series is available.

Conclusion

There is no single concept of ‘the price’ that is equally useful for all trading parties. Prices differ depending on how they are calculated, where they are measured, how assets are traded, and how much of an asset someone wants to buy or sell. Getting ‘the price’ of an asset on-chain is no easy task and most solutions come with compromises in terms of decentralisation and accuracy. Uniswap offers a decentralised on-chain price oracle that gives users access to the average price over some interval of time. These oracles are resistant to price manipulation, but come with their own trade-offs. We will explain more about some of the advantages and disadvantages of Uniswap’s oracle solution in the near future, so keep your eyes peeled!

About Euler

Euler is a capital-efficient permissionless lending protocol that helps users to earn interest on their crypto assets or hedge against volatile markets without the need for a trusted third-party. Euler features a number of innovations not seen before in DeFi, including permissionless lending markets, reactive interest rates, protected collateral, MEV-resistant liquidations, multi-collateral stability pools, sub-accounts, risk-adjusted loans, and much more. For more information, visit euler.finance.

Join the Community

Follow us on Twitter. Join our Discord. Keep in touch on Telegram (community, announcements). Check out our website.

Disclaimer:

This piece is provided by Euler Labs Ltd. for informational purposes only and should not be interpreted as investment, tax, legal, insurance, or business advice. Euler Labs Ltd. and The Euler Foundation are independent entities.

Neither Euler Labs Ltd., The Euler Foundation, nor any of their owners, members, directors, officers, employees, agents, independent contractors, or affiliates are registered as an investment advisor, broker-dealer, futures commission merchant, or commodity trading advisor or are members of any self-regulatory organization.

The information provided herein is not intended to be, and should not be construed in any manner whatsoever, as personalized advice or advice tailored to the needs of any specific person. Nothing on the Website should be construed as an offer to sell, a solicitation of an offer to buy, or a recommendation for any asset or transaction.

This post reflects the current opinions of the authors and is not made on behalf of Euler Labs, The Euler Foundation, or their affiliates and does not necessarily reflect the opinions of Euler Labs, The Euler Foundation, their affiliates, or individuals associated with Euler Labs or The Euler Foundation.

Euler Labs Ltd. and The Euler Foundation do not represent or speak for or on behalf of the users of Euler Finance. The commentary and opinions provided by Euler Labs Ltd. or The Euler Foundation are for general informational purposes only, are provided “AS IS,” and without any warranty of any kind. To the best of our knowledge and belief, all information contained herein is accurate and reliable and has been obtained from public sources believed to be accurate and reliable at the time of publication.

The information provided is presented only as of the date published or indicated and may be superseded by subsequent events or for other reasons. As events and markets change continuously, previously published information and data may not be current and should not be relied upon.

The opinions reflected herein are subject to change without being updated.

--

--

Euler Labs
Euler Labs

Published in Euler Labs

We’re a UK tech startup harnessing the power of mathematics to build high-performance non-custodial protocols on #Ethereum and other blockchains.

No responses yet