Struct State

Source
pub struct State {
    pub config: PoolConfig,
    pub info: PoolInfo,
}

Fields§

§config: PoolConfig§info: PoolInfo

Implementations§

Source§

impl State

Source

pub fn calculate_idle_share_reserves(&self) -> FixedPoint<U256>

Calculates the number of share reserves that are not reserved by open positions.

Source

pub fn calculate_solvency(&self) -> Result<FixedPoint<U256>>

Calculates the pool’s solvency.

s = z - \tfrac{\text{exposure}}{c} - z_{\text{min}}
Source

pub fn calculate_idle_share_reserves_in_base(&self) -> FixedPoint<U256>

Calculates the number of base reserves that are not reserved by open positions.

Source

pub fn calculate_scaled_normalized_time_remaining( &self, scaled_maturity_time: FixedPoint<U256>, current_time: U256, ) -> FixedPoint<U256>

Given a scaled FixedPoint maturity time, calculate the normalized time remaining with high precision.

Source§

impl State

Source

pub fn calculate_close_long<F: Into<FixedPoint<U256>>>( &self, bond_amount: F, maturity_time: U256, current_time: U256, ) -> Result<FixedPoint<U256>>

Calculates the amount of shares the trader will receive after fees for closing a long

Source

pub fn calculate_market_value_long<F: Into<FixedPoint<U256>>>( &self, bond_amount: F, maturity_time: U256, current_time: U256, ) -> Result<FixedPoint<U256>>

Calculates the amount of shares the trader will receive after fees for closing a long assuming no slippage, market impact, or liquidity constraints. This is the spot valuation.

To get this value, we use the same calculations as calculate_close_long, except for the curve part of the trade, where we replace calculate_shares_out_given_bonds_in for the following:

$\text{curve} = \tfrac{\Delta y}{c} \cdot p \cdot t$

$\Delta y = \text{bond_amount}$ $c = \text{close_vault_share_price (current if non-matured)}$

Source§

impl State

Source

pub fn open_long_curve_fee( &self, base_amount: FixedPoint<U256>, ) -> Result<FixedPoint<U256>>

Calculates the curve fee paid when opening longs with a given base amount.

The open long curve fee, $\Phi_{c,ol}(\Delta x)$, is paid in bonds and is given by:

\Phi_{c,ol}(\Delta x) = \phi_c
\cdot \left( \tfrac{1}{p} - 1 \right) \cdot \Delta x
Source

pub fn open_long_governance_fee( &self, base_amount: FixedPoint<U256>, maybe_curve_fee: Option<FixedPoint<U256>>, ) -> Result<FixedPoint<U256>>

Calculates the governance fee paid when opening longs with a given base amount.

The open long governance fee, $\Phi_{g,ol}(\Delta x)$, is paid in base and is given by:

\Phi_{g,ol}(\Delta x) = \phi_g \cdot p \cdot \Phi_{c,ol}(\Delta x)
Source

pub fn close_long_curve_fee( &self, bond_amount: FixedPoint<U256>, maturity_time: U256, current_time: U256, ) -> Result<FixedPoint<U256>>

Calculates the curve fee paid when closing longs for a given bond amount.

The the close long curve fee, $\Phi_{c,cl}(\Delta y)$, is paid in shares and is given by:

\Phi_{c,cl}(\Delta y) =
\frac{\phi_c \cdot (1 - p) \cdot \Delta y \cdot t}{c}

where $t$ is the normalized time remaining until bond maturity.

Source

pub fn close_long_flat_fee( &self, bond_amount: FixedPoint<U256>, maturity_time: U256, current_time: U256, ) -> FixedPoint<U256>

Calculates the flat fee paid when closing longs for a given bond amount.

The close long flat fee, $\Phi_{f,cl}(\Delta y)$, is paid in shares and is given by:

\Phi_{f,cl}(\Delta y) = \frac{\Delta y \cdot (1 - t) \cdot \phi_f)}{c}

where $t$ is the normalized time remaining until bond maturity.

Source§

impl State

Source

pub fn calculate_max_spot_price(&self) -> Result<FixedPoint<U256>>

Calculates the pool’s max spot price.

Hyperdrive has assertions to ensure that traders don’t purchase bonds at negative interest rates. The maximum spot price that longs can push the market to is given by:

p_{\text{max}} = \frac{1 - \phi_f}{1 + \phi_c \cdot
\left( p_0^{-1} - 1 \right) \cdot \left( \phi_f - 1 \right)}
Source

pub fn calculate_max_long<F: Into<FixedPoint<U256>>, I: Into<I256>>( &self, budget: F, checkpoint_exposure: I, maybe_max_iterations: Option<usize>, ) -> Result<FixedPoint<U256>>

Calculates the max long that can be opened given a budget.

We start by calculating the long that brings the pool’s spot price to 1. If we are solvent at this point, then we’re done. Otherwise, we approach the max long iteratively using Newton’s method.

Source§

impl State

Source

pub fn calculate_open_long<F: Into<FixedPoint<U256>>>( &self, base_amount: F, ) -> Result<FixedPoint<U256>>

Calculates the long amount that will be opened for a given base amount.

The long amount $y(x)$ that a trader will receive is given by:

y(x) = y_{*}(x) - c(x)

Where $y_{*}(x)$ is the amount of long that would be opened if there was no curve fee and $c(x)$ is the curve fee. $y_{*}(x)$ is given by:

y_{*}(x) = y - \left(
               k - \tfrac{c}{\mu} \cdot \left(
                   \mu \cdot \left( z + \tfrac{x}{c}
               \right) \right)^{1 - t_s}
           \right)^{\tfrac{1}{1 - t_s}}
Source

pub fn calculate_pool_state_after_open_long( &self, base_amount: FixedPoint<U256>, maybe_bond_delta: Option<FixedPoint<U256>>, ) -> Result<Self>

Calculate an updated pool state after opening a long.

For a given base delta and bond delta, the base delta is converted to shares and the reserves are updated such that state.bond_reserves -= bond_delta and state.share_reserves += base_delta / vault_share_price.

Source

pub fn calculate_pool_deltas_after_open_long( &self, base_amount: FixedPoint<U256>, maybe_bond_delta: Option<FixedPoint<U256>>, ) -> Result<(FixedPoint<U256>, FixedPoint<U256>)>

Calculate the share and bond deltas to be applied to the pool after opening a long.

Source

pub fn calculate_spot_price_after_long( &self, base_amount: FixedPoint<U256>, maybe_bond_pool_delta: Option<FixedPoint<U256>>, ) -> Result<FixedPoint<U256>>

Calculates the spot price after opening a Hyperdrive long. If a bond_amount is not provided, then one is estimated using calculate_open_long.

Source

pub fn calculate_spot_rate_after_long( &self, base_amount: FixedPoint<U256>, maybe_bond_amount: Option<FixedPoint<U256>>, ) -> Result<FixedPoint<U256>>

Calculate the spot rate after a long has been opened. If a bond_amount is not provided, then one is estimated using calculate_open_long.

We calculate the rate for a fixed length of time as:

r(\Delta y) = \frac{1 - p(\Delta y)}{p(\Delta y) t}

where $p(x)$ is the spot price after a long for delta_base $= x$ and $t$ is the normalized position druation.

In this case, we use the resulting spot price after a hypothetical long for base_amount is opened.

Source§

impl State

Source

pub fn calculate_targeted_long_with_budget<F1: Into<FixedPoint<U256>>, F2: Into<FixedPoint<U256>>, F3: Into<FixedPoint<U256>>, I: Into<I256>>( &self, budget: F1, target_rate: F2, checkpoint_exposure: I, maybe_max_iterations: Option<usize>, maybe_allowable_error: Option<F3>, ) -> Result<FixedPoint<U256>>

Gets a target long that can be opened given a budget to achieve a desired fixed rate.

If the long amount to reach the target is greater than the budget, the budget is returned. If the long amount to reach the target is invalid (i.e. it would produce an insolvent pool), then an error is thrown, and the user is advised to use calculate_max_long.

Source§

impl State

Source

pub fn calculate_add_liquidity( &self, current_block_timestamp: U256, contribution: FixedPoint<U256>, min_lp_share_price: FixedPoint<U256>, min_apr: FixedPoint<U256>, max_apr: FixedPoint<U256>, as_base: bool, ) -> Result<FixedPoint<U256>>

Calculates the LP shares for a given contribution when adding liquidity.

Source

pub fn calculate_pool_state_after_add_liquidity( &self, contribution: FixedPoint<U256>, as_base: bool, ) -> Result<State>

Source

pub fn calculate_pool_deltas_after_add_liquidity( &self, contribution: FixedPoint<U256>, as_base: bool, ) -> Result<(FixedPoint<U256>, I256, FixedPoint<U256>)>

Source§

impl State

Source

pub fn calculate_initial_reserves( &self, share_amount: FixedPoint<U256>, target_apr: FixedPoint<U256>, ) -> Result<(FixedPoint<U256>, I256, FixedPoint<U256>)>

Calculates the initial reserves. We solve for the initial reserves by solving the following equations simultaneously:

(1) $c \cdot z = c \cdot z_e + p_{\text{target}} \cdot y$

(2) $p_{\text{target}} = \left(\tfrac{\mu \cdot z_e}{y}\right)^{t_s}$

where $p_{\text{target}}$ is the target spot price implied by the target spot rate.

Source

pub fn calculate_update_liquidity( &self, share_reserves: FixedPoint<U256>, share_adjustment: I256, bond_reserves: FixedPoint<U256>, minimum_share_reserves: FixedPoint<U256>, share_reserves_delta: I256, ) -> Result<(FixedPoint<U256>, I256, FixedPoint<U256>)>

Calculates the resulting share_reserves, share_adjustment, and bond_reserves when updating liquidity with a share_reserves_delta.

Source

pub fn calculate_present_value( &self, current_block_timestamp: U256, ) -> Result<FixedPoint<U256>>

Calculates the present value in shares of LP’s capital in the pool.

Source

pub fn calculate_net_curve_trade( &self, long_average_time_remaining: FixedPoint<U256>, short_average_time_remaining: FixedPoint<U256>, ) -> Result<I256>

Source

pub fn calculate_net_flat_trade( &self, long_average_time_remaining: FixedPoint<U256>, short_average_time_remaining: FixedPoint<U256>, ) -> Result<I256>

Calculates the result of closing the net flat position.

Source

pub fn calculate_distribute_excess_idle( &self, current_block_timestamp: U256, active_lp_total_supply: FixedPoint<U256>, withdrawal_shares_total_supply: FixedPoint<U256>, max_iterations: u64, ) -> Result<(FixedPoint<U256>, FixedPoint<U256>)>

Calculates the amount of withdrawal shares that can be redeemed and the share proceeds the withdrawal pool should receive given the pool’s current idle liquidity. We use the following algorithm to ensure that the withdrawal pool receives the correct amount of shares to (1) preserve the LP share price and (2) pay out as much of the idle liquidity as possible to the withdrawal pool:

  1. If $y_s \cdot t_s <= y_l \cdot t_l$ or $y_{\text{max\_out}}(I) >= y_s \cdot t_s - y_l \cdot t_l$ , set $dz_{\text{max}} = I$ and proceed to step (3). Otherwise, proceed to step (2).
  2. Solve $y_{\text{max\_out}}(dz_{\text{max}}) = y_s \cdot t_s - y_l \cdot t_l$ for $dz_{\text{max}}$ using Newton’s method.
  3. Set $dw = (1 - \tfrac{PV(dz_{\text{max}})}{PV(0)}) \cdot l$. If $dw <= w$, then proceed to step (5). Otherwise, set $dw = w$ and continue to step (4).
  4. Solve $\tfrac{PV(0)}{l} = \tfrac{PV(dz)}{(l - dw)}$ for $dz$ using Newton’s method if $y_l \cdot t_l ~= y_s \cdot t_s$ or directly otherwise.
  5. Return $dw$ and $dz$.

Returns (withdrawal_shares_redeemed, share_proceeds, success)

Source§

impl State

Source

pub fn calculate_remove_liquidity( &self, current_block_timestamp: U256, active_lp_total_supply: FixedPoint<U256>, withdrawal_shares_total_supply: FixedPoint<U256>, lp_shares: FixedPoint<U256>, total_vault_shares: FixedPoint<U256>, total_vault_assets: FixedPoint<U256>, min_output_per_share: FixedPoint<U256>, minimum_transaction_amount: FixedPoint<U256>, as_base: bool, ) -> Result<(FixedPoint<U256>, FixedPoint<U256>, State)>

Allows an LP to burn shares and withdraw from the pool.

Source

pub fn redeem_withddrawal_shares( &self, current_block_timestamp: U256, active_lp_total_supply: FixedPoint<U256>, withdrawal_shares_total_supply: FixedPoint<U256>, withdrawal_shares: FixedPoint<U256>, total_supply: FixedPoint<U256>, total_assets: FixedPoint<U256>, min_output_per_share: FixedPoint<U256>, as_base: bool, ) -> Result<(FixedPoint<U256>, FixedPoint<U256>, State)>

Redeems withdrawal shares by giving the LP a pro-rata amount of the withdrawal pool’s proceeds. This function redeems the maximum amount of the specified withdrawal shares given the amount of withdrawal shares ready to withdraw.

Source§

impl State

Source

pub fn calculate_net_curve_trade_from_timestamp( &self, current_block_timestamp: U256, ) -> Result<I256>

Source

pub fn calculate_net_flat_trade_from_timestamp( &self, current_block_timestamp: U256, ) -> Result<I256>

Calculates the result of closing the net flat position.

Source

pub fn get_state_after_liquidity_update( &self, share_reserves_delta: I256, ) -> Result<State>

Gets the resulting state when updating liquidity.

Source§

impl State

Source

pub fn calculate_short_proceeds_up( &self, bond_amount: FixedPoint<U256>, share_amount: FixedPoint<U256>, open_vault_share_price: FixedPoint<U256>, close_vault_share_price: FixedPoint<U256>, ) -> FixedPoint<U256>

Calculates the proceeds in shares of closing a short position. This takes into account the trading profits, the interest that was earned by the short, the flat fee the short pays, and the amount of margin that was released by closing the short. The adjusted value in shares that underlies the bonds is given by:

P_{\text{adj}} = \left( \frac{c1}{c_0 \cdot c} + \phi_f \right)
\cdot \frac{\Delta y}{c}

and the short proceeds are given by:

\text{proceeds} =
\begin{cases}
    P_\text{adj} - dz,
      & \text{if } P_{\text{adj}} > dz \\
    0,              & \text{otherwise}
\end{cases}

where $dz$ is the pool share adjustment. In the event that the interest is negative and outweighs the trading profits and margin released, the short’s proceeds are marked to zero.

Source

pub fn calculate_close_short<F: Into<FixedPoint<U256>>>( &self, bond_amount: F, open_vault_share_price: F, close_vault_share_price: F, maturity_time: U256, current_time: U256, ) -> Result<FixedPoint<U256>>

Calculates the amount of shares the trader will receive after fees for closing a short

Source

pub fn calculate_market_value_short<F: Into<FixedPoint<U256>>>( &self, bond_amount: F, open_vault_share_price: F, close_vault_share_price: F, maturity_time: U256, current_time: U256, ) -> Result<FixedPoint<U256>>

Calculates the amount of shares the trader will receive after fees for closing a short assuming no slippage, market impact, or liquidity constraints. This is the spot valuation.

To get this value, we use the same calculations as calculate_close_short, except for the curve part of the trade, where we replace calculate_shares_in_given_bonds_out for the following:

$\text{curve} = \tfrac{\Delta y}{c} \cdot p \cdot t$

$\Delta y = \text{bond_amount}$ $c = \text{close_vault_share_price (current if non-matured)}$

Source§

impl State

Source

pub fn open_short_curve_fee( &self, bond_amount: FixedPoint<U256>, ) -> Result<FixedPoint<U256>>

Calculates the curve fee paid when opening shorts with a given bond amount.

The open short curve fee, $\Phi_{c,os}(\Delta y)$, is paid in base and is given by:

\Phi_{c,os}(\Delta y) = \phi_c \cdot (1 - p) \cdot \Delta y
Source

pub fn open_short_governance_fee( &self, bond_amount: FixedPoint<U256>, maybe_curve_fee: Option<FixedPoint<U256>>, ) -> Result<FixedPoint<U256>>

Calculates the governance fee paid when opening shorts with a given bond amount.

The open short governance fee, $\Phi_{g,os}(\Delta y)$, is paid in base and is given by:

\Phi_{g,os}(\Delta y) = \phi_g \cdot \Phi_{c,os}(\Delta y)
Source

pub fn close_short_curve_fee( &self, bond_amount: FixedPoint<U256>, maturity_time: U256, current_time: U256, ) -> Result<FixedPoint<U256>>

Calculates the curve fee paid when opening shorts with a given bond amount.

The close short curve fee, $\Phi_{c,cs}(\Delta y)$, is paid in shares and is given by:

\Phi_{c,cs}(\Delta y) = \frac{\phi_c \cdot (1-p) \cdot \Delta y \cdot t}{c}

where $t$ is the normalized time remaining until bond maturity.

Source

pub fn close_short_governance_fee( &self, bond_amount: FixedPoint<U256>, maturity_time: U256, current_time: U256, maybe_curve_fee: Option<FixedPoint<U256>>, ) -> Result<FixedPoint<U256>>

Calculate the governance fee paid when closing shorts with a given bond amount.

The close short governance fee, $\Phi_{g,cs}(\Delta y)$, is paid in shares and is given by:

\Phi_{g,cs}(\Delta y) = \Phi_{c,cs}(\Delta y) * \phi_g

NOTE: Round down to underestimate the governance curve fee

Source

pub fn close_short_flat_fee( &self, bond_amount: FixedPoint<U256>, maturity_time: U256, current_time: U256, ) -> FixedPoint<U256>

Calculate the flat fee paid when closing shorts with a given bond amount.

The close short flat fee, $\Phi_{f,cs}(\Delta y)$, is paid in shares and is given by:

\Phi_{f,cs}(\Delta y) = \frac{\Delta y \cdot (1 - t) \cdot \phi_f}{c}

where $t$ is the normalized time remaining until bond maturity.

Source§

impl State

Source

pub fn calculate_min_spot_price(&self) -> Result<FixedPoint<U256>>

Calculates the minimum price that the pool can support.

YieldSpace intersects the y-axis with a finite slope, so there is a minimum price that the pool can support. This is the price at which the share reserves are equal to the minimum share reserves.

We can solve for the bond reserves $y_{\text{max}}$ implied by the share reserves being equal to $z_{\text{min}}$ using the current k value:

k = \tfrac{c}{\mu} \cdot \left( \mu \cdot z_{min} \right)^{1 - t_s}
+ y_{max}^{1 - t_s} \\
\implies \\
y_{max} = \left( k - \tfrac{c}{\mu} \cdot \left(
\mu \cdot z_{min} \right)^{1 - t_s} \right)^{\tfrac{1}{1 - t_s}}

From there, we can calculate the spot price as normal as:

p = \left( \tfrac{\mu \cdot z_{min}}{y_{max}} \right)^{t_s}
Source

pub fn calculate_short_bonds_given_deposit( &self, target_base_amount: FixedPoint<U256>, open_vault_share_price: FixedPoint<U256>, absolute_max_bond_amount: FixedPoint<U256>, maybe_tolerance: Option<FixedPoint<U256>>, maybe_max_iterations: Option<usize>, ) -> Result<FixedPoint<U256>>

Use Newton’s method with rate reduction to find the amount of bonds shorted for a given base deposit amount.

Source

pub fn calculate_max_short<F1: Into<FixedPoint<U256>>, F2: Into<FixedPoint<U256>>, I: Into<I256>>( &self, budget: F1, open_vault_share_price: F2, checkpoint_exposure: I, maybe_conservative_price: Option<FixedPoint<U256>>, maybe_max_iterations: Option<usize>, ) -> Result<FixedPoint<U256>>

Calculates the max short that can be opened with the given budget.

We start by finding the largest possible short (irrespective of budget), and then we iteratively approach a solution using Newton’s method if the budget isn’t satisified.

The user can provide maybe_conservative_price, which is a lower bound on the realized price that the short will pay. This is used to help the algorithm converge faster in real world situations. If this is None, then we’ll use the theoretical worst case realized price.

Source

pub fn calculate_absolute_max_short( &self, spot_price: FixedPoint<U256>, checkpoint_exposure: I256, maybe_max_iterations: Option<usize>, ) -> Result<FixedPoint<U256>>

Calculates the absolute max short that can be opened without violating the pool’s solvency constraints.

Source§

impl State

Source

pub fn calculate_open_short( &self, bond_amount: FixedPoint<U256>, open_vault_share_price: FixedPoint<U256>, ) -> Result<FixedPoint<U256>>

Calculates the amount of base the trader will need to deposit for a short of a given size.

For some number of bonds being shorted, $\Delta y$, the short deposit, $D(\Delta y)$, is made up of several components:

  • The short principal: $P_{\text{lp}}(\Delta y)$
  • The curve fee: $\Phi_{c,os}(\Delta y) = \phi_{c} \cdot ( 1 - p_{0} ) \cdot \Delta y$
  • The governance-curve fee: $\Phi_{g,os}(\Delta y) = \phi_{g} \Phi_{c,os}(\Delta y)$
  • The flat fee: $\Phi_{f,os}(\Delta y) = \tfrac{1}{c} ( \Delta y \cdot (1 - t) \cdot \phi_{f} )$
  • The total value in shares that underlies the bonds: $\tfrac{c_1}{c_0 \cdot c} \Delta y$

The short principal is given by:

P_{\text{lp}}(\Delta y) = z - \tfrac{1}{\mu} \cdot (
    \tfrac{\mu}{c} \cdot (k - (y + \Delta y)^{1 - t_s})
)^{\tfrac{1}{1 - t_s}}

The adjusted value in shares that underlies the bonds is given by:

P_\text{adj} = \left( \frac{c_1}{c_0} + \phi_f \right) \cdot \frac{\Delta y}{c}

And finally the short deposit in base is:

D(\Delta y) =
\begin{cases}
    P_\text{adj} - P_{\text{lp}}(\Delta y) + \Phi_{c}(\Delta y),
      & \text{if } P_{\text{adj}} > P_{\text{lp}}(\Delta y) - \Phi_{c}(\Delta y) \\
    0, & \text{otherwise}
\end{cases}
Source

pub fn calculate_open_short_derivative( &self, bond_amount: FixedPoint<U256>, open_vault_share_price: FixedPoint<U256>, maybe_initial_spot_price: Option<FixedPoint<U256>>, ) -> Result<FixedPoint<U256>>

Calculates the derivative of the short deposit function with respect to the short amount.

This derivative allows us to use Newton’s method to approximate the maximum short that a trader can open. The share adjustment derivative is a constant:

P^{\prime}_{\text{adj}}(\Delta y)
= \tfrac{c_{1}}{c_{0} \cdot c} + \tfrac{\phi_{f}}{c}

The curve fee dervative is given by:

\Phi^{\prime}_{\text{c}}(\Delta y) = \phi_{c} \cdot (1 - p_0),

where $p_0$ is the opening (or initial) spot price. Using these and the short principal derivative, we can calculate the open short derivative:

D^{\prime}(\Delta y) =
\begin{cases}
   c \cdot \left(
     P^{\prime}_{\text{adj}}(\Delta y)
     - P^{\prime}_{\text{lp}}(\Delta y)
     + \Phi^{\prime}_{c,os}(\Delta y)
   \right),
   & \text{if }
     P_{\text{adj}} > P_{\text{lp}}(\Delta y) - \Phi_{c,os}(\Delta y) \\
   0, & \text{otherwise}
\end{cases}
Source

pub fn calculate_short_principal( &self, bond_amount: FixedPoint<U256>, ) -> Result<FixedPoint<U256>>

Calculates the amount of short principal that the LPs need to pay to back a short before fees are taken into consideration, $P_\text{lp}(\Delta y)$.

Let the LP principal that backs $\Delta y$ shorts be given by $P_{\text{lp}}(\Delta y)$. We can solve for this in terms of $\Delta y$ using the YieldSpace invariant:

k = \tfrac{c}{\mu} \cdot (\mu \cdot (z - P(\Delta y)))^{1 - t_s} + (y + \Delta y)^{1 - t_s} \\
\implies \\
P_{\text{lp}}(\Delta y) = z - \tfrac{1}{\mu}
\cdot \left(
  \tfrac{\mu}{c} \cdot (k - (y + \Delta y)^{1 - t_s})
\right)^{\tfrac{1}{1 - t_s}}
Source

pub fn calculate_short_principal_derivative( &self, bond_amount: FixedPoint<U256>, ) -> Result<FixedPoint<U256>>

Calculates the derivative of the short principal w.r.t. the amount of bonds that are shorted.

The derivative is:

P^{\prime}_{\text{lp}}(\Delta y) = \tfrac{1}{c} \cdot (y + \Delta y)^{-t_s}
\cdot \left(
    \tfrac{\mu}{c} \cdot (k - (y + \Delta y)^{1 - t_s})
\right)^{\tfrac{t_s}{1 - t_s}}
Source

pub fn calculate_pool_state_after_open_short( &self, bond_amount: FixedPoint<U256>, maybe_share_amount: Option<FixedPoint<U256>>, ) -> Result<Self>

Calculate an updated pool state after opening a short.

For a given bond amount and share amount, the reserves are updated such that state.bond_reserves += bond_amount and state.share_reserves -= share_amount.

Source

pub fn calculate_pool_share_delta_after_open_short( &self, bond_amount: FixedPoint<U256>, ) -> Result<FixedPoint<U256>>

Calculate the share delta to be applied to the pool after opening a short.

Source

pub fn calculate_spot_price_after_short( &self, bond_amount: FixedPoint<U256>, maybe_base_amount: Option<FixedPoint<U256>>, ) -> Result<FixedPoint<U256>>

Calculates the spot price after opening a short. Arguments are deltas that would be applied to the pool.

Source

pub fn calculate_spot_rate_after_short( &self, bond_amount: FixedPoint<U256>, maybe_base_amount: Option<FixedPoint<U256>>, ) -> Result<FixedPoint<U256>>

Calculate the spot rate after a short has been opened. If a base_amount is not provided, then one is estimated using calculate_pool_share_delta_after_open_short.

We calculate the rate for a fixed length of time as:

r(\Delta y) = \frac{1 - p(\Delta y)}{p(\Delta y) \cdot t}

where $p(\Delta y)$ is the spot price after a short for delta_bonds $= \Delta y$ and $t$ is the normalized position druation.

Source

pub fn calculate_implied_rate( &self, bond_amount: FixedPoint<U256>, open_vault_share_price: FixedPoint<U256>, variable_apy: FixedPoint<U256>, ) -> Result<I256>

Calculate the implied rate of opening a short at a given size. This rate is calculated as an APY.

Given the effective fixed rate the short will pay $r_{\text{effective}}$ and the variable rate the short will receive $r_{\text{variable}}$, the short’s implied APY, $r_{\text{implied}}$ will be:

r_{\text{implied}} = \frac{r_{\text{variable}}
- r_{\text{effective}}}{r_{\text{effective}}}

We can short-cut this calculation using the amount of base the short will pay and comparing this to the amount of base the short will receive if the variable rate stays the same. The implied rate is just the ROI if the variable rate stays the same.

To do this, we must figure out the term-adjusted yield $TPY$ according to the position duration $t$. Since we start off from a compounded APY and also output a compounded TPY, the compounding frequency $f$ is simplified away. Thus, the adjusted yield will be:

\text{APR} = f \cdot (( 1 + \text{APY})^{\tfrac{1}{f}}  - 1)

Therefore,

\begin{aligned}
TPY &= (1 + \frac{APR}{f})^{d \cdot f} \\
&= (1 + APY)^{d} - 1
\end{aligned}

We use the TPY to figure out the base proceeds, and calculate the rate of return based on the short’s opening cost. Since shorts must backpay the variable interest accrued since the last checkpoint, we subtract that from the opening cost, as they get it back upon closing the short.

Source

pub fn calculate_approximate_short_bonds_given_base_deposit( &self, base_deposit: FixedPoint<U256>, open_vault_share_price: FixedPoint<U256>, ) -> Result<FixedPoint<U256>>

Estimate the bonds that would be shorted given a base deposit amount.

The LP principal in shares is bounded from below by $S(min)$, which is the output of calculating the short principal on the minimum transaction amount.

Given this, we can compute the a conservative estimate of the bonds shorted, $\Delta y$, given the trader’s base deposit amount, $c \cdot D(\Delta y)$:

A = \frac{c_1}{c_0} + \phi_f + \phi_c \cdot (1 - p) \\

D(\Delta y) = A \cdot \frac{\Delta y}{c} - S(\Delta y) \\

S(\text{min\_tx}) \le S(\Delta y) \\

\therefore \\

\Delta y(D) &\ge \frac{c}{A} \cdot \left( D + S(\text{min\_tx}) \right)

The resulting bond amount is guaranteed to cost a trader less than or equal to the provided base deposit amount.

Source§

impl State

Source

pub fn new(config: PoolConfig, info: PoolInfo) -> Self

Creates a new State from the given PoolConfig and PoolInfo.

Source

pub fn calculate_spot_price(&self) -> Result<FixedPoint<U256>>

Calculates the pool’s spot price.

Source

pub fn calculate_spot_rate(&self) -> Result<FixedPoint<U256>>

Calculate the pool’s current spot (aka “fixed”) rate.

Source

pub fn to_checkpoint(&self, time: U256) -> U256

Converts a timestamp to the checkpoint timestamp that it corresponds to.

Source

pub fn vault_share_price(&self) -> FixedPoint<U256>

Trait Implementations§

Source§

impl Clone for State

Source§

fn clone(&self) -> State

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for State

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Distribution<State> for Standard

Source§

fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> State

Generate a random value of T, using rng as the source of randomness.
Source§

fn sample_iter<R>(self, rng: R) -> DistIter<Self, R, T>
where R: Rng, Self: Sized,

Create an iterator that generates random values of T, using rng as the source of randomness. Read more
Source§

fn map<F, S>(self, func: F) -> DistMap<Self, F, T, S>
where F: Fn(T) -> S, Self: Sized,

Create a distribution of values of ‘S’ by mapping the output of Self through the closure F Read more
Source§

impl YieldSpace for State

Source§

fn z(&self) -> FixedPoint<U256>

The share reserves.
Source§

fn zeta(&self) -> I256

The share adjustment.
Source§

fn y(&self) -> FixedPoint<U256>

The bond reserves.
Source§

fn mu(&self) -> FixedPoint<U256>

The initial vault share price.
Source§

fn c(&self) -> FixedPoint<U256>

The share price.
Source§

fn t(&self) -> FixedPoint<U256>

The YieldSpace time parameter.
Source§

fn ze(&self) -> Result<FixedPoint<U256>>

The effective share reserves.
Source§

fn calculate_spot_price(&self) -> Result<FixedPoint<U256>>

Source§

fn calculate_bonds_out_given_shares_in_down( &self, dz: FixedPoint<U256>, ) -> Result<FixedPoint<U256>>

Calculates the amount of bonds a user will receive from the pool by providing a specified amount of shares. We underestimate the amount of bonds out to prevent sandwiches.
Source§

fn calculate_shares_in_given_bonds_out_up( &self, dy: FixedPoint<U256>, ) -> Result<FixedPoint<U256>>

Calculates the amount of shares a user must provide the pool to receive a specified amount of bonds. We overestimate the amount of shares in.
Source§

fn calculate_shares_in_given_bonds_out_down( &self, dy: FixedPoint<U256>, ) -> Result<FixedPoint<U256>>

Calculates the amount of shares a user must provide the pool to receive a specified amount of bonds. We underestimate the amount of shares in.
Source§

fn calculate_shares_out_given_bonds_in_down( &self, dy: FixedPoint<U256>, ) -> Result<FixedPoint<U256>>

Calculates the amount of shares a user will receive from the pool by providing a specified amount of bonds. This function reverts if an integer overflow or underflow occurs. We underestimate the amount of shares out.
Source§

fn calculate_max_buy_shares_in(&self) -> Result<FixedPoint<U256>>

Calculates the share payment required to purchase the maximum amount of bonds from the pool.
Source§

fn calculate_max_buy_bonds_out(&self) -> Result<FixedPoint<U256>>

Calculates the maximum amount of bonds that can be purchased with the specified reserves. We round so that the max buy amount is underestimated.
Source§

fn calculate_max_sell_bonds_in( &self, z_min: FixedPoint<U256>, ) -> Result<FixedPoint<U256>>

Calculates the maximum amount of bonds that can be sold with the specified reserves. We round so that the max sell amount is underestimated.
Source§

fn k_up(&self) -> Result<FixedPoint<U256>>

Calculates the YieldSpace invariant k. This invariant is given by: Read more
Source§

fn k_down(&self) -> Result<FixedPoint<U256>>

Calculates the YieldSpace invariant k. This invariant is given by: Read more

Auto Trait Implementations§

§

impl Freeze for State

§

impl RefUnwindSafe for State

§

impl Send for State

§

impl Sync for State

§

impl Unpin for State

§

impl UnwindSafe for State

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> Conv for T

Source§

fn conv<T>(self) -> T
where Self: Into<T>,

Converts self into T using Into<T>. Read more
Source§

impl<T> FmtForward for T

Source§

fn fmt_binary(self) -> FmtBinary<Self>
where Self: Binary,

Causes self to use its Binary implementation when Debug-formatted.
Source§

fn fmt_display(self) -> FmtDisplay<Self>
where Self: Display,

Causes self to use its Display implementation when Debug-formatted.
Source§

fn fmt_lower_exp(self) -> FmtLowerExp<Self>
where Self: LowerExp,

Causes self to use its LowerExp implementation when Debug-formatted.
Source§

fn fmt_lower_hex(self) -> FmtLowerHex<Self>
where Self: LowerHex,

Causes self to use its LowerHex implementation when Debug-formatted.
Source§

fn fmt_octal(self) -> FmtOctal<Self>
where Self: Octal,

Causes self to use its Octal implementation when Debug-formatted.
Source§

fn fmt_pointer(self) -> FmtPointer<Self>
where Self: Pointer,

Causes self to use its Pointer implementation when Debug-formatted.
Source§

fn fmt_upper_exp(self) -> FmtUpperExp<Self>
where Self: UpperExp,

Causes self to use its UpperExp implementation when Debug-formatted.
Source§

fn fmt_upper_hex(self) -> FmtUpperHex<Self>
where Self: UpperHex,

Causes self to use its UpperHex implementation when Debug-formatted.
Source§

fn fmt_list(self) -> FmtList<Self>
where &'a Self: for<'a> IntoIterator,

Formats each item in a sequence. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pipe for T
where T: ?Sized,

Source§

fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R
where Self: Sized,

Pipes by value. This is generally the method you want to use. Read more
Source§

fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> R
where R: 'a,

Borrows self and passes that borrow into the pipe function. Read more
Source§

fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> R
where R: 'a,

Mutably borrows self and passes that borrow into the pipe function. Read more
Source§

fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
where Self: Borrow<B>, B: 'a + ?Sized, R: 'a,

Borrows self, then passes self.borrow() into the pipe function. Read more
Source§

fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R, ) -> R
where Self: BorrowMut<B>, B: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.borrow_mut() into the pipe function. Read more
Source§

fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
where Self: AsRef<U>, U: 'a + ?Sized, R: 'a,

Borrows self, then passes self.as_ref() into the pipe function.
Source§

fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
where Self: AsMut<U>, U: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.as_mut() into the pipe function.
Source§

fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
where Self: Deref<Target = T>, T: 'a + ?Sized, R: 'a,

Borrows self, then passes self.deref() into the pipe function.
Source§

fn pipe_deref_mut<'a, T, R>( &'a mut self, func: impl FnOnce(&'a mut T) -> R, ) -> R
where Self: DerefMut<Target = T> + Deref, T: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.deref_mut() into the pipe function.
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> Tap for T

Source§

fn tap(self, func: impl FnOnce(&Self)) -> Self

Immutable access to a value. Read more
Source§

fn tap_mut(self, func: impl FnOnce(&mut Self)) -> Self

Mutable access to a value. Read more
Source§

fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
where Self: Borrow<B>, B: ?Sized,

Immutable access to the Borrow<B> of a value. Read more
Source§

fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
where Self: BorrowMut<B>, B: ?Sized,

Mutable access to the BorrowMut<B> of a value. Read more
Source§

fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
where Self: AsRef<R>, R: ?Sized,

Immutable access to the AsRef<R> view of a value. Read more
Source§

fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
where Self: AsMut<R>, R: ?Sized,

Mutable access to the AsMut<R> view of a value. Read more
Source§

fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
where Self: Deref<Target = T>, T: ?Sized,

Immutable access to the Deref::Target of a value. Read more
Source§

fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
where Self: DerefMut<Target = T> + Deref, T: ?Sized,

Mutable access to the Deref::Target of a value. Read more
Source§

fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self

Calls .tap() only in debug builds, and is erased in release builds.
Source§

fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self

Calls .tap_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
where Self: Borrow<B>, B: ?Sized,

Calls .tap_borrow() only in debug builds, and is erased in release builds.
Source§

fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
where Self: BorrowMut<B>, B: ?Sized,

Calls .tap_borrow_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
where Self: AsRef<R>, R: ?Sized,

Calls .tap_ref() only in debug builds, and is erased in release builds.
Source§

fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
where Self: AsMut<R>, R: ?Sized,

Calls .tap_ref_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
where Self: Deref<Target = T>, T: ?Sized,

Calls .tap_deref() only in debug builds, and is erased in release builds.
Source§

fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mut T)) -> Self
where Self: DerefMut<Target = T> + Deref, T: ?Sized,

Calls .tap_deref_mut() only in debug builds, and is erased in release builds.
Source§

impl<T> ToFixed for T
where T: Debug,

Source§

fn to_fixed<T>(self) -> FixedPoint<T>
where T: FixedPointValue + From<Self>,

Converts the value to a FixedPoint<T> instance, first converting the value to the underlying T type if necessary. Read more
Source§

fn try_to_fixed<T>(self) -> Result<FixedPoint<T>, Report>
where T: FixedPointValue + TryFrom<Self>,

Attempts to convert the value to a FixedPoint<T> instance, first converting the value to the underlying T type if necessary. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> TryConv for T

Source§

fn try_conv<T>(self) -> Result<T, Self::Error>
where Self: TryInto<T>,

Attempts to convert self into T using TryInto<T>. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> JsonSchemaMaybe for T