Verified contractPartial
LendController
Address0x2fb54c8eae57767a9a509a395b9c4fa0702e2675
- Balance
0 ETH
- Transactions
261
- Compiler
vyper 0.4.3
- Same code
1 more contract
Details
- Compiler
- vyper 0.4.3+commit.bff19ea2
- Language
- vyper
- EVM version
- cancun
- License
- Not stated
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,603,281
- Creation transaction
- 0x24fd3f6fd7…6ce74a6c78
17 files
- curve_stablecoin/lending/LendController.vymain6.88 KB
- curve_stablecoin/constants.vy942 B
- curve_stablecoin/controller.vy52.47 KB
- curve_stablecoin/interfaces/IAMM.vyi3.84 KB
- curve_stablecoin/interfaces/IConfigurator.vyi2.12 KB
- curve_stablecoin/interfaces/IController.vyi5.86 KB
- curve_stablecoin/interfaces/IControllerView.vyi1.44 KB
- curve_stablecoin/interfaces/IFactory.vyi168 B
- curve_stablecoin/interfaces/ILMCallback.vyi863 B
- curve_stablecoin/interfaces/ILendController.vyi624 B
- curve_stablecoin/interfaces/IMonetaryPolicy.vyi75 B
- curve_stablecoin/interfaces/IPriceOracle.vyi73 B
- curve_stablecoin/interfaces/IVault.vyi2.99 KB
- curve_std/crv_math.vy129 B
- curve_std/interfaces/IERC20.vyi922 B
- curve_std/token.vy643 B
- snekmate/utils/math.vy28.12 KB
curve_stablecoin/lending/LendController.vy
# pragma version 0.4.3
# pragma nonreentrancy on
# pragma optimize codesize
"""
@title LlamaLend Lend Market Controller
@author Curve.Fi
@license Copyright (c) Curve.Fi, 2020-2025 - all rights reserved
@notice Main contract to interact with a Llamalend Lend Market. Each
contract is specific to a single lending market.
@custom:security [email protected]
@custom:kill Set borrow_cap to 0 and vault's max_supply to 0 to prevent new deposits. Existing loans can still be repaid/liquidated.
"""
from curve_std.interfaces import IERC20
from curve_stablecoin.interfaces import IAMM
from curve_stablecoin.interfaces import IMonetaryPolicy
from curve_stablecoin.interfaces import IVault
from curve_stablecoin.interfaces import IController
from curve_std import crv_math
implements: IController
from curve_stablecoin.interfaces import ILendController
implements: ILendController
from curve_stablecoin import controller as core
from curve_stablecoin.interfaces import IControllerView as IView
implements: IView
implements: core.VirtualMethods
initializes: core
from curve_std import token as tkn
exports: (
# Constants
core.MAX_RATE,
# Loan management
core.create_loan,
core.borrow_more,
core.add_collateral,
core.approve,
core.remove_collateral,
core.repay,
core.set_extra_health,
core.liquidate,
core.save_rate,
core.collect_fees,
# Related contracts getters
core.amm,
core.view,
core.factory,
core.configurator,
# Getters
core.approval,
core.borrowed_token,
core.calculate_debt_n1,
core.collateral_token,
core.debt,
core.extra_health,
core.health,
core.create_loan_health_preview,
core.add_collateral_health_preview,
core.remove_collateral_health_preview,
core.borrow_more_health_preview,
core.repay_health_preview,
core.liquidate_health_preview,
core.liquidation_discount,
core.liquidation_discounts,
core.loan_discount,
core.loan_exists,
core.loan_ix,
core.loans,
core.monetary_policy,
core.n_loans,
core.tokens_to_liquidate,
core.tokens_to_shrink,
core.total_debt,
core.admin_fees,
core.admin_percentage,
# Setters
core.configure,
# From view contract
core.user_prices,
core.user_state,
core.users_to_liquidate,
core.min_collateral,
core.max_borrowable,
)
borrow_cap: public(uint256)
VAULT: immutable(IVault)
_available_balance: uint256
@external
@view
@reentrant
def available_balance() -> uint256:
return self._available_balance
# https://github.com/vyperlang/vyper/issues/4721
@external
@view
@reentrant
def vault() -> address:
"""
@notice Address of the vault
@return Address of the vault contract
"""
return VAULT.address
@deploy
def __init__(
_vault: IVault,
_amm: IAMM,
_borrowed_token: IERC20,
_collateral_token: IERC20,
_monetary_policy: IMonetaryPolicy,
_loan_discount: uint256,
_liquidation_discount: uint256,
_view_blueprint: address,
_configurator: core.IConfigurator,
):
"""
@notice Lend Controller constructor
@param _vault Address of the vault this controller belongs to
@param _amm AMM address (already deployed from blueprint)
@param _borrowed_token Token which is being borrowed
@param _collateral_token Token to use for collateral
@param _monetary_policy Address of monetary policy
@param _loan_discount Discount of the maximum loan size compare to get_x_down() value
@param _liquidation_discount Discount of the maximum loan size compare to
get_x_down() for "bad liquidation" purposes
@param _view_blueprint Address of the controller view blueprint
@param _configurator Address of the configurator contract
"""
VAULT = _vault
core.__init__(
_collateral_token,
_borrowed_token,
_monetary_policy,
_loan_discount,
_liquidation_discount,
_amm,
_view_blueprint,
_configurator,
)
# Borrow cap is zero by default in lend markets. The admin has to raise it
# after deployment to allow borrowing.
core.admin_percentage = 0
# Pre-approve the vault to transfer borrowed tokens out of the controller
tkn.max_approve(core.BORROWED_TOKEN, VAULT.address)
@external
@view
@reentrant
def version() -> String[10]:
"""
@notice Version of this controller
@return Version string of the form "<core_version>-lend"
"""
return concat(core.version, "-lend")
@external
def configure_lend(_borrow_cap: uint256, _admin_percentage: uint256):
assert msg.sender == core.CONFIGURATOR.address, "Only configurator"
if _borrow_cap != core.SKIP_CONFIG_UINT256:
self.borrow_cap = _borrow_cap
if _admin_percentage != core.SKIP_CONFIG_UINT256:
rate_mul: uint256 = staticcall core.AMM.get_rate_mul()
core._update_total_debt(0, rate_mul, False)
core.admin_percentage = _admin_percentage
@external
@reentrant
def on_borrowed_token_transfer_in(_amount: uint256):
"""
@notice Hook called by
1. The controller on repay/liquidate
2. The vault on deposit/mint
@param _amount Amount of borrowed tokens transferred in
"""
assert msg.sender == VAULT.address or msg.sender == self # dev: vault or controller only
self._available_balance += _amount
@external
@reentrant
def on_borrowed_token_transfer_out(_amount: uint256):
"""
@notice Hook called by
1. The controller on create_loan/borrow_more/collect_fees
2. The vault on withdraw/redeem
@param _amount Amount of borrowed tokens transferred out
"""
assert msg.sender == VAULT.address or msg.sender == self # dev: vault or controller only
# core._admin_fees() == 0 in case of collect_fees()
assert _amount <= crv_math.sub_or_zero(self._available_balance, core._admin_fees()), "Available balance exceeded"
self._available_balance -= _amount
@external
@reentrant
def _on_debt_increased(_total_debt: uint256):
"""
@notice Hook called when debt is increased
@param _total_debt New total debt after the increase
"""
assert msg.sender == self # dev: virtual method protection (controller only)
assert _total_debt <= self.borrow_cap, "Borrow cap exceeded"
@external
@view
def lent() -> uint256:
"""
@notice Total amount of borrowed tokens lent out since creation
@return Total lent amount
"""
return core.lent
@external
@view
def repaid() -> uint256:
"""
@notice Total amount of borrowed tokens repaid since creation
@return Total repaid amount
"""
return core.repaid
@external
@view
def collected() -> uint256:
"""
@notice Cumulative amount of borrowed assets ever collected as admin fees
@return Total collected admin fees
"""
return core.collected
curve_stablecoin/constants.vy
__version__: constant(String[5]) = "2.0.0"
MAX_TICKS: constant(int256) = 50
MAX_TICKS_UINT: constant(uint256) = 50
MIN_TICKS: constant(int256) = 4
MIN_TICKS_UINT: constant(uint256) = 4
MAX_SKIP_TICKS: constant(int256) = 1024
MAX_SKIP_TICKS_UINT: constant(uint256) = 1024
DEAD_SHARES: constant(uint256) = 1000
WAD: constant(uint256) = 10**18
SWAD: constant(int256) = 10**18
CALLDATA_MAX_SIZE: constant(uint256) = 32 * 300
# Sentinel values used in `configure` methods.
# We use an arbitrary high value that is unlikely to be used as a real value (can't use zero address as it might be intentional)
# keccak("SKIP_CONFIG") in decimal
SKIP_CONFIG_UINT256: constant(uint256) = 34683848501677104821777960696933802007602333377339998839659032476042327981902
# Last 20 bytes of keccak("SKIP_CONFIG_ADDRESS"), used as a nonzero sentinel for address config params
SKIP_CONFIG_ADDRESS: constant(address) = 0xEE97C47b4665063dD362c127B31a2d463BDFf91c
curve_stablecoin/controller.vy
# pragma version 0.4.3
# pragma nonreentrancy on
# pragma optimize codesize
from curve_stablecoin.interfaces import IAMM
from curve_stablecoin.interfaces import IMonetaryPolicy
from curve_stablecoin.interfaces import ILMCallback
from curve_stablecoin.interfaces import IFactory
from curve_stablecoin.interfaces import IPriceOracle
from curve_stablecoin.interfaces import IController
from curve_stablecoin.interfaces import IControllerView as IView
from curve_stablecoin.interfaces import IConfigurator
from curve_std.interfaces import IERC20
implements: IController
implements: IView
from curve_std import token as tkn
from curve_std import crv_math
from snekmate.utils import math
################################################################
# IMMUTABLES #
################################################################
AMM: immutable(IAMM)
A: immutable(uint256)
# log(A / (A - 1))
LOGN_A_RATIO: immutable(int256)
SQRT_BAND_RATIO: immutable(uint256)
COLLATERAL_TOKEN: immutable(IERC20)
COLLATERAL_PRECISION: immutable(uint256)
BORROWED_TOKEN: immutable(IERC20)
BORROWED_PRECISION: immutable(uint256)
FACTORY: immutable(IFactory)
CONFIGURATOR: immutable(IConfigurator)
################################################################
# CONSTANTS #
################################################################
from curve_stablecoin import constants as c
version: public(constant(String[5])) = c.__version__
# https://github.com/vyperlang/vyper/issues/4723
WAD: constant(uint256) = c.WAD
SWAD: constant(int256) = c.SWAD
DEAD_SHARES: constant(uint256) = c.DEAD_SHARES
MIN_TICKS_UINT: constant(uint256) = c.MIN_TICKS_UINT
MAX_TICKS_UINT: constant(uint256) = c.MAX_TICKS_UINT
MIN_TICKS: constant(int256) = c.MIN_TICKS
CALLDATA_MAX_SIZE: constant(uint256) = c.CALLDATA_MAX_SIZE
SKIP_CONFIG_UINT256: constant(uint256) = c.SKIP_CONFIG_UINT256
SKIP_CONFIG_ADDRESS: constant(address) = c.SKIP_CONFIG_ADDRESS
CALLBACK_DEPOSIT: constant(bytes4) = method_id(
"callback_deposit(address,uint256,uint256,uint256,bytes)",
output_type=bytes4,
) # active_band=0, borrowed=0
CALLBACK_REPAY: constant(bytes4) = method_id(
"callback_repay(address,uint256,uint256,uint256,bytes)", output_type=bytes4
)
CALLBACK_LIQUIDATE: constant(bytes4) = method_id(
"callback_liquidate(address,uint256,uint256,uint256,bytes)",
output_type=bytes4,
) # active_band=0
MAX_RATE: public(constant(uint256)) = 43959106799 # 300% APY
################################################################
# STORAGE #
################################################################
_view: IView
# avoiding circular imports by exposing the getter as address to make the compiler happy
@external
@view
@reentrant
def view() -> address:
return self._view.address
liquidation_discount: public(uint256)
loan_discount: public(reentrant(uint256))
_monetary_policy: IMonetaryPolicy
# https://github.com/vyperlang/vyper/issues/4721
@external
@view
@reentrant
def monetary_policy() -> IMonetaryPolicy:
"""
@notice Address of the monetary policy
@return Address of the monetary policy contract
"""
return self._monetary_policy
approval: public(HashMap[address, HashMap[address, bool]])
extra_health: public(reentrant(HashMap[address, uint256]))
loan: HashMap[address, IController.Loan]
liquidation_discounts: public(HashMap[address, uint256])
_total_debt: IController.Loan
# Enumerate existing loans
loans: public(address[2**64 - 1])
# Position of the loan in the list
loan_ix: public(HashMap[address, uint256])
# Number of nonzero loans
n_loans: public(uint256)
# cumulative amount of borrowed assets ever lent
lent: uint256
# cumulative amount of borrowed assets ever repaid
repaid: uint256
# cumulative amount of borrowed assets ever collected as admin fees
collected: uint256
# Admin fees yet to be collected. Goes to zero when collected.
_stored_admin_fees: uint256
admin_percentage: public(uint256)
# DANGER DO NOT RELY ON MSG.SENDER IN VIRTUAL METHODS
interface VirtualMethods:
def _on_debt_increased(_total_debt: uint256): nonpayable
def on_borrowed_token_transfer_in(_amount: uint256): nonpayable
def on_borrowed_token_transfer_out(_amount: uint256): nonpayable
implements: VirtualMethods
VIRTUAL: immutable(VirtualMethods)
@deploy
def __init__(
_collateral_token: IERC20,
_borrowed_token: IERC20,
_monetary_policy: IMonetaryPolicy,
_loan_discount: uint256,
_liquidation_discount: uint256,
_amm: IAMM,
_view_blueprint: address,
_configurator: IConfigurator,
):
VIRTUAL = VirtualMethods(self)
FACTORY = IFactory(msg.sender)
AMM = _amm
A = staticcall AMM.A()
LOGN_A_RATIO = math._wad_ln(convert(A * WAD // (A - 1), int256))
SQRT_BAND_RATIO = isqrt(10**36 * A // (A - 1))
COLLATERAL_TOKEN = _collateral_token
collateral_decimals: uint256 = convert(staticcall COLLATERAL_TOKEN.decimals(), uint256)
COLLATERAL_PRECISION = pow_mod256(10, 18 - collateral_decimals)
BORROWED_TOKEN = _borrowed_token
borrowed_decimals: uint256 = convert(staticcall BORROWED_TOKEN.decimals(), uint256)
BORROWED_PRECISION = pow_mod256(10, 18 - borrowed_decimals)
# This is useless for lending markets, but leaving it doesn't create any harm
tkn.max_approve(BORROWED_TOKEN, FACTORY.address)
CONFIGURATOR = _configurator
self._total_debt.rate_mul = WAD
self.admin_percentage = WAD
self._configure(
_loan_discount,
_liquidation_discount,
_monetary_policy,
_view_blueprint,
SKIP_CONFIG_UINT256,
IPriceOracle(SKIP_CONFIG_ADDRESS),
ILMCallback(SKIP_CONFIG_ADDRESS),
)
@external
@view
def minted() -> uint256:
return self.lent + self.collected
@external
@view
def redeemed() -> uint256:
return self.repaid
@external
@view
@reentrant
def available_balance() -> uint256:
return staticcall BORROWED_TOKEN.balanceOf(self)
@internal
@view
def _get_total_debt() -> uint256:
"""
@notice Total debt of this controller
@return Total outstanding debt with accrued interest
"""
rate_mul: uint256 = staticcall AMM.get_rate_mul()
loan: IController.Loan = self._total_debt
return loan.initial_debt * rate_mul // loan.rate_mul
@internal
@view
def _preview_total_debt(_rate_mul: uint256, _loan: IController.Loan) -> (uint256, uint256):
loan_with_interest: uint256 = _loan.initial_debt * _rate_mul // _loan.rate_mul
accrued_interest: uint256 = loan_with_interest - _loan.initial_debt
accrued_admin_fees: uint256 = accrued_interest * self.admin_percentage // WAD
return (loan_with_interest, accrued_admin_fees)
@internal
def _update_total_debt(_d_debt: uint256, _rate_mul: uint256, _is_increase: bool) -> IController.Loan:
"""
@notice Update total debt of this controller
@dev This method MUST be called strictly BEFORE lent, repaid or collected change
@param _d_debt Change in debt amount (unsigned)
@param _rate_mul New rate multiplier
@param _is_increase Whether debt increases or decreases
@return Updated loan struct with new initial_debt and rate_mul
"""
loan: IController.Loan = self._total_debt
loan_with_interest: uint256 = 0
accrued_admin_fees: uint256 = 0
loan_with_interest, accrued_admin_fees = self._preview_total_debt(
_rate_mul, loan
)
self._stored_admin_fees += accrued_admin_fees
loan.initial_debt = loan_with_interest
if _is_increase:
loan.initial_debt += _d_debt
else:
loan.initial_debt = crv_math.sub_or_zero(loan.initial_debt, _d_debt)
loan.rate_mul = _rate_mul
self._total_debt = loan
if _is_increase:
extcall VIRTUAL.on_borrowed_token_transfer_out(_d_debt)
extcall VIRTUAL._on_debt_increased(loan.initial_debt)
else:
extcall VIRTUAL.on_borrowed_token_transfer_in(_d_debt)
return loan
@external
@view
@reentrant
def factory() -> IFactory:
"""
@notice Address of the factory
@return Address of the factory contract
"""
return FACTORY
@external
@view
@reentrant
def configurator() -> address:
"""
@notice Address of the configurator
@return Address of the configurator contract
"""
return CONFIGURATOR.address
@external
@view
@reentrant
def amm() -> IAMM:
"""
@notice Address of the AMM
@return Address of the AMM contract
"""
return AMM
@external
@view
@reentrant
def collateral_token() -> IERC20:
"""
@notice Address of the collateral token
@return Address of the collateral token contract
"""
return COLLATERAL_TOKEN
@external
@view
@reentrant
def borrowed_token() -> IERC20:
"""
@notice Address of the borrowed token
@return Address of the borrowed token contract
"""
return BORROWED_TOKEN
@internal
def _save_rate():
"""
@notice Save current rate
@dev If the monetary policy is stateful `rate_write` MUST be permissioned
so that only the controller can call it. Otherwise one can circumvent the
reentrancy lock present in all the external methods that call `self._save_rate`
by calling `rate_write` directly.
"""
rate: uint256 = min(extcall self._monetary_policy.rate_write(), MAX_RATE)
extcall AMM.set_rate(rate)
@external
def save_rate():
"""
@notice Save current rate
"""
self._save_rate()
@internal
@view
def _debt(_user: address) -> (uint256, uint256):
"""
@notice Get the value of debt and rate_mul without changing the state
@param _user User address
@return (debt, rate_mul)
"""
rate_mul: uint256 = staticcall AMM.get_rate_mul()
loan: IController.Loan = self.loan[_user]
if loan.initial_debt == 0:
return (0, rate_mul)
else:
# Let user repay 1 smallest decimal more so that the system doesn't lose on precision
# Use ceil div
debt: uint256 = math._ceil_div(loan.initial_debt * rate_mul, loan.rate_mul)
return (debt, rate_mul)
@external
@view
def debt(_user: address) -> uint256:
"""
@notice Get the value of debt without changing the state
@param _user User address
@return Value of debt
"""
return self._debt(_user)[0]
@external
@view
def loan_exists(_user: address) -> bool:
"""
@notice Check whether there is a loan of `user` in existence
@param _user Address of the user to check
@return True if the user has an active loan, False otherwise
"""
return self.loan[_user].initial_debt > 0
@external
@view
@reentrant
def total_debt() -> uint256:
"""
@notice Total debt of this controller
@dev Marked as reentrant because used by monetary policy
@return Total outstanding debt with accrued interest
"""
return self._get_total_debt()
@internal
@pure
def _get_y_effective(
_collateral: uint256,
_N: uint256,
_discount: uint256,
_SQRT_BAND_RATIO: uint256,
_A: uint256,
) -> uint256:
"""
@notice Intermediary method which calculates y_effective defined as x_effective / p_base,
however discounted by loan_discount.
x_effective is an amount which can be obtained from collateral when liquidating
@param _collateral Amount of collateral with 18 decimals to get the value for
@param _N Number of bands the deposit is made into
@param _discount Loan discount at 1e18 base (e.g. 1e18 == 100%)
@param _SQRT_BAND_RATIO Square root of the band ratio sqrt((A-1)/A) at 1e18 base
@param _A Band width factor
@return y_effective
"""
# x_effective = sum_{i=0..N-1}(y / N * p(n_{n1+i})) =
# = y / N * p_oracle_up(n1) * sqrt((A - 1) / A) * sum_{0..N-1}(((A-1) / A)**k)
# === d_y_effective * p_oracle_up(n1) * sum(...) === y_effective * p_oracle_up(n1)
# d_y_effective = y / N / sqrt(A / (A - 1))
# d_y_effective: uint256 = collateral * unsafe_sub(10**18, discount) / (SQRT_BAND_RATIO * N)
# Make some extra discount to always deposit lower when we have DEAD_SHARES rounding
d_y_effective: uint256 = unsafe_div(
_collateral
* unsafe_sub(
WAD,
min(
_discount
+ unsafe_div(
(DEAD_SHARES * WAD),
max(unsafe_div(_collateral, _N), DEAD_SHARES),
),
WAD,
),
),
unsafe_mul(_SQRT_BAND_RATIO, _N),
)
y_effective: uint256 = d_y_effective
for _: uint256 in range(1, _N, bound=MAX_TICKS_UINT):
d_y_effective = unsafe_div(d_y_effective * unsafe_sub(_A, 1), _A)
y_effective = unsafe_add(y_effective, d_y_effective)
return y_effective
@external
@view
def max_borrowable(
_d_collateral: uint256, _N: uint256, _user: address = empty(address)
) -> uint256:
"""
@notice Calculation of maximum which can be borrowed.
Returns the maximum additional amount to be borrowed in case the user has a position.
@param _d_collateral Collateral amount against which to borrow
(additional amount if the user has a position)
@param _N Number of bands to have the deposit into (to be ignored if the user has a position)
@param _user User to calculate the value for
(can be zero address for create_loan if the user doesn't have extra_health)
@return Maximum (additional) amount of borrowed asset to borrow
"""
return staticcall self._view.max_borrowable(_d_collateral, _N, _user)
@external
@view
def min_collateral(
_debt: uint256, _N: uint256, _user: address = empty(address)
) -> uint256:
"""
@notice Calculation of minimum collaterl amount required for given debt amount
@param _debt The amount of debt for which calculation should be done
@param _N number of bands to have the deposit into
@param _user User to calculate the value for (only necessary for nonzero extra_health)
@return Minimum amount of collateral asset to provide
"""
return staticcall self._view.min_collateral(_debt, _N, _user)
@external
@view
def calculate_debt_n1(
_collateral: uint256,
_debt: uint256,
_N: uint256,
_user: address = empty(address),
) -> int256:
"""
@notice Calculate the upper band number for the deposit to sit in to support
the given debt. Reverts if requested debt is too high.
@param _collateral Amount of collateral (at its native precision)
@param _debt Amount of requested debt
@param _N Number of bands to deposit into
@param _user User to calculate n1 for (only necessary for nonzero extra_health)
@return Upper band n1 (n1 <= n2) to deposit into. Signed integer
"""
assert _N > MIN_TICKS_UINT - 1 # dev: Need more ticks
assert _N < MAX_TICKS_UINT + 1 # dev: Need less ticks
return self._calculate_debt_n1(_collateral, _debt, _N, _user)
@internal
@view
def _calculate_debt_n1(
_collateral: uint256,
_debt: uint256,
_N: uint256,
_user: address,
) -> int256:
assert _debt > 0 # dev: No loan
n0: int256 = staticcall AMM.active_band()
p_base: uint256 = staticcall AMM.p_oracle_up(n0)
# x_effective = y / N * p_oracle_up(n1) * sqrt((A - 1) / A) * sum_{0..N-1}(((A-1) / A)**k)
# === d_y_effective * p_oracle_up(n1) * sum(...) === y_effective * p_oracle_up(n1)
# d_y_effective = y / N / sqrt(A / (A - 1))
y_effective: uint256 = self._get_y_effective(
_collateral * COLLATERAL_PRECISION,
_N,
self.loan_discount + self.extra_health[_user],
SQRT_BAND_RATIO,
A,
)
# p_oracle_up(n1) = base_price * ((A - 1) / A)**n1
# We borrow up until min band touches p_oracle,
# or it touches non-empty bands which cannot be skipped.
# We calculate required n1 for given (collateral, debt),
# and if n1 corresponds to price_oracle being too high, or unreachable band
# - we revert.
# n1 is band number based on adiabatic trading, e.g. when p_oracle ~ p
y_effective = unsafe_div(
y_effective * p_base, _debt * BORROWED_PRECISION + 1
) # Now it's a ratio
# n1 = floor(log(y_effective) / self.logAratio)
# EVM semantics is not doing floor unlike Python, so we do this
assert y_effective > 0 # dev: Amount too low
n1: int256 = math._wad_ln(convert(y_effective, int256))
if n1 < 0:
n1 -= unsafe_sub(
LOGN_A_RATIO, 1
) # This is to deal with vyper's rounding of negative numbers
n1 = unsafe_div(n1, LOGN_A_RATIO)
n1 = min(n1, 1024 - convert(_N, int256)) + n0
if n1 <= n0:
assert staticcall AMM.can_skip_bands(n1 - 1), "Debt too high"
assert (
staticcall AMM.p_oracle_up(n1) <= staticcall AMM.price_oracle()
), "Debt too high"
return n1
@internal
@view
def _check_loan_exists(_debt: uint256):
# Abstraction to save bytecode on error messages
assert _debt > 0, "Loan doesn't exist"
@internal
def _execute_callback(
_callbacker: address,
_callback_sig: bytes4,
_user: address,
_borrowed: uint256,
_collateral: uint256,
_debt: uint256,
_calldata: Bytes[CALLDATA_MAX_SIZE],
) -> IController.CallbackData:
assert _callbacker != COLLATERAL_TOKEN.address
assert _callbacker != BORROWED_TOKEN.address
data: IController.CallbackData = empty(IController.CallbackData)
data.active_band = staticcall AMM.active_band()
band_x: uint256 = staticcall AMM.bands_x(data.active_band)
band_y: uint256 = staticcall AMM.bands_y(data.active_band)
# Callback
response: Bytes[64] = raw_call(
_callbacker,
concat(
_callback_sig,
abi_encode(_user, _borrowed, _collateral, _debt, _calldata),
),
max_outsize=64,
)
data.borrowed = convert(slice(response, 0, 32), uint256)
data.collateral = convert(slice(response, 32, 32), uint256)
# Checks after callback
assert data.active_band == staticcall AMM.active_band()
assert band_x == staticcall AMM.bands_x(data.active_band)
assert band_y == staticcall AMM.bands_y(data.active_band)
return data
@internal
def _update_user_liquidation_discount(_for: address, _approval: bool, _new_debt: uint256) -> uint256:
# Update liquidation discount only if it's the same or approved user. No rugs
liquidation_discount: uint256 = 0
if _approval:
liquidation_discount = self.liquidation_discount
self.liquidation_discounts[_for] = liquidation_discount
else:
liquidation_discount = self.liquidation_discounts[_for]
# Doesn't allow to end up with unhealthy state, except unhealthy user liquidation case (new_debt == 0)
# full = False to make this condition non-manipulatable (and also cheaper on gas)
if _new_debt > 0:
assert self._health(_for, _new_debt, False, liquidation_discount) >= 0, "The action ends with unhealthy state"
return liquidation_discount
@external
@view
def create_loan_health_preview(
_collateral: uint256,
_debt: uint256,
_N: uint256,
_for: address,
_full: bool,
) -> int256:
"""
@notice Calculates health after calling create_loan with the same params
@param _collateral Amount of collateral to use (from wallet + callback).
Note: the collateral amount coming from the callback should be included.
@param _debt Borrowed asset debt to take
@param _N Number of bands to deposit into (to do autoliquidation-deliquidation),
can be from MIN_TICKS to MAX_TICKS
@param _for Address of the user the loan is being created for
@param _full Whether it's a 'full' health or not
@return Signed health value
"""
return staticcall self._view.create_loan_health_preview(
_collateral, _debt, _N, _for, _full
)
@external
def create_loan(
_collateral: uint256,
_debt: uint256,
_N: uint256,
_for: address = msg.sender,
_callbacker: address = empty(address),
_calldata: Bytes[CALLDATA_MAX_SIZE] = b"",
):
"""
@notice Create loan but pass borrowed tokens to a callback first so that it can build leverage
@param _collateral Amount of collateral to use
@param _debt Borrowed asset debt to take
@param _N Number of bands to deposit into (to do autoliquidation-deliquidation),
can be from MIN_TICKS to MAX_TICKS
@param _for Address to create the loan for
@param _callbacker Address of the callback contract
@param _calldata Any data for callbacker
"""
assert self._has_approval(_for)
more_collateral: uint256 = 0
if _callbacker != empty(address):
tkn.transfer(BORROWED_TOKEN, _callbacker, _debt)
# If there is any unused debt, callbacker can send it to the user
cb: IController.CallbackData = self._execute_callback(
_callbacker,
CALLBACK_DEPOSIT,
_for,
0,
_collateral,
_debt,
_calldata,
)
assert cb.borrowed == 0 # dev: Not available
more_collateral = cb.collateral
total_collateral: uint256 = _collateral + more_collateral
assert self.loan[_for].initial_debt == 0, "Loan already created"
assert _N > MIN_TICKS_UINT - 1 # dev: Need more ticks
assert _N < MAX_TICKS_UINT + 1 # dev: Need less ticks
n1: int256 = self._calculate_debt_n1(total_collateral, _debt, _N, _for)
n2: int256 = n1 + convert(unsafe_sub(_N, 1), int256)
rate_mul: uint256 = staticcall AMM.get_rate_mul()
self.loan[_for] = IController.Loan(initial_debt=_debt, rate_mul=rate_mul)
n_loans: uint256 = self.n_loans
self.loans[n_loans] = _for
self.loan_ix[_for] = n_loans
self.n_loans = unsafe_add(n_loans, 1)
extcall AMM.deposit_range(_for, total_collateral, n1, n2)
tkn.transfer_from(COLLATERAL_TOKEN, msg.sender, AMM.address, _collateral)
tkn.transfer_from(COLLATERAL_TOKEN, _callbacker, AMM.address, more_collateral)
if _callbacker == empty(address):
tkn.transfer(BORROWED_TOKEN, _for, _debt)
self._update_total_debt(_debt, rate_mul, True)
self.lent += _debt
self._save_rate()
liquidation_discount: uint256 = self._update_user_liquidation_discount(_for, True, _debt)
log IController.UserState(
user=_for,
collateral=total_collateral,
borrowed=0,
debt=_debt,
n1=n1,
n2=n2,
liquidation_discount=liquidation_discount,
)
log IController.Borrow(
caller=msg.sender, user=_for, collateral_increase=total_collateral, loan_increase=_debt
)
@internal
def _add_collateral_borrow(
_d_collateral: uint256,
_d_debt: uint256,
_for: address,
_remove_collateral: bool,
) -> uint256:
"""
@notice Internal method to borrow and add or remove collateral
@param _d_collateral Amount of collateral to add
@param _d_debt Amount of debt increase
@param _for Address to transfer tokens to
@param _remove_collateral Remove collateral instead of adding
@return Current rate multiplier
"""
debt: uint256 = 0
rate_mul: uint256 = 0
debt, rate_mul = self._debt(_for)
self._check_loan_exists(debt)
debt += _d_debt
xy: uint256[2] = extcall AMM.withdraw(_for, WAD)
assert xy[0] == 0, "Underwater"
if _remove_collateral:
xy[1] -= _d_collateral
else:
xy[1] += _d_collateral
ns: int256[2] = staticcall AMM.read_user_tick_numbers(_for)
size: uint256 = convert(unsafe_add(unsafe_sub(ns[1], ns[0]), 1), uint256)
n1: int256 = self._calculate_debt_n1(xy[1], debt, size, _for)
n2: int256 = n1 + unsafe_sub(ns[1], ns[0])
extcall AMM.deposit_range(_for, xy[1], n1, n2)
self.loan[_for] = IController.Loan(initial_debt=debt, rate_mul=rate_mul)
liquidation_discount: uint256 = self._update_user_liquidation_discount(_for, True, debt)
if _remove_collateral:
log IController.RemoveCollateral(
caller=msg.sender, user=_for, collateral_decrease=_d_collateral
)
else:
log IController.Borrow(
caller=msg.sender, user=_for, collateral_increase=_d_collateral, loan_increase=_d_debt
)
log IController.UserState(
user=_for,
collateral=xy[1],
borrowed=0,
debt=debt,
n1=n1,
n2=n2,
liquidation_discount=liquidation_discount,
)
return rate_mul
@external
@view
def add_collateral_health_preview(
_collateral: uint256,
_for: address,
_full: bool,
) -> int256:
"""
@notice Calculates health after calling add_collateral with the same args
@param _collateral Amount of collateral to add
@param _for The user to add collateral for
@param _full Whether it's a 'full' health or not
@return Signed health value
"""
return staticcall self._view.add_collateral_health_preview(_collateral, _for, _full)
@external
def add_collateral(_collateral: uint256, _for: address = msg.sender):
"""
@notice Add extra collateral to avoid bad liquidations
@param _collateral Amount of collateral to add
@param _for Address to add collateral for
"""
if _collateral == 0:
return
assert self._has_approval(_for)
self._add_collateral_borrow(_collateral, 0, _for, False)
tkn.transfer_from(COLLATERAL_TOKEN, msg.sender, AMM.address, _collateral)
self._save_rate()
@external
@view
def remove_collateral_health_preview(
_collateral: uint256,
_for: address,
_full: bool,
) -> int256:
"""
@notice Calculates health after calling remove_collateral with the same args
@param _collateral Amount of collateral to remove
@param _for Address to remove collateral from
@param _full Whether it's a 'full' health or not
@return Signed health value
"""
return staticcall self._view.remove_collateral_health_preview(
_collateral, _for, _full
)
@external
def remove_collateral(_collateral: uint256, _for: address = msg.sender):
"""
@notice Remove some collateral without repaying the debt
@param _collateral Amount of collateral to remove
@param _for Address to remove collateral for
"""
if _collateral == 0:
return
assert self._has_approval(_for)
self._add_collateral_borrow(_collateral, 0, _for, True)
tkn.transfer_from(COLLATERAL_TOKEN, AMM.address, _for, _collateral)
self._save_rate()
@external
@view
def borrow_more_health_preview(
_collateral: uint256,
_debt: uint256,
_for: address,
_full: bool,
) -> int256:
"""
@notice Calculates health after calling borrow_more with the same params
@param _collateral Amount of collateral to add (from wallet + callback).
Note: the collateral amount coming from the callback should be included.
@param _debt Amount of borrowed asset debt to take
@param _for Address to borrow for
@param _full Whether it's a 'full' health or not
@return Signed health value
"""
return staticcall self._view.borrow_more_health_preview(
_collateral, _debt, _for, _full
)
@external
def borrow_more(
_collateral: uint256,
_debt: uint256,
_for: address = msg.sender,
_callbacker: address = empty(address),
_calldata: Bytes[CALLDATA_MAX_SIZE] = b"",
):
"""
@notice Borrow more borrowed tokens while adding more collateral using a callback (to leverage more)
@param _collateral Amount of collateral to add
@param _debt Amount of borrowed asset debt to take
@param _for Address to borrow for
@param _callbacker Address of the callback contract
@param _calldata Any data for callbacker
"""
if _debt == 0:
return
assert self._has_approval(_for)
more_collateral: uint256 = 0
if _callbacker != empty(address):
tkn.transfer(BORROWED_TOKEN, _callbacker, _debt)
# If there is any unused debt, callbacker can send it to the user
cb: IController.CallbackData = self._execute_callback(
_callbacker,
CALLBACK_DEPOSIT,
_for,
0,
_collateral,
_debt,
_calldata,
)
assert cb.borrowed == 0 # dev: Not available
more_collateral = cb.collateral
rate_mul: uint256 = self._add_collateral_borrow(
_collateral + more_collateral, _debt, _for, False
)
tkn.transfer_from(COLLATERAL_TOKEN, msg.sender, AMM.address, _collateral)
tkn.transfer_from(COLLATERAL_TOKEN, _callbacker, AMM.address, more_collateral)
if _callbacker == empty(address):
tkn.transfer(BORROWED_TOKEN, _for, _debt)
self._update_total_debt(_debt, rate_mul, True)
self.lent += _debt
self._save_rate()
@internal
def _remove_from_list(_for: address):
last_loan_ix: uint256 = self.n_loans - 1
loan_ix: uint256 = self.loan_ix[_for]
assert (
self.loans[loan_ix] == _for
) # dev: should never fail but safety first
self.loan_ix[_for] = 0
if loan_ix < last_loan_ix: # Need to replace
last_loan: address = self.loans[last_loan_ix]
self.loans[loan_ix] = last_loan
self.loan_ix[last_loan] = loan_ix
self.n_loans = last_loan_ix
@internal
def _repay_full(
_for: address,
_debt: uint256, # same as _d_debt in this case
_xy: uint256[2],
_cb: IController.CallbackData,
_callbacker: address,
):
"""
@notice Fully repay a loan and return all remaining collateral to the user
@param _for Address of the borrower whose loan is being repaid
@param _debt Total debt amount to repay
@param _xy Amounts of borrowed and collateral tokens withdrawn from the AMM
@param _cb Callback data (usually for selling collateral)
@param _callbacker Address of the callback contract, or empty if no callback
"""
if _callbacker == empty(address):
_xy = extcall AMM.withdraw(_for, WAD)
# ================= Recover borrowed tokens (xy[0]) =================
non_wallet_d_debt: uint256 = _xy[0] + _cb.borrowed
wallet_d_debt: uint256 = crv_math.sub_or_zero(_debt, non_wallet_d_debt)
if _xy[0] > 0: # pull borrowed tokens from AMM (already soft liquidated)
tkn.transfer_from(BORROWED_TOKEN, AMM.address, self, _xy[0])
tkn.transfer_from(BORROWED_TOKEN, _callbacker, self, _cb.borrowed)
tkn.transfer_from(BORROWED_TOKEN, msg.sender, self, wallet_d_debt)
tkn.transfer(BORROWED_TOKEN, _for, crv_math.sub_or_zero(non_wallet_d_debt, _debt))
# ================= Recover collateral tokens (xy[1]) =================
if _callbacker == empty(address):
tkn.transfer_from(COLLATERAL_TOKEN, AMM.address, _for, _xy[1])
else:
tkn.transfer_from(COLLATERAL_TOKEN, _callbacker, _for, _cb.collateral)
self._remove_from_list(_for)
log IController.UserState(
user=_for, collateral=0, borrowed=0, debt=0, n1=0, n2=0, liquidation_discount=0
)
log IController.Repay(
caller=msg.sender, user=_for, collateral_decrease=_xy[1], loan_decrease=_debt
)
@internal
def _repay_partial(
_for: address,
_debt: uint256,
_wallet_d_debt: uint256,
_xy: uint256[2],
_cb: IController.CallbackData,
_callbacker: address,
_max_active_band: int256,
_shrink: bool,
) -> uint256:
"""
@notice Partially repay a loan and reposition the user in the AMM
@param _for Address of the borrower whose loan is being partially repaid
@param _debt Current total debt of the user before repayment
@param _wallet_d_debt Amount of borrowed tokens being repaid from the caller's wallet
@param _xy Amounts of borrowed and collateral tokens withdrawn from the AMM
@param _cb Callback data (usually for selling collateral)
@param _callbacker Address of the callback contract, or empty if no callback
@param _max_active_band Maximum allowed active band (slippage guard against griefing)
@param _shrink Whether to shrink the position range toward the active band
@return Amount of debt actually repaid
"""
# slippage-like check to prevent dos on repay (grief attack)
active_band: int256 = staticcall AMM.active_band_with_skip()
new_collateral: uint256 = _xy[1]
if _callbacker != empty(address):
assert _cb.collateral <= _xy[1], "Collateral can't increase during repay"
active_band = _cb.active_band
new_collateral = _cb.collateral
assert active_band <= _max_active_band
ns: int256[2] = staticcall AMM.read_user_tick_numbers(_for)
size: int256 = unsafe_sub(ns[1], ns[0])
if ns[0] <= active_band and _shrink:
assert ns[1] >= active_band + MIN_TICKS, "Can't shrink"
size = unsafe_sub(ns[1], active_band + 1)
# _debt > _wallet_d_debt + cb.borrowed + xy[0] (check repay method)
new_debt: uint256 = unsafe_sub(_debt, unsafe_add(_cb.borrowed, _wallet_d_debt))
new_borrowed: uint256 = _xy[0]
if ns[0] > active_band or _shrink:
# Not underwater or shrink mode - can move bands
if _callbacker == empty(address):
_xy = extcall AMM.withdraw(_for, WAD)
new_collateral = _xy[1]
if _shrink:
new_debt -= _xy[0]
else:
assert _xy[0] == 0
new_borrowed = 0
ns[0] = self._calculate_debt_n1(
new_collateral,
new_debt,
convert(unsafe_add(size, 1), uint256),
_for,
)
ns[1] = ns[0] + size
extcall AMM.deposit_range(_for, new_collateral, ns[0], ns[1])
else:
# Underwater without shrink - cannot use callback or move bands.
# But can avoid a bad liquidation just reducing debt amount.
assert _callbacker == empty(address)
liquidation_discount: uint256 = self._update_user_liquidation_discount(_for, True, new_debt)
# ================= Recover borrowed tokens (xy[0]) =================
if _shrink:
tkn.transfer_from(BORROWED_TOKEN, AMM.address, self, _xy[0])
tkn.transfer_from(BORROWED_TOKEN, _callbacker, self, _cb.borrowed)
tkn.transfer_from(BORROWED_TOKEN, msg.sender, self, _wallet_d_debt)
# ================= Recover collateral tokens (xy[1]) =================
tkn.transfer_from(COLLATERAL_TOKEN, _callbacker, AMM.address, _cb.collateral)
d_debt: uint256 = _debt - new_debt
log IController.UserState(
user=_for,
collateral=new_collateral,
borrowed=new_borrowed,
debt=new_debt,
n1=ns[0],
n2=ns[1],
liquidation_discount=liquidation_discount,
)
log IController.Repay(
caller=msg.sender,
user=_for,
collateral_decrease=crv_math.sub_or_zero(_xy[1], new_collateral),
loan_decrease=d_debt,
)
return d_debt
@external
@view
def repay_health_preview(
_d_collateral: uint256,
_d_debt: uint256,
_for: address,
_shrink: bool,
_full: bool,
) -> int256:
"""
@notice Calculates health after calling repay with the same params
@dev Works only for partial repay, reverts for full repay
@param _d_collateral Amount of collateral to remove (goes to callback)
@param _d_debt The amount of debt to repay (from wallet + callback).
Note: the borrowed amount coming from the callback should be included.
@param _for The user to repay the debt for
@param _shrink Whether shrink soft-liquidated part of the position or not
@param _full Whether it's a 'full' health or not
@return Signed health value
"""
return staticcall self._view.repay_health_preview(
_d_collateral, _d_debt, _for, _shrink, _full
)
@external
def repay(
_wallet_d_debt: uint256,
_for: address = msg.sender,
_max_active_band: int256 = max_value(int256),
_callbacker: address = empty(address),
_calldata: Bytes[CALLDATA_MAX_SIZE] = b"",
_shrink: bool = False
):
"""
@notice Repay debt (partially or fully)
@param _wallet_d_debt The amount of debt to repay from user's wallet.
If it's max_value(uint256) or just higher than the current debt - will do full repayment.
@param _for The user to repay the debt for
@param _max_active_band Don't allow active band to be higher than this (to prevent front-running the repay)
@param _callbacker Address of the callback contract
@param _calldata Any data for callbacker
@param _shrink Whether shrink soft-liquidated part of the position or not
"""
assert self._has_approval(_for)
debt: uint256 = 0
rate_mul: uint256 = 0
debt, rate_mul = self._debt(_for)
self._check_loan_exists(debt)
xy: uint256[2] = staticcall AMM.get_sum_xy(_for)
cb: IController.CallbackData = empty(IController.CallbackData)
if _callbacker != empty(address):
xy = extcall AMM.withdraw(_for, WAD)
tkn.transfer_from(COLLATERAL_TOKEN, AMM.address, _callbacker, xy[1])
cb = self._execute_callback(
_callbacker, CALLBACK_REPAY, _for, xy[0], xy[1], debt, _calldata
)
d_debt: uint256 = min(min(_wallet_d_debt, debt) + xy[0] + cb.borrowed, debt)
assert d_debt > 0 # dev: no coins to repay
if d_debt == debt:
self._repay_full(_for, d_debt, xy, cb, _callbacker)
else:
d_debt = self._repay_partial(
_for,
debt,
_wallet_d_debt,
xy,
cb,
_callbacker,
_max_active_band,
_shrink,
)
debt -= d_debt
self.loan[_for] = IController.Loan(initial_debt=debt, rate_mul=rate_mul)
self._update_total_debt(d_debt, rate_mul, False)
self.repaid += d_debt
self._save_rate()
@external
@view
def tokens_to_shrink(_user: address, _d_collateral: uint256 = 0) -> uint256:
"""
@notice Calculate the amount of borrowed asset required to shrink the user's position
@param _user Address of the user to shrink the position for
@param _d_collateral The amount of collateral from user's position which is going to be used by callback
@return The amount of borrowed asset needed
"""
return staticcall self._view.tokens_to_shrink(_user, _d_collateral)
@internal
@view
def _health(
_user: address, _debt: uint256, _full: bool, _liquidation_discount: uint256
) -> int256:
"""
@notice Returns position health normalized to 1e18 for the user.
Liquidation starts when < 0, however devaluation of collateral doesn't cause liquidation
@param _user User address to calculate health for
@param _debt The amount of debt to calculate health for
@param _full Whether to take into account the price difference above the highest user's band
@param _liquidation_discount Liquidation discount to use (can be 0)
@return Health: > 0 = good.
"""
self._check_loan_exists(_debt)
health: int256 = SWAD - convert(_liquidation_discount, int256)
health = (
unsafe_div(
convert(staticcall AMM.get_x_down(_user), int256) * health,
convert(_debt, int256),
)
- SWAD
)
if _full:
ns0: int256 = (staticcall AMM.read_user_tick_numbers(_user))[0] # ns[1] > ns[0]
if ns0 > staticcall AMM.active_band(): # We are not in liquidation mode
p: uint256 = staticcall AMM.price_oracle()
p_up: uint256 = staticcall AMM.p_oracle_up(ns0)
if p > p_up:
health += convert(
unsafe_div(
unsafe_sub(p, p_up)
* (staticcall AMM.get_sum_xy(_user))[1]
* COLLATERAL_PRECISION,
_debt * BORROWED_PRECISION,
),
int256,
)
return health
@internal
@pure
def _get_f_remove(_frac: uint256, _health_limit: uint256) -> uint256:
# f_remove = ((1 + h / 2) / (1 + h) * (1 - frac) + frac) * frac
if _health_limit == 0:
return _frac
if _frac == WAD:
return WAD
f_remove: uint256 = unsafe_div(
unsafe_mul(
unsafe_add(WAD, unsafe_div(_health_limit, 2)),
unsafe_sub(WAD, _frac),
),
unsafe_add(WAD, _health_limit),
)
return unsafe_div(unsafe_mul(unsafe_add(f_remove, _frac), _frac), WAD)
@external
@view
def liquidate_health_preview(
_user: address,
_caller: address,
_frac: uint256,
_full: bool,
) -> int256:
"""
@notice Calculates health after calling liquidate with the same args
@param _user User to liquidate
@param _caller Address from which liquidate tx is going to be sent.
Depending on this address liquidation_discount will be changed or not.
@param _frac Fraction to liquidate; 100% = 10**18
@param _full Whether it's a 'full' health or not
@return Signed health value
"""
return staticcall self._view.liquidate_health_preview(
_user, _caller, _frac, _full
)
@external
def liquidate(
_user: address,
_min_x: uint256,
_frac: uint256 = 10**18,
_callbacker: address = empty(address),
_calldata: Bytes[CALLDATA_MAX_SIZE] = b"",
):
"""
@notice Perform a bad liquidation (or self-liquidation) of user if health is not good
@param _user Address of the user to liquidate
@param _min_x Minimal amount of borrowed asset to receive (to avoid liquidators being sandwiched)
@param _frac Fraction to liquidate; 100% = 10**18
@param _callbacker Address of the callback contract
@param _calldata Any data for callbacker
"""
approval: bool = self._has_approval(_user)
liquidation_discount: uint256 = self.liquidation_discounts[_user]
debt: uint256 = 0
rate_mul: uint256 = 0
debt, rate_mul = self._debt(_user)
health_before: int256 = self._health(_user, debt, True, liquidation_discount)
health_limit: uint256 = 0
if not approval:
assert health_before < 0, "Not enough rekt"
health_limit = liquidation_discount
final_debt: uint256 = debt
assert _frac <= WAD, "frac>100%"
debt = unsafe_div(debt * _frac + (WAD - 1), WAD)
assert debt > 0
final_debt = unsafe_sub(final_debt, debt)
# If liquidating entire debt, ensure full collateral withdrawal
f_remove: uint256 = self._get_f_remove(_frac, health_limit)
if final_debt == 0:
f_remove = WAD
# Withdraw sender's borrowed and collateral to our contract
# When frac is set - we withdraw a bit less for the same debt fraction
# f_remove = ((1 + h/2) / (1 + h) * (1 - frac) + frac) * frac
# where h is health limit.
# This is less than full h discount but more than no discount
xy: uint256[2] = extcall AMM.withdraw(_user, f_remove) # [stable, collateral]
# x increase in same block -> price up -> good
# x decrease in same block -> price down -> bad
assert xy[0] >= _min_x, "Slippage"
min_amm_burn: uint256 = min(xy[0], debt)
tkn.transfer_from(BORROWED_TOKEN, AMM.address, self, min_amm_burn)
if debt > xy[0]:
to_repay: uint256 = unsafe_sub(debt, xy[0])
if _callbacker == empty(address):
# Withdraw collateral if no callback is present
tkn.transfer_from(COLLATERAL_TOKEN, AMM.address, msg.sender, xy[1])
# Request what's left from user
tkn.transfer_from(BORROWED_TOKEN, msg.sender, self, to_repay)
else:
# Move collateral to callbacker, call it and remove everything from it back in
tkn.transfer_from(COLLATERAL_TOKEN, AMM.address, _callbacker, xy[1])
# Callback
cb: IController.CallbackData = self._execute_callback(
_callbacker,
CALLBACK_LIQUIDATE,
_user,
xy[0],
xy[1],
debt,
_calldata,
)
assert cb.borrowed >= to_repay, "no enough proceeds"
tkn.transfer_from(BORROWED_TOKEN, _callbacker, self, to_repay)
tkn.transfer_from(BORROWED_TOKEN, _callbacker, msg.sender, crv_math.sub_or_zero(cb.borrowed, to_repay))
tkn.transfer_from(COLLATERAL_TOKEN, _callbacker, msg.sender, cb.collateral)
else:
# Withdraw collateral
tkn.transfer_from(COLLATERAL_TOKEN, AMM.address, msg.sender, xy[1])
# xy[0] >= debt
tkn.transfer_from(BORROWED_TOKEN, AMM.address, msg.sender, unsafe_sub(xy[0], debt))
self.loan[_user] = IController.Loan(initial_debt=final_debt, rate_mul=rate_mul)
self._update_total_debt(debt, rate_mul, False)
self.repaid += debt
self._save_rate()
log IController.Repay(
caller=msg.sender, user=_user, collateral_decrease=xy[1], loan_decrease=debt
)
log IController.Liquidate(
liquidator=msg.sender,
user=_user,
collateral_received=xy[1],
borrowed_received=xy[0],
debt=debt,
)
if final_debt == 0:
log IController.UserState(
user=_user, collateral=0, borrowed=0, debt=0, n1=0, n2=0, liquidation_discount=0
)
self._remove_from_list(_user)
else:
if health_before >= 0:
liquidation_discount = self._update_user_liquidation_discount(_user, approval, final_debt)
else:
# Passing new_debt == 0 means the action can end with unhealthy state
liquidation_discount = self._update_user_liquidation_discount(_user, approval, 0)
xy = staticcall AMM.get_sum_xy(_user)
ns: int256[2] = staticcall AMM.read_user_tick_numbers(_user) # ns[1] > ns[0]
log IController.UserState(
user=_user,
collateral=xy[1],
borrowed=xy[0],
debt=final_debt,
n1=ns[0],
n2=ns[1],
liquidation_discount=liquidation_discount
)
@external
@view
def tokens_to_liquidate(_user: address, _frac: uint256 = WAD) -> uint256:
"""
@notice Calculate the amount of borrowed asset to have in liquidator's wallet to liquidate a user
@param _user Address of the user to liquidate
@param _frac Fraction to liquidate; 100% = 10**18
@return The amount of borrowed asset needed
"""
assert _frac <= WAD, "frac>100%"
health_limit: uint256 = 0
if not self._has_approval(_user):
health_limit = self.liquidation_discounts[_user]
borrowed: uint256 = unsafe_div(
(staticcall AMM.get_sum_xy(_user))[0]
* self._get_f_remove(_frac, health_limit),
WAD,
)
debt: uint256 = unsafe_div(self._debt(_user)[0] * _frac + (WAD - 1), WAD)
return crv_math.sub_or_zero(debt, borrowed)
@external
@view
def health(_user: address, _full: bool = False) -> int256:
"""
@notice Returns position health normalized to 1e18 for the user.
Liquidation starts when < 0, however devaluation of collateral doesn't cause liquidation
@param _user Address of the user
@param _full If True, use the full health calculation including bad debt discounts
@return Health value normalized to 1e18
"""
return self._health(
_user, self._debt(_user)[0], _full, self.liquidation_discounts[_user]
)
@external
@view
def users_to_liquidate(
_from: uint256 = 0, _limit: uint256 = 0
) -> DynArray[IController.Position, 1000]:
"""
@notice Returns a dynamic array of users who can be "hard-liquidated".
This method is designed for convenience of liquidation bots.
@param _from Loan index to start iteration from
@param _limit Number of loans to look over
@return Dynamic array with detailed info about positions of users
"""
return staticcall self._view.users_to_liquidate(_from, _limit)
@external
@view
def user_prices(_user: address) -> uint256[2]: # Upper, lower
"""
@notice Lowest price of the lower band and highest price of the upper band the user has deposit in the AMM
@param _user User address
@return (upper_price, lower_price)
"""
return staticcall self._view.user_prices(_user)
@external
@view
def user_state(_user: address) -> uint256[4]:
"""
@notice Return the user state in one call
@param _user User to return the state for
@return (collateral, borrowed, debt, N)
"""
return staticcall self._view.user_state(_user)
@internal
def _configure(
_loan_discount: uint256,
_liquidation_discount: uint256,
_monetary_policy: IMonetaryPolicy,
_view_blueprint: address,
_fee: uint256,
_price_oracle: IPriceOracle,
_liquidity_mining_callback: ILMCallback,
):
if _loan_discount != SKIP_CONFIG_UINT256 and _liquidation_discount != SKIP_CONFIG_UINT256:
self.loan_discount = _loan_discount
self.liquidation_discount = _liquidation_discount
if _monetary_policy.address != SKIP_CONFIG_ADDRESS:
self._monetary_policy = _monetary_policy
if _view_blueprint != SKIP_CONFIG_ADDRESS:
view: address = create_from_blueprint(
_view_blueprint,
self,
SQRT_BAND_RATIO,
LOGN_A_RATIO,
AMM,
A,
COLLATERAL_TOKEN,
COLLATERAL_PRECISION,
BORROWED_TOKEN,
BORROWED_PRECISION,
)
self._view = IView(view)
if _fee != SKIP_CONFIG_UINT256:
extcall AMM.set_fee(_fee)
if _price_oracle.address != SKIP_CONFIG_ADDRESS:
extcall AMM.set_price_oracle(_price_oracle)
if _liquidity_mining_callback.address != SKIP_CONFIG_ADDRESS:
extcall AMM.set_callback(_liquidity_mining_callback)
@external
def configure(
_loan_discount: uint256,
_liquidation_discount: uint256,
_monetary_policy: IMonetaryPolicy,
_view_blueprint: address,
_fee: uint256,
_price_oracle: IPriceOracle,
_liquidity_mining_callback: ILMCallback,
):
assert msg.sender == CONFIGURATOR.address # dev: Only configurator
self._configure(
_loan_discount,
_liquidation_discount,
_monetary_policy,
_view_blueprint,
_fee,
_price_oracle,
_liquidity_mining_callback,
)
@internal
@view
def _admin_fees() -> uint256:
return self._stored_admin_fees + self._preview_total_debt(staticcall AMM.get_rate_mul(), self._total_debt)[1]
@external
@view
@reentrant
def admin_fees() -> uint256:
"""
@notice Pending admin fees which can be claimed if the controller has enough balance
@return Amount of pending admin fees in borrowed token units
"""
return self._admin_fees()
@external
def collect_fees() -> uint256:
"""
@notice Collect the fees charged as interest.
@return Amount of fees collected and transferred to the fee receiver
"""
rate_mul: uint256 = staticcall AMM.get_rate_mul()
self._update_total_debt(0, rate_mul, False)
# self._stored_admin_fees == self.admin_fees() after _update_total_debt
pending_admin_fees: uint256 = self._stored_admin_fees
self.collected += pending_admin_fees
self._stored_admin_fees = 0
extcall VIRTUAL.on_borrowed_token_transfer_out(pending_admin_fees)
tkn.transfer(BORROWED_TOKEN, staticcall FACTORY.fee_receiver(), pending_admin_fees)
self._save_rate()
log IController.CollectFees(amount=pending_admin_fees)
return pending_admin_fees
@external
@reentrant
def on_borrowed_token_transfer_in(_amount: uint256):
pass
@external
@reentrant
def on_borrowed_token_transfer_out(_amount: uint256):
pass
@external
@reentrant
def _on_debt_increased(_total_debt: uint256):
pass
@external
def approve(_spender: address, _allow: bool):
"""
@notice Allow another address to borrow and repay for the user
@param _spender Address to whitelist for the action
@param _allow Whether to turn the approval on or off (no amounts)
"""
self.approval[msg.sender][_spender] = _allow
log IController.Approval(owner=msg.sender, spender=_spender, allow=_allow)
@internal
@view
def _has_approval(_for: address) -> bool:
return msg.sender == _for or self.approval[_for][msg.sender]
@external
def set_extra_health(_value: uint256):
"""
@notice Add a little bit more to loan_discount to start SL with health higher than usual
@param _value 1e18-based addition to loan_discount
"""
assert _value < WAD, "extra_health too high"
self.extra_health[msg.sender] = _value
log IController.SetExtraHealth(user=msg.sender, health=_value)
curve_stablecoin/interfaces/IAMM.vyi
from curve_stablecoin.interfaces import ILMCallback
from curve_stablecoin.interfaces import IPriceOracle
# Structs
struct UserTicks:
ns: int256
ticks: uint256[25]
struct DetailedTrade:
in_amount: uint256
out_amount: uint256
n1: int256
n2: int256
ticks_in: DynArray[uint256, 50]
last_tick_j: uint256
# Events
event TokenExchange:
buyer: indexed(address)
sold_id: uint256
tokens_sold: uint256
bought_id: uint256
tokens_bought: uint256
event Deposit:
provider: indexed(address)
amount: uint256
n1: int256
n2: int256
event Withdraw:
provider: indexed(address)
amount_borrowed: uint256
amount_collateral: uint256
event SetRate:
rate: uint256
rate_mul: uint256
time: uint256
# Functions
@external
def set_admin(_admin: address):
...
@view
@external
def coins(i: uint256) -> address:
...
@view
@external
def price_oracle() -> uint256:
...
@view
@external
def get_rate_mul() -> uint256:
...
@view
@external
def get_base_price() -> uint256:
...
@view
@external
def p_current_up(n: int256) -> uint256:
...
@view
@external
def p_current_down(n: int256) -> uint256:
...
@view
@external
def p_oracle_up(n: int256) -> uint256:
...
@view
@external
def p_oracle_down(n: int256) -> uint256:
...
@view
@external
def get_p() -> uint256:
...
@view
@external
def read_user_tick_numbers(user: address) -> int256[2]:
...
@view
@external
def read_user_ticks(user: address) -> DynArray[uint256, 50]:
...
@view
@external
def can_skip_bands(n_end: int256) -> bool:
...
@view
@external
def active_band_with_skip() -> int256:
...
@view
@external
def has_liquidity(user: address) -> bool:
...
@external
def deposit_range(user: address, amount: uint256, n1: int256, n2: int256):
...
@external
def withdraw(user: address, frac: uint256) -> uint256[2]:
...
@view
@external
def get_dy(i: uint256, j: uint256, in_amount: uint256) -> uint256:
...
@view
@external
def get_dxdy(i: uint256, j: uint256, in_amount: uint256) -> (uint256, uint256):
...
@view
@external
def get_dx(i: uint256, j: uint256, out_amount: uint256) -> uint256:
...
@view
@external
def get_dydx(i: uint256, j: uint256, out_amount: uint256) -> (uint256, uint256):
...
@external
def exchange(i: uint256, j: uint256, in_amount: uint256, min_amount: uint256, _for: address) -> uint256[2]:
...
@external
def exchange_dy(i: uint256, j: uint256, out_amount: uint256, max_amount: uint256, _for: address) -> uint256[2]:
...
@view
@external
def get_y_up(user: address) -> uint256:
...
@view
@external
def get_x_down(user: address) -> uint256:
...
@view
@external
def get_sum_xy(user: address) -> uint256[2]:
...
@view
@external
def get_xy(user: address) -> DynArray[uint256, 50][2]:
...
@view
@external
def get_amount_for_price(p: uint256) -> (uint256, bool):
...
@external
def set_rate(rate: uint256) -> uint256:
...
@external
def set_fee(fee: uint256):
...
@external
def set_callback(liquidity_mining_callback: ILMCallback):
...
@external
def set_price_oracle(_price_oracle: IPriceOracle):
...
@view
@external
def admin() -> address:
...
@view
@external
def A() -> uint256:
...
@view
@external
def fee() -> uint256:
...
@view
@external
def rate() -> uint256:
...
@view
@external
def active_band() -> int256:
...
@view
@external
def min_band() -> int256:
...
@view
@external
def max_band() -> int256:
...
@view
@external
def price_oracle_contract() -> IPriceOracle:
...
@view
@external
def bands_x(arg0: int256) -> uint256:
...
@view
@external
def bands_y(arg0: int256) -> uint256:
...
@view
@external
def liquidity_mining_callback() -> ILMCallback:
...
curve_stablecoin/interfaces/IConfigurator.vyi
from curve_stablecoin.interfaces import IController
from curve_stablecoin.interfaces import ILendController
from curve_stablecoin.interfaces import IMonetaryPolicy
from curve_stablecoin.interfaces import IPriceOracle
from curve_stablecoin.interfaces import ILMCallback
# Events
event SetCustomAdmin:
controller: indexed(address)
admin: address
event SetBorrowingDiscounts:
controller: indexed(address)
loan_discount: uint256
liquidation_discount: uint256
event SetBorrowCap:
controller: indexed(address)
borrow_cap: uint256
event SetAdminPercentage:
controller: indexed(address)
admin_percentage: uint256
event SetMonetaryPolicy:
controller: indexed(address)
monetary_policy: address
event SetView:
controller: indexed(address)
view: address
event SetPriceOracle:
controller: indexed(address)
price_oracle: address
event SetCallback:
controller: indexed(address)
callback: address
event SetAmmFee:
controller: indexed(address)
fee: uint256
event SetDefaultAdmin:
new_default_admin: address
# Functions
@external
def set_custom_admin(_controller: IController, _admin: address):
...
@external
def set_owner(_new_default_admin: address):
...
@external
def set_borrowing_discounts(_controller: IController, _loan_discount: uint256, _liquidation_discount: uint256):
...
@external
def set_monetary_policy(_controller: IController, _monetary_policy: IMonetaryPolicy):
...
@external
def set_view(_controller: IController, _view_blueprint: address):
...
@external
def set_borrow_cap(_controller: ILendController, _borrow_cap: uint256):
...
@external
def set_admin_percentage(_controller: ILendController, _admin_percentage: uint256):
...
@external
def set_price_oracle(_controller: IController, _price_oracle: IPriceOracle, _max_deviation: uint256):
...
@external
def set_callback(_controller: IController, _cb: ILMCallback):
...
@external
def set_amm_fee(_controller: IController, _fee: uint256):
...
@view
@external
def default_admin() -> address:
...
curve_stablecoin/interfaces/IController.vyi
from curve_std.interfaces import IERC20
from curve_stablecoin.interfaces import ILMCallback
from curve_stablecoin.interfaces import IAMM
from curve_stablecoin.interfaces import IMonetaryPolicy
from curve_stablecoin.interfaces import IPriceOracle
from curve_stablecoin.interfaces import IFactory
from curve_stablecoin import constants as c
CALLDATA_MAX_SIZE: constant(uint256) = c.CALLDATA_MAX_SIZE
# Events
event Repay:
caller: indexed(address)
user: indexed(address)
collateral_decrease: uint256
loan_decrease: uint256
event Liquidate:
liquidator: indexed(address)
user: indexed(address)
collateral_received: uint256
borrowed_received: uint256
debt: uint256
event UserState:
user: indexed(address)
collateral: uint256
borrowed: uint256
debt: uint256
n1: int256
n2: int256
liquidation_discount: uint256
event RemoveCollateral:
caller: indexed(address)
user: indexed(address)
collateral_decrease: uint256
event Borrow:
caller: indexed(address)
user: indexed(address)
collateral_increase: uint256
loan_increase: uint256
event Approval:
owner: indexed(address)
spender: indexed(address)
allow: bool
event SetExtraHealth:
user: indexed(address)
health: uint256
event CollectFees:
amount: uint256
# Structs
struct Position:
user: address
x: uint256
y: uint256
debt: uint256
health: int256
struct Loan:
initial_debt: uint256
rate_mul: uint256
struct CallbackData:
active_band: int256
borrowed: uint256
collateral: uint256
# Functions
@view
@external
def monetary_policy() -> IMonetaryPolicy:
...
@external
@view
def available_balance() -> uint256:
...
@view
@external
def max_borrowable(_d_collateral: uint256, _N: uint256, _user: address) -> uint256:
...
@external
def liquidate(user: address, min_x: uint256, _frac: uint256, callbacker: address = empty(address), calldata: Bytes[CALLDATA_MAX_SIZE] = b''):
...
@external
def borrow_more(collateral: uint256, debt: uint256, _for: address, callbacker: address, calldata: Bytes[CALLDATA_MAX_SIZE]):
...
@external
def configure(
loan_discount: uint256,
liquidation_discount: uint256,
monetary_policy: IMonetaryPolicy,
view: address,
fee: uint256,
price_oracle: IPriceOracle,
liquidity_mining_callback: ILMCallback,
):
...
@external
def create_loan(collateral: uint256, debt: uint256, N: uint256, _for: address, callbacker: address, calldata: Bytes[CALLDATA_MAX_SIZE]):
...
@external
def repay(
_d_debt: uint256,
_for: address = msg.sender,
max_active_band: int256 = max_value(int256),
callbacker: address = empty(address),
calldata: Bytes[CALLDATA_MAX_SIZE] = b"",
shrink: bool = False,
):
...
@view
@external
def tokens_to_shrink(user: address, _d_collateral: uint256) -> uint256:
...
@external
def approve(_spender: address, _allow: bool):
...
@external
def set_extra_health(_value: uint256):
...
@external
def save_rate():
...
@external
def collect_fees() -> uint256:
...
@external
def add_collateral(collateral: uint256, _for: address):
...
@external
def remove_collateral(collateral: uint256, _for: address):
...
@view
@external
def amm() -> IAMM:
...
@view
@external
def collateral_token() -> IERC20:
...
@view
@external
def borrowed_token() -> IERC20:
...
@view
@external
def debt(user: address) -> uint256:
...
@view
@external
def loan_exists(user: address) -> bool:
...
@view
@external
def total_debt() -> uint256:
...
@view
@external
def min_collateral(debt: uint256, N: uint256, user: address) -> uint256:
...
@view
@external
def calculate_debt_n1(collateral: uint256, debt: uint256, N: uint256, user: address) -> int256:
...
@view
@external
def user_prices(user: address) -> uint256[2]:
...
@view
@external
def user_state(user: address) -> uint256[4]:
...
@view
@external
def create_loan_health_preview(collateral: uint256, debt: uint256, N: uint256, _for: address, full: bool) -> int256:
...
@view
@external
def add_collateral_health_preview(collateral: uint256, _for: address, full: bool) -> int256:
...
@view
@external
def remove_collateral_health_preview(collateral: uint256, _for: address, full: bool) -> int256:
...
@view
@external
def borrow_more_health_preview(collateral: uint256, debt: uint256, _for: address, full: bool) -> int256:
...
@view
@external
def repay_health_preview(d_collateral: uint256, d_debt: uint256, _for: address, shrink: bool, full: bool) -> int256:
...
@view
@external
def liquidate_health_preview(user: address, _caller: address, _frac: uint256, full: bool) -> int256:
...
@view
@external
def tokens_to_liquidate(user: address, frac: uint256) -> uint256:
...
@view
@external
def health(user: address, full: bool) -> int256:
...
@view
@external
def users_to_liquidate(_from: uint256, _limit: uint256) -> DynArray[Position, 1000]:
...
@view
@external
def admin_fees() -> uint256:
...
@view
@external
def factory() -> IFactory:
...
@view
@external
def configurator() -> address:
...
@view
@external
def liquidation_discount() -> uint256:
...
@view
@external
def loan_discount() -> uint256:
...
@view
@external
def approval(arg0: address, arg1: address) -> bool:
...
@view
@external
def extra_health(arg0: address) -> uint256:
...
@view
@external
def liquidation_discounts(arg0: address) -> uint256:
...
@view
@external
def loans(arg0: uint256) -> address:
...
@view
@external
def loan_ix(arg0: address) -> uint256:
...
@view
@external
def n_loans() -> uint256:
...
@view
@external
def version() -> String[1]:
...
@view
@external
def view() -> address:
...
curve_stablecoin/interfaces/IControllerView.vyi
from curve_stablecoin.interfaces import IController
# Functions
@view
@external
def create_loan_health_preview(_collateral: uint256, _debt: uint256, _N: uint256, _for: address, _full: bool) -> int256:
...
@view
@external
def add_collateral_health_preview(_collateral: uint256, _for: address, _full: bool) -> int256:
...
@view
@external
def remove_collateral_health_preview(_collateral: uint256, _for: address, _full: bool) -> int256:
...
@view
@external
def borrow_more_health_preview(_collateral: uint256, _debt: uint256, _for: address, _full: bool) -> int256:
...
@view
@external
def repay_health_preview(_d_collateral: uint256, _d_debt: uint256, _for: address, _shrink: bool, _full: bool) -> int256:
...
@view
@external
def tokens_to_shrink(user: address, _d_collateral: uint256) -> uint256:
...
@view
@external
def liquidate_health_preview(_user: address, _caller: address, _frac: uint256, _full: bool) -> int256:
...
@view
@external
def users_to_liquidate(_from: uint256, _limit: uint256) -> DynArray[IController.Position, 1000]:
...
@view
@external
def user_prices(user: address) -> uint256[2]:
...
@view
@external
def user_state(user: address) -> uint256[4]:
...
@view
@external
def max_borrowable(_d_collateral: uint256, _N: uint256, _user: address) -> uint256:
...
@view
@external
def min_collateral(debt: uint256, N: uint256, user: address) -> uint256:
...
curve_stablecoin/interfaces/IFactory.vyi
from curve_std.interfaces import IERC20
@view
def stablecoin() -> IERC20:
...
@view
def admin() -> address:
...
@view
def fee_receiver() -> address:
...
curve_stablecoin/interfaces/ILMCallback.vyi
from curve_stablecoin import constants as c
MAX_TICKS_UINT: constant(uint256) = c.MAX_TICKS_UINT
event SetKilled:
is_killed: bool
event UpdateInflationRate:
new_rate: uint256
future_epoch_time: uint256
event CheckpointRPC:
rpc: uint256
t: uint256
event CheckpointUser:
user: indexed(address)
integrate_fraction: uint256
event CheckpointBand:
n: indexed(int256)
rps: uint256
collateral_per_share: uint256
struct IntegralRPC:
rpc: uint256
t: uint256
struct IntegralRPS:
rps: uint256
rpc: uint256
struct IntegralRPU:
rpu: uint256
rps: uint256
def callback_collateral_shares(n: int256, collateral_per_share: DynArray[uint256, MAX_TICKS_UINT], size: uint256):
...
def callback_user_shares(user: address, n: int256, user_shares: DynArray[uint256, MAX_TICKS_UINT], size: uint256):
...
curve_stablecoin/interfaces/ILendController.vyi
# Llamalend-specific interface additions not covered by IController
@external
@view
def vault() -> address:
...
@external
def configure_lend(_borrow_cap: uint256, _admin_percentage: uint256):
...
@external
def on_borrowed_token_transfer_in(_amount: uint256):
...
@external
def on_borrowed_token_transfer_out(_amount: uint256):
...
@external
@view
def borrow_cap() -> uint256:
...
@external
@view
def lent() -> uint256:
...
@external
@view
def repaid() -> uint256:
...
@external
@view
def collected() -> uint256:
...
@external
@view
def admin_percentage() -> uint256:
...
curve_stablecoin/interfaces/IMonetaryPolicy.vyi
def rate_write() -> uint256:
...
@view
def rate() -> uint256:
...
curve_stablecoin/interfaces/IPriceOracle.vyi
@view
def price() -> uint256:
...
def price_w() -> uint256:
...
curve_stablecoin/interfaces/IVault.vyi
from curve_std.interfaces import IERC20
from curve_stablecoin.interfaces import IAMM
from curve_stablecoin.interfaces import IController
from curve_stablecoin.interfaces import IFactory
event SetMaxSupply:
max_supply: uint256
@external
def initialize(
_amm: IAMM,
_controller: IController,
_borrowed_token: IERC20,
_collateral_token: IERC20,
):
...
@external
def set_max_supply(_max_supply: uint256):
...
@view
def borrowed_token() -> IERC20:
...
@view
def collateral_token() -> IERC20:
...
@view
def amm() -> IAMM:
...
@view
def controller() -> IController:
...
@view
def factory() -> IFactory:
...
@view
@external
def admin() -> address:
...
@view
def maxSupply() -> uint256:
...
@view
@external
def asset() -> IERC20:
...
@view
@external
def borrow_apr() -> uint256:
...
@view
@external
def lend_apr() -> uint256:
...
@view
@external
def totalAssets() -> uint256:
...
@view
@external
def pricePerShare(_is_floor: bool = True) -> uint256:
...
@view
@external
def convertToShares(_assets: uint256) -> uint256:
...
@view
@external
def convertToAssets(_shares: uint256) -> uint256:
...
@view
@external
def maxDeposit(_receiver: address) -> uint256:
...
@view
@external
def previewDeposit(_assets: uint256) -> uint256:
...
@external
def deposit(_assets: uint256, _receiver: address = msg.sender) -> uint256:
...
@view
@external
def maxMint(_receiver: address) -> uint256:
...
@view
@external
def previewMint(_shares: uint256) -> uint256:
...
@external
def mint(_shares: uint256, _receiver: address = msg.sender) -> uint256:
...
@view
@external
def maxWithdraw(_owner: address) -> uint256:
...
@view
@external
def previewWithdraw(_assets: uint256) -> uint256:
...
@external
def withdraw(
_assets: uint256,
_receiver: address = msg.sender,
_owner: address = msg.sender,
) -> uint256:
...
@view
@external
def maxRedeem(_owner: address) -> uint256:
...
@view
@external
def previewRedeem(_shares: uint256) -> uint256:
...
@external
def redeem(
_shares: uint256,
_receiver: address = msg.sender,
_owner: address = msg.sender,
) -> uint256:
...
@view
def decimals() -> uint8:
...
@view
def name() -> String[64]:
...
@view
def symbol() -> String[34]:
...
@view
def allowance(_owner: address, _spender: address) -> uint256:
...
@view
def balanceOf(_owner: address) -> uint256:
...
@view
def totalSupply() -> uint256:
...
@external
def transferFrom(_from: address, _to: address, _value: uint256) -> bool:
...
@external
def transfer(_to: address, _value: uint256) -> bool:
...
@external
def approve(_spender: address, _value: uint256) -> bool:
...
@external
def increaseAllowance(_spender: address, _add_value: uint256) -> bool:
...
@external
def decreaseAllowance(_spender: address, _sub_value: uint256) -> bool:
...
curve_std/crv_math.vy
# pragma version 0.4.3
@pure
@internal
def sub_or_zero(a: uint256, b: uint256) -> uint256:
return unsafe_sub(max(a, b), b)
curve_std/interfaces/IERC20.vyi
# pragma version 0.4.3
# See https://github.com/vyperlang/vyper/pull/4349 for rationale
SYMBOL_MAX_LEN: constant(uint256) = 32
NAME_MAX_LEN: constant(uint256) = 64
# Events
event Transfer:
sender: indexed(address)
receiver: indexed(address)
value: uint256
event Approval:
owner: indexed(address)
spender: indexed(address)
value: uint256
# Functions
@view
def totalSupply() -> uint256:
...
@view
def balanceOf(_owner: address) -> uint256:
...
@view
def allowance(_owner: address, _spender: address) -> uint256:
...
def transfer(_to: address, _value: uint256) -> bool:
...
def transferFrom(_from: address, _to: address, _value: uint256) -> bool:
...
def approve(_spender: address, _value: uint256) -> bool:
...
@view
def name() -> String[NAME_MAX_LEN]:
...
@view
def symbol() -> String[SYMBOL_MAX_LEN]:
...
@view
def decimals() -> uint8:
...
curve_std/token.vy
# pragma version 0.4.3
from curve_std.interfaces import IERC20
@internal
def max_approve(token: IERC20, spender: address):
if staticcall token.allowance(self, spender) == 0:
assert extcall token.approve(spender, max_value(uint256), default_return_value=True)
@internal
def transfer_from(token: IERC20, _from: address, _to: address, amount: uint256):
if amount > 0:
assert extcall token.transferFrom(_from, _to, amount, default_return_value=True)
@internal
def transfer(token: IERC20, _to: address, amount: uint256):
if amount > 0:
assert extcall token.transfer(_to, amount, default_return_value=True)
snekmate/utils/math.vy
# pragma version ~=0.4.3
# pragma nonreentrancy off
"""
@title Standard Mathematical Utility Functions
@custom:contract-name math
@license GNU Affero General Public License v3.0 only
@author pcaversaccio
@custom:coauthor bout3fiddy
@notice These functions implement standard mathematical utility
functions that are missing in the Vyper language. If a
function is inspired by an existing implementation, it
is properly referenced in the function docstring. The
following functions have been added for convenience:
- `_uint256_average` (`internal` `pure` function),
- `_int256_average` (`internal` `pure` function),
- `_ceil_div` (`internal` `pure` function),
- `_signum` (`internal` `pure` function),
- `_mul_div` (`internal` `pure` function),
- `_log2` (`internal` `pure` function),
- `_log10` (`internal` `pure` function),
- `_log256` (`internal` `pure` function),
- `_wad_ln` (`internal` `pure` function),
- `_wad_exp` (`internal` `pure` function),
- `_cbrt` (`internal` `pure` function),
- `_wad_cbrt` (`internal` `pure` function).
"""
@deploy
@payable
def __init__():
"""
@dev To omit the opcodes for checking the `msg.value`
in the creation-time EVM bytecode, the constructor
is declared as `payable`.
"""
pass
@internal
@pure
def _uint256_average(x: uint256, y: uint256) -> uint256:
"""
@dev Returns the average of two 32-byte unsigned integers.
@notice Note that the result is rounded towards zero. For
more details on finding the average of two unsigned
integers without an overflow, please refer to:
https://devblogs.microsoft.com/oldnewthing/20220207-00/?p=106223.
@param x The first 32-byte unsigned integer of the data set.
@param y The second 32-byte unsigned integer of the data set.
@return uint256 The 32-byte average (rounded towards zero) of
`x` and `y`.
"""
return unsafe_add(x & y, (x ^ y) >> 1)
@internal
@pure
def _int256_average(x: int256, y: int256) -> int256:
"""
@dev Returns the average of two 32-byte signed integers.
@notice Note that the result is rounded towards infinity.
For more details on finding the average of two signed
integers without an overflow, please refer to:
https://patents.google.com/patent/US6007232A/en.
@param x The first 32-byte signed integer of the data set.
@param y The second 32-byte signed integer of the data set.
@return int256 The 32-byte average (rounded towards infinity)
of `x` and `y`.
"""
return unsafe_add(unsafe_add(x >> 1, y >> 1), x & y & 1)
@internal
@pure
def _ceil_div(x: uint256, y: uint256) -> uint256:
"""
@dev Calculates "ceil(x / y)" for any strictly positive `y`.
@notice The implementation is inspired by OpenZeppelin's
implementation here:
https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/Math.sol.
@param x The 32-byte numerator.
@param y The 32-byte denominator.
@return uint256 The 32-byte rounded up result of "x/y".
"""
assert y != empty(uint256), "math: ceil_div division by zero"
# Due to a known compiler bug (https://github.com/vyperlang/vyper/issues/3480),
# we use `0` instead of `empty(uint256)` as return value.
return 0 if (x == empty(uint256)) else unsafe_add(unsafe_div(x - 1, y), 1)
@internal
@pure
def _signum(x: int256) -> int256:
"""
@dev Returns the indication of the sign of a 32-byte signed integer.
@notice The function returns `-1` if `x < 0`, `0` if `x == 0`, and `1`
if `x > 0`. For more details on finding the sign of a signed
integer, please refer to:
https://graphics.stanford.edu/~seander/bithacks.html#CopyIntegerSign.
@param x The 32-byte signed integer variable.
@return int256 The 32-byte sign indication (`1`, `0`, or `-1`) of `x`.
"""
return unsafe_sub(convert((x > empty(int256)), int256), convert((x < empty(int256)), int256))
@internal
@pure
def _mul_div(x: uint256, y: uint256, denominator: uint256, roundup: bool) -> uint256:
"""
@dev Calculates "(x * y) / denominator" in 512-bit precision,
following the selected rounding direction.
@notice The implementation is inspired by Remco Bloemen's
implementation under the MIT license here:
https://xn--2-umb.com/21/muldiv.
Furthermore, the rounding direction design pattern is
inspired by OpenZeppelin's implementation here:
https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/Math.sol.
@param x The 32-byte multiplicand.
@param y The 32-byte multiplier.
@param denominator The 32-byte divisor.
@param roundup The Boolean variable that specifies whether
to round up or not. The default `False` is round down.
@return uint256 The 32-byte calculation result.
"""
# Handle division by zero.
assert denominator != empty(uint256), "math: mul_div division by zero"
# 512-bit multiplication "[prod1 prod0] = x * y".
# Compute the product "mod 2**256" and "mod 2**256 - 1".
# Then use the Chinese Remainder theorem to reconstruct
# the 512-bit result. The result is stored in two 256-bit
# variables, where: "product = prod1 * 2**256 + prod0".
mm: uint256 = uint256_mulmod(x, y, max_value(uint256))
# The least significant 256 bits of the product.
prod0: uint256 = unsafe_mul(x, y)
# The most significant 256 bits of the product.
prod1: uint256 = empty(uint256)
if mm < prod0:
prod1 = unsafe_sub(unsafe_sub(mm, prod0), 1)
else:
prod1 = unsafe_sub(mm, prod0)
# Handling of non-overflow cases, 256 by 256 division.
if prod1 == empty(uint256):
if roundup and uint256_mulmod(x, y, denominator) != empty(uint256):
# Calculate "ceil((x * y) / denominator)". The following
# line cannot overflow because we have the previous check
# "(x * y) % denominator != 0", which accordingly rules out
# the possibility of "x * y = 2**256 - 1" and `denominator == 1`.
return unsafe_add(unsafe_div(prod0, denominator), 1)
return unsafe_div(prod0, denominator)
# Ensure that the result is less than "2**256". Also,
# prevents that `denominator == 0`.
assert denominator > prod1, "math: mul_div overflow"
#######################
# 512 by 256 Division #
#######################
# Make division exact by subtracting the remainder
# from "[prod1 prod0]". First, compute remainder using
# the `uint256_mulmod` operation.
remainder: uint256 = uint256_mulmod(x, y, denominator)
# Second, subtract the 256-bit number from the 512-bit
# number.
if remainder > prod0:
prod1 = unsafe_sub(prod1, 1)
prod0 = unsafe_sub(prod0, remainder)
# Factor powers of two out of the denominator and calculate
# the largest power of two divisor of denominator. Always `>= 1`,
# unless the denominator is zero (which is prevented above),
# in which case `twos` is zero. For more details, please refer to:
# https://cs.stackexchange.com/q/138556.
twos: uint256 = unsafe_sub(empty(uint256), denominator) & denominator
# Divide denominator by `twos`.
denominator_div: uint256 = unsafe_div(denominator, twos)
# Divide "[prod1 prod0]" by `twos`.
prod0 = unsafe_div(prod0, twos)
# Flip `twos` such that it is "2**256 / twos". If `twos` is zero,
# it becomes one.
twos = unsafe_add(unsafe_div(unsafe_sub(empty(uint256), twos), twos), 1)
# Shift bits from `prod1` to `prod0`.
prod0 |= unsafe_mul(prod1, twos)
# Invert the denominator "mod 2**256". Since the denominator is
# now an odd number, it has an inverse modulo "2**256", so we have:
# "denominator * inverse = 1 mod 2**256". Calculate the inverse by
# starting with a seed that is correct for four bits. That is,
# "denominator * inverse = 1 mod 2**4".
inverse: uint256 = unsafe_mul(3, denominator_div) ^ 2
# Use Newton-Raphson iteration to improve accuracy. Thanks to Hensel's
# lifting lemma, this also works in modular arithmetic by doubling the
# correct bits in each step.
inverse = unsafe_mul(inverse, unsafe_sub(2, unsafe_mul(denominator_div, inverse))) # Inverse "mod 2**8".
inverse = unsafe_mul(inverse, unsafe_sub(2, unsafe_mul(denominator_div, inverse))) # Inverse "mod 2**16".
inverse = unsafe_mul(inverse, unsafe_sub(2, unsafe_mul(denominator_div, inverse))) # Inverse "mod 2**32".
inverse = unsafe_mul(inverse, unsafe_sub(2, unsafe_mul(denominator_div, inverse))) # Inverse "mod 2**64".
inverse = unsafe_mul(inverse, unsafe_sub(2, unsafe_mul(denominator_div, inverse))) # Inverse "mod 2**128".
inverse = unsafe_mul(inverse, unsafe_sub(2, unsafe_mul(denominator_div, inverse))) # Inverse "mod 2**256".
# Since the division is now exact, we can divide by multiplying
# with the modular inverse of the denominator. This returns the
# correct result modulo "2**256". Since the preconditions guarantee
# that the result is less than "2**256", this is the final result.
# We do not need to calculate the high bits of the result and
# `prod1` is no longer necessary.
result: uint256 = unsafe_mul(prod0, inverse)
if roundup and uint256_mulmod(x, y, denominator) != empty(uint256):
# Calculate "ceil((x * y) / denominator)". The following
# line uses intentionally checked arithmetic to prevent
# a theoretically possible overflow.
result += 1
return result
@internal
@pure
def _log2(x: uint256, roundup: bool) -> uint256:
"""
@dev Returns the log in base 2 of `x`, following the selected
rounding direction.
@notice Note that it returns `0` if given `0`. The implementation
is inspired by OpenZeppelin's implementation here:
https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/Math.sol.
@param x The 32-byte variable.
@param roundup The Boolean variable that specifies whether
to round up or not. The default `False` is round down.
@return uint256 The 32-byte calculation result.
"""
# For the special case `x == 0`, we already return `0` here in order
# not to iterate through the remaining code.
if x == empty(uint256):
return empty(uint256)
value: uint256 = x
result: uint256 = empty(uint256)
# The following lines cannot overflow because we have the well-known
# decay behaviour of `log2(max_value(uint256)) < max_value(uint256)`.
if x >> 128 != empty(uint256):
x >>= 128
result = 128
if x >> 64 != empty(uint256):
x >>= 64
result = unsafe_add(result, 64)
if x >> 32 != empty(uint256):
x >>= 32
result = unsafe_add(result, 32)
if x >> 16 != empty(uint256):
x >>= 16
result = unsafe_add(result, 16)
if x >> 8 != empty(uint256):
x >>= 8
result = unsafe_add(result, 8)
if x >> 4 != empty(uint256):
x >>= 4
result = unsafe_add(result, 4)
if x >> 2 != empty(uint256):
x >>= 2
result = unsafe_add(result, 2)
if x >> 1 != empty(uint256):
result = unsafe_add(result, 1)
if roundup and (1 << result) < value:
result = unsafe_add(result, 1)
return result
@internal
@pure
def _log10(x: uint256, roundup: bool) -> uint256:
"""
@dev Returns the log in base 10 of `x`, following the selected
rounding direction.
@notice Note that it returns `0` if given `0`. The implementation
is inspired by OpenZeppelin's implementation here:
https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/Math.sol.
@param x The 32-byte variable.
@param roundup The Boolean variable that specifies whether
to round up or not. The default `False` is round down.
@return uint256 The 32-byte calculation result.
"""
# For the special case `x == 0`, we already return `0` here in order
# not to iterate through the remaining code.
if x == empty(uint256):
return empty(uint256)
value: uint256 = x
result: uint256 = empty(uint256)
# The following lines cannot overflow because we have the well-known
# decay behaviour of `log10(max_value(uint256)) < max_value(uint256)`.
if x >= 10 ** 64:
x = unsafe_div(x, 10 ** 64)
result = 64
if x >= 10 ** 32:
x = unsafe_div(x, 10 ** 32)
result = unsafe_add(result, 32)
if x >= 10 ** 16:
x = unsafe_div(x, 10 ** 16)
result = unsafe_add(result, 16)
if x >= 10 ** 8:
x = unsafe_div(x, 10 ** 8)
result = unsafe_add(result, 8)
if x >= 10 ** 4:
x = unsafe_div(x, 10 ** 4)
result = unsafe_add(result, 4)
if x >= 10 ** 2:
x = unsafe_div(x, 10 ** 2)
result = unsafe_add(result, 2)
if x >= 10:
result = unsafe_add(result, 1)
if roundup and (10 ** result) < value:
result = unsafe_add(result, 1)
return result
@internal
@pure
def _log256(x: uint256, roundup: bool) -> uint256:
"""
@dev Returns the log in base 256 of `x`, following the selected
rounding direction.
@notice Note that it returns `0` if given `0`. Also, adding one to the
rounded down result gives the number of pairs of hex symbols
needed to represent `x` as a hex string. The implementation is
inspired by OpenZeppelin's implementation here:
https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/Math.sol.
@param x The 32-byte variable.
@param roundup The Boolean variable that specifies whether
to round up or not. The default `False` is round down.
@return uint256 The 32-byte calculation result.
"""
# For the special case `x == 0`, we already return `0` here in order
# not to iterate through the remaining code.
if x == empty(uint256):
return empty(uint256)
value: uint256 = x
result: uint256 = empty(uint256)
# The following lines cannot overflow because we have the well-known
# decay behaviour of `log256(max_value(uint256)) < max_value(uint256)`.
if x >> 128 != empty(uint256):
x >>= 128
result = 16
if x >> 64 != empty(uint256):
x >>= 64
result = unsafe_add(result, 8)
if x >> 32 != empty(uint256):
x >>= 32
result = unsafe_add(result, 4)
if x >> 16 != empty(uint256):
x >>= 16
result = unsafe_add(result, 2)
if x >> 8 != empty(uint256):
result = unsafe_add(result, 1)
if roundup and (1 << (result << 3)) < value:
result = unsafe_add(result, 1)
return result
@internal
@pure
def _wad_ln(x: int256) -> int256:
"""
@dev Calculates the natural logarithm of a signed integer with a
precision of 1e18.
@notice Note that it returns `0` if given `0`. Furthermore, this function
consumes about 1,400 to 1,650 gas units depending on the value
of `x`. The implementation is inspired by Remco Bloemen's
implementation under the MIT license here:
https://xn--2-umb.com/22/exp-ln.
@param x The 32-byte variable.
@return int256 The 32-byte calculation result.
"""
assert x >= empty(int256), "math: wad_ln undefined"
# For the special case `x == 0`, we already return `0` here in order
# not to iterate through the remaining code.
if x == empty(int256):
return empty(int256)
# We want to convert `x` from "10**18" fixed point to "2**96"
# fixed point. We do this by multiplying by "2**96 / 10**18".
# But since "ln(x * C) = ln(x) + ln(C)" holds, we can just do
# nothing here and add "ln(2**96 / 10**18)" at the end.
# Reduce the range of `x` to "(1, 2) * 2**96".
# Also remember that "ln(2**k * x) = k * ln(2) + ln(x)" holds.
k: int256 = unsafe_sub(convert(self._log2(convert(x, uint256), False), int256), 96)
# Note that to circumvent Vyper's safecast feature for the potentially
# negative expression `x <<= uint256(159 - k)`, we first convert the
# expression `x <<= uint256(159 - k)` to `bytes32` and subsequently
# to `uint256`. Remember that the EVM default behaviour is to use two's
# complement representation to handle signed integers.
x = convert(convert(convert(x << convert(unsafe_sub(159, k), uint256), bytes32), uint256) >> 159, int256)
# Evaluate using a "(8, 8)"-term rational approximation. Since `p` is monic,
# we will multiply by a scaling factor later.
p: int256 = unsafe_add(
unsafe_mul(unsafe_add(x, 3_273_285_459_638_523_848_632_254_066_296), x) >> 96,
24_828_157_081_833_163_892_658_089_445_524,
)
p = unsafe_add(unsafe_mul(p, x) >> 96, 43_456_485_725_739_037_958_740_375_743_393)
p = unsafe_sub(unsafe_mul(p, x) >> 96, 11_111_509_109_440_967_052_023_855_526_967)
p = unsafe_sub(unsafe_mul(p, x) >> 96, 45_023_709_667_254_063_763_336_534_515_857)
p = unsafe_sub(unsafe_mul(p, x) >> 96, 14_706_773_417_378_608_786_704_636_184_526)
p = unsafe_sub(unsafe_mul(p, x), 795_164_235_651_350_426_258_249_787_498 << 96)
# We leave `p` in the "2**192" base so that we do not have to scale it up
# again for the division. Note that `q` is monic by convention.
q: int256 = unsafe_add(
unsafe_mul(unsafe_add(x, 5_573_035_233_440_673_466_300_451_813_936), x) >> 96,
71_694_874_799_317_883_764_090_561_454_958,
)
q = unsafe_add(unsafe_mul(q, x) >> 96, 283_447_036_172_924_575_727_196_451_306_956)
q = unsafe_add(unsafe_mul(q, x) >> 96, 401_686_690_394_027_663_651_624_208_769_553)
q = unsafe_add(unsafe_mul(q, x) >> 96, 204_048_457_590_392_012_362_485_061_816_622)
q = unsafe_add(unsafe_mul(q, x) >> 96, 31_853_899_698_501_571_402_653_359_427_138)
q = unsafe_add(unsafe_mul(q, x) >> 96, 909_429_971_244_387_300_277_376_558_375)
# It is known that the polynomial `q` has no zeros in the domain.
# No scaling is required, as `p` is already "2**96" too large. Also,
# `r` is in the range "(0, 0.125) * 2**96" after the division.
r: int256 = unsafe_div(p, q)
# To finalise the calculation, we have to proceed with the following steps:
# - multiply by the scaling factor "s = 5.549...",
# - add "ln(2**96 / 10**18)",
# - add "k * ln(2)", and
# - multiply by "10**18 / 2**96 = 5**18 >> 78".
# In order to perform the most gas-efficient calculation, we carry out all
# these steps in one expression.
return (
unsafe_add(
unsafe_add(
unsafe_mul(r, 1_677_202_110_996_718_588_342_820_967_067_443_963_516_166),
unsafe_mul(
k, 16_597_577_552_685_614_221_487_285_958_193_947_469_193_820_559_219_878_177_908_093_499_208_371
),
),
600_920_179_829_731_861_736_702_779_321_621_459_595_472_258_049_074_101_567_377_883_020_018_308,
)
>> 174
)
@internal
@pure
def _wad_exp(x: int256) -> int256:
"""
@dev Calculates the natural exponential function of a signed integer with
a precision of 1e18.
@notice Note that this function consumes about 810 gas units. The implementation
is inspired by Remco Bloemen's implementation under the MIT license here:
https://xn--2-umb.com/22/exp-ln.
@param x The 32-byte variable.
@return int256 The 32-byte calculation result.
"""
# If the result is `< 1`, we return zero. This happens when we have the following:
# "x <= (log(1e-18) * 1e18) ~ -4.15e19".
if x <= -41_446_531_673_892_822_313:
return empty(int256)
# When the result is "> (2**255 - 1) / 1e18" we cannot represent it as a signed integer.
# This happens when "x >= floor(log((2**255 - 1) / 1e18) * 1e18) ~ 135".
assert x < 135_305_999_368_893_231_589, "math: wad_exp overflow"
# `x` is now in the range "(-42, 136) * 1e18". Convert to "(-42, 136) * 2**96" for higher
# intermediate precision and a binary base. This base conversion is a multiplication with
# "1e18 / 2**96 = 5**18 / 2**78".
x = unsafe_div(x << 78, 5 ** 18)
# Reduce the range of `x` to "(-½ ln 2, ½ ln 2) * 2**96" by factoring out powers of two
# so that "exp(x) = exp(x') * 2**k", where `k` is a signer integer. Solving this gives
# "k = round(x / log(2))" and "x' = x - k * log(2)". Thus, `k` is in the range "[-61, 195]".
k: int256 = unsafe_add(unsafe_div(x << 96, 54_916_777_467_707_473_351_141_471_128), 2 ** 95) >> 96
x = unsafe_sub(x, unsafe_mul(k, 54_916_777_467_707_473_351_141_471_128))
# Evaluate using a "(6, 7)"-term rational approximation. Since `p` is monic,
# we will multiply by a scaling factor later.
y: int256 = unsafe_add(
unsafe_mul(unsafe_add(x, 1_346_386_616_545_796_478_920_950_773_328), x) >> 96,
57_155_421_227_552_351_082_224_309_758_442,
)
p: int256 = unsafe_add(
unsafe_mul(
unsafe_add(
unsafe_mul(unsafe_sub(unsafe_add(y, x), 94_201_549_194_550_492_254_356_042_504_812), y) >> 96,
28_719_021_644_029_726_153_956_944_680_412_240,
),
x,
),
4_385_272_521_454_847_904_659_076_985_693_276 << 96,
)
# We leave `p` in the "2**192" base so that we do not have to scale it up
# again for the division.
q: int256 = unsafe_add(
unsafe_mul(unsafe_sub(x, 2_855_989_394_907_223_263_936_484_059_900), x) >> 96,
50_020_603_652_535_783_019_961_831_881_945,
)
q = unsafe_sub(unsafe_mul(q, x) >> 96, 533_845_033_583_426_703_283_633_433_725_380)
q = unsafe_add(unsafe_mul(q, x) >> 96, 3_604_857_256_930_695_427_073_651_918_091_429)
q = unsafe_sub(unsafe_mul(q, x) >> 96, 14_423_608_567_350_463_180_887_372_962_807_573)
q = unsafe_add(unsafe_mul(q, x) >> 96, 26_449_188_498_355_588_339_934_803_723_976_023)
# The polynomial `q` has no zeros in the range because all its roots are complex.
# No scaling is required, as `p` is already "2**96" too large. Also,
# `r` is in the range "(0.09, 0.25) * 2**96" after the division.
r: int256 = unsafe_div(p, q)
# To finalise the calculation, we have to multiply `r` by:
# - the scale factor "s = ~6.031367120",
# - the factor "2**k" from the range reduction, and
# - the factor "1e18 / 2**96" for the base conversion.
# We do this all at once, with an intermediate result in "2**213" base,
# so that the final right shift always gives a positive value.
# Note that to circumvent Vyper's safecast feature for the potentially
# negative parameter value `r`, we first convert `r` to `bytes32` and
# subsequently to `uint256`. Remember that the EVM default behaviour is
# to use two's complement representation to handle signed integers.
return convert(
unsafe_mul(
convert(convert(r, bytes32), uint256), 3_822_833_074_963_236_453_042_738_258_902_158_003_155_416_615_667
)
>> convert(unsafe_sub(195, k), uint256),
int256,
)
@internal
@pure
def _cbrt(x: uint256, roundup: bool) -> uint256:
"""
@dev Calculates the cube root of an unsigned integer.
@notice Note that this function consumes about 1,600 to 1,800 gas units
depending on the value of `x` and `roundup`. The implementation is
inspired by Curve Finance's implementation under the MIT license here:
https://github.com/curvefi/tricrypto-ng/blob/main/contracts/main/CurveCryptoMathOptimized3.vy.
@param x The 32-byte variable from which the cube root is calculated.
@param roundup The Boolean variable that specifies whether
to round up or not. The default `False` is round down.
@return The 32-byte cube root of `x`.
"""
# For the special case `x == 0`, we already return `0` here in order
# not to iterate through the remaining code.
if x == empty(uint256):
return empty(uint256)
y: uint256 = unsafe_div(self._wad_cbrt(x), 10 ** 12)
if roundup and unsafe_mul(unsafe_mul(y, y), y) != x:
y = unsafe_add(y, 1)
return y
@internal
@pure
def _wad_cbrt(x: uint256) -> uint256:
"""
@dev Calculates the cube root of an unsigned integer with a precision
of 1e18.
@notice Note that this function consumes about 1,500 to 1,700 gas units
depending on the value of `x`. The implementation is inspired
by Curve Finance's implementation under the MIT license here:
https://github.com/curvefi/tricrypto-ng/blob/main/contracts/main/CurveCryptoMathOptimized3.vy.
@param x The 32-byte variable from which the cube root is calculated.
@return The 32-byte cubic root of `x` with a precision of 1e18.
"""
# For the special case `x == 0`, we already return `0` here in order
# not to iterate through the remaining code.
if x == empty(uint256):
return empty(uint256)
# Since this cube root is for numbers with base 1e18, we have to scale
# the input by 1e36 to increase the precision. This leads to an overflow
# for very large numbers. So we conditionally sacrifice precision.
value: uint256 = empty(uint256)
if x >= unsafe_mul(unsafe_div(max_value(uint256), 10 ** 36), 10 ** 18):
value = x
elif x >= unsafe_div(max_value(uint256), 10 ** 36):
value = unsafe_mul(x, 10 ** 18)
else:
value = unsafe_mul(x, 10 ** 36)
# Compute the binary logarithm of `value`.
log2x: uint256 = self._log2(value, False)
# If we divide log2x by 3, the remainder is "log2x % 3". So if we simply
# multiply "2**(log2x/3)" and discard the remainder to calculate our guess,
# the Newton-Raphson method takes more iterations to converge to a solution
# because it lacks this precision. A few more calculations now in order to
# do fewer calculations later:
# - "pow = log2(x) // 3" (the operator `//` means integer division),
# - "remainder = log2(x) % 3",
# - "initial_guess = 2**pow * cbrt(2)**remainder".
# Now substituting "2 = 1.26 ≈ 1,260 / 1,000", we get:
# - "initial_guess = 2**pow * 1,260**remainder // 1,000**remainder".
remainder: uint256 = log2x % 3
y: uint256 = unsafe_div(
unsafe_mul(pow_mod256(2, unsafe_div(log2x, 3)), pow_mod256(1_260, remainder)), pow_mod256(1_000, remainder)
)
# Since we have chosen good initial values for the cube roots, 7 Newton-Raphson
# iterations are just sufficient. 6 iterations would lead to non-convergences,
# and 8 would be one iteration too many. Without initial values, the iteration
# number can be up to 20 or more. The iterations are unrolled. This reduces the
# gas cost, but requires more bytecode.
y = unsafe_div(unsafe_add(unsafe_mul(2, y), unsafe_div(value, unsafe_mul(y, y))), 3)
y = unsafe_div(unsafe_add(unsafe_mul(2, y), unsafe_div(value, unsafe_mul(y, y))), 3)
y = unsafe_div(unsafe_add(unsafe_mul(2, y), unsafe_div(value, unsafe_mul(y, y))), 3)
y = unsafe_div(unsafe_add(unsafe_mul(2, y), unsafe_div(value, unsafe_mul(y, y))), 3)
y = unsafe_div(unsafe_add(unsafe_mul(2, y), unsafe_div(value, unsafe_mul(y, y))), 3)
y = unsafe_div(unsafe_add(unsafe_mul(2, y), unsafe_div(value, unsafe_mul(y, y))), 3)
y = unsafe_div(unsafe_add(unsafe_mul(2, y), unsafe_div(value, unsafe_mul(y, y))), 3)
# Since we scaled up, we have to scale down accordingly.
if x >= unsafe_mul(unsafe_div(max_value(uint256), 10 ** 36), 10 ** 18):
return unsafe_mul(y, 10 ** 12)
elif x >= unsafe_div(max_value(uint256), 10 ** 36):
return unsafe_mul(y, 10 ** 6)
return y
Compiler settingsShow
{
"evmVersion": "cancun"
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.