# Hyperdrive Explainer ## Overview At its core, Hyperdrive is a protocol for trading assets that can be redeemed for their full face value at maturity. To ensure that we have a balanced market where the price of bonds can be increased and decreased, we support two basic operations: purchasing bonds (opening a long position) and [short selling](https://www.investopedia.com/terms/s/shortselling.asp) bonds (opening a short position). Hyperdrive pools are configured with a "position duration" or "term length" that specifies how long bonds must be held before they mature. At any time, a user can purchase or short sell bonds on Hyperdrive with the pool's position duration. This is a notable departure from Element V1 where users had to purchase bonds with a pre-defined maturity time, which resulted in the user frequently receiving shorter-dated bonds than they wanted. Aside from improving the user experience for traders, Hyperdrive also improves the user experience for liquidity providers since they can "set and forget" their liquidity in the pool instead of frequently needing to move their capital to new pools as the bonds mature. ## Basics In order to understand the rest of the protocol, it's useful to have some familiarity with the basics of bond math. Throughout our documentation and the codebase, we use the concepts of price and fixed rate interchangeably because *they are interchangeable*. To explain this intuitively, we'll go through a simple example. Let's assume that our bonds have a period of 1 year. If Alice pays $1 for 1.05 bonds, she will receive $1.05 when they redeem their bonds at maturity. This is a return of $0.05 on a $1 investment, which equates to a 5% rate of return. Similarly, if we assumed that Alice purchased $1 worth of bonds that will pay a 5% rate of return, then we'd see that she would have $1 \cdot (1 + 0.05) = 1.05$ a year later (at maturity). We can generalize this example with the following identity. $p$ is the price of base in terms of bonds (i.e. how much each bond is worth), $r$ is the fixed-rate of our bonds represented in decimals, and $t$ is the term length of our bonds (normalized to a fraction of a year -- e.g. 6 months $\to$ 0.5). This gives us: $$ r = \frac{1 - p}{p \cdot t} \Leftrightarrow p = \frac{1}{1 + r \cdot t} $$ > Note: r represents the simple interest with no compounding ## Trading ### Longs A trader opens a long by purchasing bonds from Hyperdrive. We call this a long position because the trader makes money as the price of bonds increases. A trader that opens a long positions provides base to the pool and receives bonds (i.e. long tokens) in return. Traders can close their longs at any time. These trades are priced using the flat+curve pricing model, which captures the notion that the longs should receive some fixed interest from the time they held the bonds but will still be effected by changes in the pool's spot price. If they hold onto their bonds for the full position duration, they can redeem the bonds on the pool for the bond's face value. The trader will receive fixed interest on their investment as the bonds mature, but they won't receive any variable interest on the money that they invested over the position duration. With this in mind, we can say that traders that open long positions are exchanging variable interest for fixed interest. While there are different reasons for traders to purchase longs, it's enough to understand that speculators will open long positions whenever the fixed rate is higher than what they expect the term's variable rate to be. This will create downward pressure on the fixed rate that should bring it in line with the expected variable rate. To ensure that long positions are always solvent, the LPs must set aside the difference between the longs starting price and face value. To compensate the LPs for their money being locked up in a long position, the LPs receive all of the variable interest generated on the long position as well as the variable interest generated on their contribution to the long's solvency. With this in mind, longs are taking the other side of the trades since they are paying fixed interest in return for variable interest. As we shall see later, the LPs are actually taking on a short position every time a long is opened. #### Examples ##### Long Held for the Entire Term Length Imagine Alice wants to invest $1,000 in a fixed-rate investment using the Hyperdrive protocol. Here's how it works: 1. Alice deposits $1,000 into the Hyperdrive platform. 2. The platform calculates the face value of the bonds she will receive based on the current fixed rate and the time until maturity. For example, if the fixed rate is 5% per year and there are 6 months left until maturity, Alice will receive bonds with a face value of $1,025. 3. Alice will hold onto these bonds until they mature. When the bonds mature, Alice can redeem them for the initial $1,000 investment plus the fixed interest ($25 in this case), for a total of $1,025. During the 6-month term, Alice will receive fixed interest on her investment and will give up any variable interest that her investment may have earned. ##### Long Held for Half the Term Length Let's say that Bob believes that interest rates will decrease in the next 3 months, and he wants to benefit from the fixed rate for this period. He can go long on the fixed rate using the Hyperdrive protocol, but instead of holding until maturity, he plans to sell after 3 months. Here's how it works: 1. Bob decides to buy $1,000 worth of bonds with a 6-month term on the platform. 2. The platform calculates the face value of the bonds he will buy based on the current fixed rate and the time until maturity. For example, if the fixed rate is 5% per year and there are 6 months left until maturity, Bob will buy bonds with a face value of $1,025. 3. The platform uses Bob's payment of $1,000 to invest in the underlying variable rate asset on behalf of the liquidity providers. 4. After 3 months, the interest rates have decreased as Bob expected, and he decides to sell his position. The platform calculates the market price of his bonds using the flat + curve pricing model, which takes into account the remaining time until maturity, the new market fixed rate, and the accrued interest so far. 5. If the new market fixed rate is lower than the initial fixed rate, the bonds' market price will be higher than the initial purchase price, as the remaining fixed interest payments are now more valuable. Bob can sell his bonds at this higher price and make a profit. 6. If the new market fixed rate is higher than the initial fixed rate, the bonds' market price will be lower than the initial purchase price, as the remaining fixed interest payments are now less valuable. In this case, Bob would lose money if he decides to sell his bonds. In this example, Bob is effectively betting that interest rates will decrease during the first half of the term. If he's right, he'll make a profit, but if he's wrong, he'll lose money. Note that he's exposed to changes in the market fixed rate since he's selling before the bonds reach maturity. ### Shorts The accounting for shorts is more complicated than the accounting for longs, but the idea is simple. A trader that opens a short is selling a bond to the LPs at the current market price. The trader that is opening in the short position isn't really providing bonds to the LP, so we can't give the trader the money the LPs pay for the bonds. Instead the trader is given IOUs (the short tokens) that allow them to sell bonds to the pool at some time in the future for the agreed upon price. The capital that LPs paid for the bonds is invested in the yield source on behalf of the shorts where it will earn them variable interest. Since the shorted bonds can be redeemed at maturity, the short provides capital to the pool that covers the difference between the face value of the bonds and the amount the LPs paid. Just like how LPs receive variable interest and pay fixed interest when longs are opened, traders receive the variable interest and pay fixed interest when shorts are opened. Since the LPs are taking the long position, they receive fixed interest and give up variable interest. When a trader closes their short, they are really purchasing the partially-matured (or fully-matured) bonds that underly the short position. These bonds are then instantaneously sold to the LP for the price that was originally agreed upon. If the price of the bonds decrease, then the short will make a profit. #### Examples ##### Short Held for the Entire Term Length Suppose Bob believes that interest rates will rise and wants to benefit from the variable rate. He can go short on the fixed rate using the Hyperdrive protocol using the following steps: 1. Bob decides to sell $1,000 worth of bonds on the platform. 2. The platform calculates the face value of the bonds he will sell based on the current fixed rate and the time until maturity. For example, if the fixed rate is 5% per year and there are 6 months left until maturity, Bob will sell bonds with a face value of $1,025. 3. The platform then calculates the amount of capital Bob has to deposit to open this short position. This is done to ensure that Bob can cover the fixed interest payment that he will owe on the long position held by the liquidity provider. Since the bonds are worth $1,000 and the face value is $1,025, he must provide $25. 4. So, Bob deposits $25 and sells $1,000 worth of bonds. The platform uses the liquidity provider's $1,000 payment to invest in the underlying variable rate asset on Bob's behalf. 5. At the end of the 6-month term, Bob will have to buy back the bonds he sold, which will be worth the face value of $1,025. If the variable rate outperforms the fixed rate, he will have made a profit, since the variable rate investment will have grown more than the $25 fixed interest he owes to the LP. If not, he will have lost money. In this case, Bob is effectively betting that the variable rate will outperform the fixed rate during the term. If he's right, he'll make a profit, but if he's wrong, he'll lose money. ##### Short Position Held for Half the Term Length Suppose Bob believes that interest rates will increase in the next 3 months, and he wants to benefit from the variable rate for this period. He can go short on the fixed rate using the Hyperdrive protocol, but instead of holding until maturity, he plans to close his short position after 3 months. Here's how it works: 1. Bob decides to short $1,000 worth of bonds with a 6-month term on the platform. 2. The platform calculates the face value of the bonds he will short based on the current fixed rate and the time until maturity. For example, if the fixed rate is 5% per year and there are 6 months left until maturity, Bob will short bonds with a face value of $1,025. 3. The platform uses the liquidity provider's payment of $1,000 to invest in the underlying variable rate asset on behalf of Bob. 4. During the 3-month period, Bob accrues variable interest on the $1,000 capital. Let's say the variable interest accrued during this time is $15. 5. After 3 months, the interest rates have increased as Bob expected, and he decides to close his short position. The platform calculates the market price of the bonds he shorted using the flat + curve pricing model, which takes into account the remaining time until maturity, the new market fixed rate, and the accrued interest so far. 6. If the new market fixed rate is higher than the initial fixed rate, the bonds' market price will be lower than the initial short sale price, as the remaining fixed interest payments are now less valuable. Bob can buy back the bonds at this lower price to close his short position and keep the difference, plus the variable interest he accrued ($15 in this case). 7. If the new market fixed rate is lower than the initial fixed rate, the bonds' market price will be higher than the initial short sale price, as the remaining fixed interest payments are now more valuable. In this case, Bob would lose money if he decides to close his short position, as he would need to buy back the bonds at a higher price. In this example, Bob is effectively betting that interest rates will increase during the first half of the term. If he's right, he'll make a profit, but if he's wrong, he'll lose money. Note that he's exposed to changes in the market fixed rate since he's closing his short position before the bonds reach maturity. ### Pricing Since long and short positions are just different ways of accounting for bond purchases and sales, Hyperdrive only needs to price bonds to facilitate trading. Hyperdrive's pricing model differs from a normal AMM in several ways. First, Hyperdrive makes use of a new AMM invariant called Flat+Curve that executes trades as multiple operations on a lower-level AMM invariant. Second, Hyperdrive's AMM reserves don't perfectly correspond to the assets that are actually held in the pool. In fact, the bond reserves are entirely virtual asset that don't need to be provided by liquidity providers when they add liquidity. ### Flat+Curve Element v1 used a variant of [YieldSpace](https://yield.is/YieldSpace.pdf) to price bonds. YieldSpace holds reserves of base (or shares in the case of [YieldSpace with Yield Bearing Vaults](/lRZ4mgdrRgOpxZQXqKYlFw)) and bonds of a specific maturity. The bond reserves reflect the contract's balance of bonds that have been previously minted and are maturing as they sit in the pool. At a specific point in time, YieldSpace is pricing bonds that have partially-matured over a specific amount of time. The interactive plot below demonstrates how as t matures from 1 to 0, the YieldSpace invariant goes from behaving like the Constant Product to the Constant Sum invariant. In other words, by the time t = 0, the bond has fully matured 1:1 with the base asset. <iframe src="https://www.desmos.com/calculator/wdj1kujgqg?embed" width="650px" height="500px" style="border: 1px solid #ccc" frameborder=0></iframe> Unfortunately, this approach of pricing bonds isn't secure for our use-case because Hyperdrive supports sales and purchases of bonds of many different maturities from a single liquidity pool. To understand the motivation behind Flat + Curve, it is important to understand how YieldSpace could be exploited if we allowed multiple maturities to be traded on it. Using YieldSpace with many maturities is vunerable to sandwich attacks. This vulnerability can be executed by monitoring the mempool until a large redemption is found. The attacker can then sandwich the redemption between an open/close short in order to profit. The vulnerability is demonstrated with the following trades: 1) alice purchase bonds at t=1 (red) 2) time passes and alice's bonds mature 3) bob opens a short at t=1 (orange) 4) alice redeems her matured bonds at t=0 (blue). 5) bob closes his short t=1 (green). ![](https://hackmd.io/_uploads/SJHOhwu43.png) The sandwich attack results in a loss of $\frac{.761}{5}\approx15.22\%$ of the base reserves. This attack works because closing the matured long will have no impact on the price of the matured bond, but it puts a large amount of downward pressure on the price of newly minted bonds. This is a problem because the attacker knows the price of newly minted bonds is about to drop and can open a well timed short to profit from it. It is important to note that this is a well known class of vulnerabilities that was first discussed in the context of Curve's StableSwap. [Peter Zeitz's report on the exploit](https://medium.com/@peter_4205/curve-vulnerability-report-a1d7630140ec) provides an intuitive geometric framing of thinking about the issue of allowing trades on multiple AMM invariants simulataneously. To mitigate this issue, Hyperdrive uses a new AMM invariant that we refer to as "Flat+Curve." The intuition behind Flat+Curve is that we can safely support trading of bonds with different maturities by thinking about a partially matured bond as a portion of newly minted bonds and a portion of fully matured bonds. With YieldSpace, we can think of all purchased bonds maturing simulaneously: ![](https://hackmd.io/_uploads/r1T3iPu43.png) With Flat+Curve we think of the bonds maturing sequentially: ![](https://hackmd.io/_uploads/B1CcsvOE2.png) This allows us to price the matured portion of bonds as if they are being redeemed, whereas the new bonds are priced on the YieldSpace invariant at t=1. We consider the new bonds portion to be the "curve" part of the trade and the matured bonds portion to be the "flat" part of the trade. Flat+Curve is agnostic to the AMM invariant that is used. Since an AMM invariant must ensure that trading and adding or removing liquidity cannot be used to extract arbitrage from the pool in a single transaction, we first apply the "curve" part of the trade as a trade on the pool, and then we apply the "flat" part of the trade as an add or remove liquidity operation. ### Reserves Just like [YieldSpace with Yield Bearing Vaults](/lRZ4mgdrRgOpxZQXqKYlFw), Hyperdrive's AMM reserves consist of share reserves and bond reserves. As longs and shorts are opened and closed, the Flat+Curve pricing model will price the output of trades by increasing or decreasing one of the reserves and solving for the other -- just like any other AMM invariant. Hyperdrive's reserves are an abstract representation of the assets that are held in the system and don't perfectly correlate to real-world assets. The "share" in share reserves refers to a share of Hyperdrive's total investment into the yield source. As the base that was invested into the yield source accrues interest, the share reserves stay the same, but the price of shares increases. This is very similar to the way that Yearn and ERC4626 vaults account for interest accruing on the pool's assets. When trades occur and LPs remove liquidity from the pool, we ensure that the remaining share reserves are sufficient to cover all of the outstanding long positions at maturity. The bond reserves aren't actually backed by real bonds. They merely represent the amount of bonds that could be minted by the AMM. Furthermore, since Flat+Curve decomposes trades of partially-matured bonds into a trade and an add or remove liquidity action on the underlying invariant, updates to the bond reserves may not exactly reflect the inflows and outflows of bonds from the trader's perspective. Despite the fact that making reserves virtual is initially unintuitive, it is the key of Hyperdrive's ability to mint bonds on demand. ## Liquidity Providers Hyperdrive LPs act as the counterparty for every trade. When a user opens a long position, the LPs take on an equal-sized short position, and vice versa. Like Uniswap and Curve LPs, Hyperdrive LPs collect fees on every trade and own a portion of the pool proportional to their LP shares. Unlike Uniswap and Curve LPs, Hyperdrive LPs cannot fully withdraw their capital at any given time because they are the counterparty to open long and short positions that they can't forcibly close. The fact that Hyperdrive LPs have unrealized profit and loss on open trades complicates the process of adding and removing liquidity safely and fairly. In order to ensure that these operations are safe and fair, we attempt to maintain the ratio between the pool's "present value" and the total supply of LP shares. We calculate present value by simulating the closing of all outstanding trades. Unfortunately, our AMM invariant is path dependent, so this calculation will always be an approximation of the real present value; however, it is a useful approximation that should be hard to manipulate. ### Adding Liquidity Adding liquidity to Hyperdrive has a similar interface to a conventional AMM that supports single-sided liquidity provision. The LP provides base and receives LP shares that represent their share of the pool. We preserve the ratio of the present value to the total supply of LP shares ($\tfrac{PV_0}{l_0} = \tfrac{PV_1}{l_1}$) by solving the present value equation as $\tfrac{PV_0}{l_0} = \tfrac{PV_1}{l_0 + dl} \implies dl = (\tfrac{PV_1}{PV_0} - 1) \cdot l_0$, where $dl$ is the change in LP shares. Since adding liquidity to the pool decreases the slippage that traders would pay when closing their positions, a naive solution would cause new LPs to expose old LPs to unrealized losses. Using the preservation of present value formula, we attribute all of these losses to the new LP. This results in the new LPs instantaneously taking on unrealized losses. ### Removing Liquidity Hyperdrive LPs can remove their portion of the pool's liquidity by burning their LP tokens; however, the tokens they get back are different than what would be received when removing liquidity from a normal AMM. Since some of the capital controlled by Hyperdrive LPs is used to back outstanding positions, LPs can't instantaneously withdraw all of the capital that they control. If we decided to only give LPs the amount of capital that could be instantaneously withdrawn, it would be possible for traders to open long and short positions to result in the LP receiving a minimal payout. With this in mind, we need to have a mechanism in place that gives LPs that withdraw a claim on their capital that underlies positions. When LPs withdraw, they receive two assets: their portion of the AMMs idle capital and IOUs that represent their claim to a portion of proceeds generated from closing positions. These IOUs are called withdrawal shares and are pegged 1:1 with active LP shares. To compute the amount of withdrawal shares owed to the withdrawing LP, we solve the preservation of the present value per LP share as $\tfrac{PV_0}{l_0} = \tfrac{PV_1}{l_0 - dl + dw} \implies dw = \tfrac{PV_1}{PV_0} \cdot l_0 - (l_0 - dl)$, where $dw$ is the change in withdrawal shares. If the withdrawal shares amount is negative, we backtrack by again using the present value per LP share to calculate how much the proportional amount of idle would be overpaying. ### Redeeming Withdrawal Shares Since LPs take on long positions when shorts are opened and short positions when longs are opened, it's straightforward to calculate the proceeds of every trade that is closed. Outstanding withdrawal shares have priority when the proceeds are paid out to the withdrawal pool and the active LP pool. We use the present value per LP share quantity to calculate the amount of withdrawal shares can be burned, which ensures that withdrawal shares and LP shares continue to be pegged 1:1. The proceeds that are directed to the withdrawal pool are redeemed on a first come, first served fashion. When withdrawal share redemptions are processed, withdrawal pool proceeds are paid out proportionally to the amount of withdrawal shares that are ready for withdrawal.