Verified contractPartial
Vault
Address0xd0d347e14fbf1872affeacb49d0b8b7182680e6c
- Balance
0 ETH
- Transactions
222
- Compiler
vyper 0.4.3
- Same code
3 more contracts
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
15 files
- curve_stablecoin/lending/Vault.vymain21.58 KB
- curve_stablecoin/constants.vy942 B
- curve_stablecoin/interfaces/IAMM.vyi3.84 KB
- curve_stablecoin/interfaces/IController.vyi5.8 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/interfaces/IERC4626.vyi1.37 KB
- curve_std/token.vy643 B
- snekmate/utils/math.vy28.12 KB
curve_stablecoin/lending/Vault.vy
# pragma version 0.4.3
# pragma optimize codesize
# pragma nonreentrancy on
"""
@title LlamaLend Vault
@notice ERC4626+ Vault for lending using LLAMMA algorithm
@author Curve.Fi
@license Copyright (c) Curve.Fi, 2020-2025 - all rights reserved
@custom:security [email protected]
@custom:kill Set max_supply to 0 via set_max_supply() to prevent new deposits. Existing positions can still be withdrawn.
"""
from curve_std.interfaces import IERC20
from curve_std.interfaces import IERC4626
from curve_stablecoin.interfaces import IAMM
from curve_stablecoin.interfaces import IController
from curve_stablecoin.interfaces import ILendController
from curve_stablecoin.interfaces import IFactory
from curve_stablecoin.interfaces import IVault
from curve_stablecoin import constants as c
from curve_std import token as tkn
from curve_std import crv_math
from snekmate.utils import math
implements: IERC20
implements: IERC4626
implements: IVault
# These are virtual shares from method proposed by OpenZeppelin
# see: https://blog.openzeppelin.com/a-novel-defense-against-erc4626-inflation-attacks
# and
# https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/extensions/ERC4626.sol
# redeclaration here is because: https://github.com/vyperlang/vyper/issues/4723
DEAD_SHARES: constant(uint256) = c.DEAD_SHARES
MIN_ASSETS: constant(uint256) = 10000
_borrowed_token: IERC20
# https://github.com/vyperlang/vyper/issues/4721
@external
@view
@reentrant
def borrowed_token() -> IERC20:
return self._borrowed_token
_collateral_token: IERC20
# https://github.com/vyperlang/vyper/issues/4721
@external
@view
@reentrant
def collateral_token() -> IERC20:
return self._collateral_token
_amm: IAMM
# https://github.com/vyperlang/vyper/issues/4721
@external
@view
@reentrant
def amm() -> IAMM:
return self._amm
_controller: IController
# https://github.com/vyperlang/vyper/issues/4721
@external
@view
@reentrant
def controller() -> IController:
return self._controller
_factory: IFactory
# https://github.com/vyperlang/vyper/issues/4721
@external
@view
@reentrant
def factory() -> IFactory:
return self._factory
maxSupply: public(reentrant(uint256))
# ERC20 publics
decimals: public(constant(uint8)) = 18
name: public(reentrant(String[64]))
symbol: public(reentrant(String[34]))
NAME_PREFIX: constant(String[16]) = 'Curve Vault for '
SYMBOL_PREFIX: constant(String[2]) = 'cv'
allowance: public(reentrant(HashMap[address, HashMap[address, uint256]]))
balanceOf: public(reentrant(HashMap[address, uint256]))
totalSupply: public(reentrant(uint256))
precision: uint256
@external
@reentrant
def initialize(
_amm: IAMM,
_controller: IController,
_borrowed_token: IERC20,
_collateral_token: IERC20,
):
"""
@notice Initializer for vaults
@param _amm Address of the AMM
@param _controller Address of the Controller
@param _borrowed_token Token which is being borrowed
@param _collateral_token Token which is being collateral
"""
assert self._borrowed_token.address == empty(address)
self._borrowed_token = _borrowed_token
borrowed_precision: uint256 = 10**(18 - convert(staticcall _borrowed_token.decimals(), uint256))
self._collateral_token = _collateral_token
self._factory = IFactory(msg.sender)
self._amm = _amm
self._controller = _controller
# ERC20 set up
self.precision = borrowed_precision
borrowed_symbol: String[32] = staticcall _borrowed_token.symbol()
self.name = concat(NAME_PREFIX, borrowed_symbol)
# Symbol must be String[32], but we do String[34]. It doesn't affect contracts which read it (they will truncate)
# However this will be changed as soon as Vyper can *properly* manipulate strings
self.symbol = concat(SYMBOL_PREFIX, borrowed_symbol)
self.maxSupply = max_value(uint256)
@external
def set_max_supply(_max_supply: uint256):
"""
@notice Set maximum depositable supply
@param _max_supply New maximum supply cap in asset tokens
"""
assert msg.sender == staticcall self._factory.admin() or msg.sender == self._factory.address
self.maxSupply = _max_supply
log IVault.SetMaxSupply(max_supply=_max_supply)
@external
@view
def borrow_apr() -> uint256:
"""
@notice Borrow APR (annualized and 1e18-based)
@return Current annualized borrow rate scaled by 1e18
"""
return staticcall self._amm.rate() * (365 * 86400)
@external
@view
def lend_apr() -> uint256:
"""
@notice Lending APR (annualized and 1e18-based), net of admin fees
@return Current annualized lending rate scaled by 1e18, after admin fee deduction
"""
debt: uint256 = staticcall self._controller.total_debt()
if debt == 0:
return 0
gross_apr: uint256 = staticcall self._amm.rate() * (365 * 86400) * debt // self._total_assets()
admin_pct: uint256 = staticcall ILendController(self._controller.address).admin_percentage()
return gross_apr * (c.WAD - admin_pct) // c.WAD
@external
@view
def asset() -> IERC20:
"""
@notice Asset which is the same as borrowed_token
@return Address of the underlying asset token
"""
return self._borrowed_token
@internal
@view
def _total_assets() -> uint256:
return (
staticcall self._controller.available_balance()
+ staticcall self._controller.total_debt()
- staticcall self._controller.admin_fees()
)
@external
@view
def totalAssets() -> uint256:
"""
@notice Total assets which can be lent out or be in reserve
@return Total amount of underlying assets managed by the vault
"""
return self._total_assets()
@internal
@view
def _convert_to_shares(_assets: uint256, _is_floor: bool = True,
_total_assets: uint256 = max_value(uint256)) -> uint256:
"""
@param _assets Amount of assets to convert
@param _is_floor If True, round down; if False, round up
@param _total_assets Override for total assets; uses current value if max_value(uint256)
@return Amount of shares equivalent to `_assets`
"""
total_assets: uint256 = _total_assets
if total_assets == max_value(uint256):
total_assets = self._total_assets()
precision: uint256 = self.precision
numerator: uint256 = (self.totalSupply + DEAD_SHARES) * _assets * precision
denominator: uint256 = (total_assets * precision + 1)
if _is_floor:
return numerator // denominator
else:
return math._ceil_div(numerator, denominator)
@internal
@view
def _convert_to_assets(_shares: uint256, _is_floor: bool = True,
_total_assets: uint256 = max_value(uint256)) -> uint256:
"""
@param _shares Amount of shares to convert
@param _is_floor If True, round down; if False, round up
@param _total_assets Override for total assets; uses current value if max_value(uint256)
@return Amount of assets equivalent to `_shares`
"""
total_assets: uint256 = _total_assets
if total_assets == max_value(uint256):
total_assets = self._total_assets()
precision: uint256 = self.precision
numerator: uint256 = _shares * (total_assets * precision + 1)
denominator: uint256 = (self.totalSupply + DEAD_SHARES) * precision
if _is_floor:
return numerator // denominator
else:
return math._ceil_div(numerator, denominator)
@external
@view
def pricePerShare(_is_floor: bool = True) -> uint256:
"""
@notice Method which shows how much one pool share costs in asset tokens if they are normalized to 18 decimals
@dev pricePerShare can decrease if totalSupply reaches zero (e.g., when all shares are burned).
In this case, it resets to the initial value.
@param _is_floor If True, round down; if False, round up
@return Price of one share in asset tokens, normalized to 1e18
"""
supply: uint256 = self.totalSupply
if supply == 0:
return 10**18 // DEAD_SHARES
else:
precision: uint256 = self.precision
numerator: uint256 = 10**18 * (self._total_assets() * precision + 1)
denominator: uint256 = (supply + DEAD_SHARES)
pps: uint256 = 0
if _is_floor:
pps = numerator // denominator
else:
pps = math._ceil_div(numerator, denominator)
assert pps > 0
return pps
@external
@view
def convertToShares(_assets: uint256) -> uint256:
"""
@notice Returns the amount of shares which the Vault would exchange for the given amount of assets provided
@param _assets Amount of assets to convert
@return Amount of shares equivalent to _assets
"""
return self._convert_to_shares(_assets)
@external
@view
def convertToAssets(_shares: uint256) -> uint256:
"""
@notice Returns the amount of assets that the Vault would exchange for the amount of shares provided
@param _shares Amount of shares to convert
@return Amount of assets equivalent to _shares
"""
return self._convert_to_assets(_shares)
@external
@view
def maxDeposit(_receiver: address) -> uint256:
"""
@notice Maximum amount of assets which a given user can deposit
@param _receiver Address of the prospective depositor
@return Maximum depositable asset amount given the current supply cap
"""
max_supply: uint256 = self.maxSupply
if max_supply == max_value(uint256):
return max_supply
else:
assets: uint256 = self._total_assets()
return max(max_supply, assets) - assets
@external
@view
def previewDeposit(_assets: uint256) -> uint256:
"""
@notice Returns the amount of shares which can be obtained upon depositing assets
@param _assets Amount of assets to deposit
@return Amount of shares that would be minted for _assets
"""
return self._convert_to_shares(_assets)
@external
def deposit(_assets: uint256, _receiver: address = msg.sender) -> uint256:
"""
@notice Deposit assets in return for whatever number of shares corresponds to the current conditions
@param _assets Amount of assets to deposit
@param _receiver Receiver of the shares who is optional. If not specified - receiver is the sender
@return Amount of shares minted
"""
controller: IController = self._controller
total_assets: uint256 = self._total_assets()
assert total_assets + _assets >= MIN_ASSETS, "Need more assets"
assert total_assets + _assets <= self.maxSupply, "Supply limit"
to_mint: uint256 = self._convert_to_shares(_assets, True, total_assets)
assert to_mint > 0, "Can't mint 0 shares"
extcall ILendController(controller.address).on_borrowed_token_transfer_in(_assets)
tkn.transfer_from(self._borrowed_token, msg.sender, controller.address, _assets)
self._mint(_receiver, to_mint)
extcall controller.save_rate()
log IERC4626.Deposit(sender=msg.sender, owner=_receiver, assets=_assets, shares=to_mint)
return to_mint
@external
@view
def maxMint(_receiver: address) -> uint256:
"""
@notice Return maximum amount of shares which a given user can mint
@param _receiver Address of the prospective minter
@return Maximum mintable share amount given the current supply cap
"""
max_supply: uint256 = self.maxSupply
if max_supply == max_value(uint256):
return max_supply
else:
assets: uint256 = self._total_assets()
return self._convert_to_shares(max(max_supply, assets) - assets)
@external
@view
def previewMint(_shares: uint256) -> uint256:
"""
@notice Calculate the amount of assets which is needed to exactly mint the given amount of shares
@param _shares Number of shares to mint
@return Amount of assets required to mint exactly _shares
"""
return self._convert_to_assets(_shares, False)
@external
def mint(_shares: uint256, _receiver: address = msg.sender) -> uint256:
"""
@notice Mint given amount of shares taking whatever number of assets it requires
@param _shares Number of shares to mint
@param _receiver Optional receiver for the shares. If not specified - it's the sender
@return Amount of assets taken from the caller
"""
assert _shares > 0, "Can't mint 0 shares"
controller: IController = self._controller
total_assets: uint256 = self._total_assets()
assets: uint256 = self._convert_to_assets(_shares, False, total_assets)
assert total_assets + assets >= MIN_ASSETS, "Need more assets"
assert total_assets + assets <= self.maxSupply, "Supply limit"
extcall ILendController(controller.address).on_borrowed_token_transfer_in(assets)
tkn.transfer_from(self._borrowed_token, msg.sender, controller.address, assets)
self._mint(_receiver, _shares)
extcall controller.save_rate()
log IERC4626.Deposit(sender=msg.sender, owner=_receiver, assets=assets, shares=_shares)
return assets
@internal
@view
def _available_balance() -> uint256:
return crv_math.sub_or_zero(
staticcall self._controller.available_balance(),
staticcall self._controller.admin_fees(),
)
@external
@view
def maxWithdraw(_owner: address) -> uint256:
"""
@notice Maximum amount of assets which a given user can withdraw. Aware of both user's balance and available liquidity
@param _owner Address of the share owner
@return Maximum withdrawable asset amount
"""
return min(
self._convert_to_assets(self.balanceOf[_owner]),
self._available_balance(),
)
@external
@view
def previewWithdraw(_assets: uint256) -> uint256:
"""
@notice Calculate number of shares which gets burned when withdrawing given amount of asset
@param _assets Amount of assets to withdraw
@return Number of shares that would be burned for _assets
"""
return self._convert_to_shares(_assets, False)
@external
def withdraw(_assets: uint256, _receiver: address = msg.sender, _owner: address = msg.sender) -> uint256:
"""
@notice Withdraw given amount of asset and burn the corresponding amount of vault shares
@param _assets Amount of assets to withdraw
@param _receiver Receiver of the assets (optional, sender if not specified)
@param _owner Owner who's shares the caller takes. Only can take those if owner gave the approval to the sender. Optional
@return Number of shares burned
"""
total_assets: uint256 = self._total_assets()
assert total_assets - _assets >= MIN_ASSETS or total_assets == _assets, "Need more assets"
shares: uint256 = self._convert_to_shares(_assets, False, total_assets)
if _owner != msg.sender:
allowance: uint256 = self.allowance[_owner][msg.sender]
if allowance != max_value(uint256):
self._approve(_owner, msg.sender, allowance - shares)
controller: IController = self._controller
self._burn(_owner, shares)
extcall ILendController(controller.address).on_borrowed_token_transfer_out(_assets)
tkn.transfer_from(self._borrowed_token, controller.address, _receiver, _assets)
extcall controller.save_rate()
log IERC4626.Withdraw(sender=msg.sender, receiver=_receiver, owner=_owner, assets=_assets, shares=shares)
return shares
@external
@view
def maxRedeem(_owner: address) -> uint256:
"""
@notice Calculate maximum amount of shares which a given user can redeem
@param _owner Address of the share owner
@return Maximum redeemable share amount given the owner's balance and available liquidity
"""
return min(
self._convert_to_shares(self._available_balance(), False),
self.balanceOf[_owner],
)
@external
@view
def previewRedeem(_shares: uint256) -> uint256:
"""
@notice Calculate the amount of assets which can be obtained by redeeming the given amount of shares
@param _shares Amount of shares to redeem
@return Amount of assets that would be received for _shares
"""
return self._convert_to_assets(_shares)
@external
def redeem(_shares: uint256, _receiver: address = msg.sender, _owner: address = msg.sender) -> uint256:
"""
@notice Burn given amount of shares and give corresponding assets to the user
@param _shares Amount of shares to burn
@param _receiver Optional receiver of the assets
@param _owner Optional owner of the shares. Can only redeem if owner gave approval to the sender
@return Amount of assets sent to the receiver
"""
if _owner != msg.sender:
allowance: uint256 = self.allowance[_owner][msg.sender]
if allowance != max_value(uint256):
self._approve(_owner, msg.sender, allowance - _shares)
total_assets: uint256 = self._total_assets()
assets_to_redeem: uint256 = self._convert_to_assets(_shares, True, total_assets)
assert total_assets - assets_to_redeem >= MIN_ASSETS or total_assets == assets_to_redeem, "Need more assets"
self._burn(_owner, _shares)
controller: IController = self._controller
extcall ILendController(controller.address).on_borrowed_token_transfer_out(assets_to_redeem)
tkn.transfer_from(self._borrowed_token, controller.address, _receiver, assets_to_redeem)
extcall controller.save_rate()
log IERC4626.Withdraw(sender=msg.sender, receiver=_receiver, owner=_owner, assets=assets_to_redeem, shares=_shares)
return assets_to_redeem
# ERC20 methods
@internal
def _approve(_owner: address, _spender: address, _value: uint256):
self.allowance[_owner][_spender] = _value
log IERC20.Approval(owner=_owner, spender=_spender, value=_value)
@internal
def _burn(_from: address, _value: uint256):
self.balanceOf[_from] -= _value
self.totalSupply -= _value
log IERC20.Transfer(sender=_from, receiver=empty(address), value=_value)
@internal
def _mint(_to: address, _value: uint256):
self.balanceOf[_to] += _value
self.totalSupply += _value
log IERC20.Transfer(sender=empty(address), receiver=_to, value=_value)
@internal
def _transfer(_from: address, _to: address, _value: uint256):
assert _to not in [self, empty(address)]
self.balanceOf[_from] -= _value
self.balanceOf[_to] += _value
log IERC20.Transfer(sender=_from, receiver=_to, value=_value)
@external
def transferFrom(_from: address, _to: address, _value: uint256) -> bool:
"""
@notice Transfer tokens from one account to another.
@dev The caller needs to have an allowance from account `_from` greater than or
equal to the value being transferred. An allowance equal to the uint256 type's
maximum, is considered infinite and does not decrease.
@param _from The account which tokens will be spent from.
@param _to The account which tokens will be sent to.
@param _value The amount of tokens to be transferred.
@return True on success
"""
allowance: uint256 = self.allowance[_from][msg.sender]
if allowance != max_value(uint256):
self._approve(_from, msg.sender, allowance - _value)
self._transfer(_from, _to, _value)
return True
@external
def transfer(_to: address, _value: uint256) -> bool:
"""
@notice Transfer tokens to `_to`.
@param _to The account to transfer tokens to.
@param _value The amount of tokens to transfer.
@return True on success
"""
self._transfer(msg.sender, _to, _value)
return True
@external
def approve(_spender: address, _value: uint256) -> bool:
"""
@notice Allow `_spender` to transfer up to `_value` amount of tokens from the caller's account.
@dev Non-zero to non-zero approvals are allowed, but should be used cautiously. The methods
increaseAllowance + decreaseAllowance are available to prevent any front-running that
may occur.
@param _spender The account permitted to spend up to `_value` amount of caller's funds.
@param _value The amount of tokens `_spender` is allowed to spend.
@return True on success
"""
self._approve(msg.sender, _spender, _value)
return True
@external
def increaseAllowance(_spender: address, _add_value: uint256) -> bool:
"""
@notice Increase the allowance granted to `_spender`.
@dev This function will never overflow, and instead will bound
allowance to MAX_UINT256. This has the potential to grant an
infinite approval.
@param _spender The account to increase the allowance of.
@param _add_value The amount to increase the allowance by.
@return True on success
"""
cached_allowance: uint256 = self.allowance[msg.sender][_spender]
allowance: uint256 = unsafe_add(cached_allowance, _add_value)
# check for an overflow
if allowance < cached_allowance:
allowance = max_value(uint256)
if allowance != cached_allowance:
self._approve(msg.sender, _spender, allowance)
return True
@external
def decreaseAllowance(_spender: address, _sub_value: uint256) -> bool:
"""
@notice Decrease the allowance granted to `_spender`.
@dev This function will never underflow, and instead will bound
allowance to 0.
@param _spender The account to decrease the allowance of.
@param _sub_value The amount to decrease the allowance by.
@return True on success
"""
cached_allowance: uint256 = self.allowance[msg.sender][_spender]
allowance: uint256 = unsafe_sub(cached_allowance, _sub_value)
# check for an underflow
if cached_allowance < allowance:
allowance = 0
if allowance != cached_allowance:
self._approve(msg.sender, _spender, allowance)
return True
@external
@view
def admin() -> address:
return staticcall self._factory.admin()
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/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/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 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/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/interfaces/IERC4626.vyi
# pragma version 0.4.3
from curve_std.interfaces import IERC20
# Events
event Deposit:
sender: indexed(address)
owner: indexed(address)
assets: uint256
shares: uint256
event Withdraw:
sender: indexed(address)
receiver: indexed(address)
owner: indexed(address)
assets: uint256
shares: uint256
# Functions
@view
def asset() -> IERC20:
...
@view
def totalAssets() -> uint256:
...
@view
def convertToShares(assetAmount: uint256) -> uint256:
...
@view
def convertToAssets(shareAmount: uint256) -> uint256:
...
@view
def maxDeposit(recipient: address) -> uint256:
...
@view
def previewDeposit(assets: uint256) -> uint256:
...
def deposit(assets: uint256, receiver: address) -> uint256:
...
@view
def maxMint(recipient: address) -> uint256:
...
@view
def previewMint(shares: uint256) -> uint256:
...
def mint(shares: uint256, receiver: address) -> uint256:
...
@view
def maxWithdraw(owner: address) -> uint256:
...
@view
def previewWithdraw(assets: uint256) -> uint256:
...
def withdraw(assets: uint256, receiver: address, owner: address) -> uint256:
...
@view
def maxRedeem(owner: address) -> uint256:
...
@view
def previewRedeem(shares: uint256) -> uint256:
...
def redeem(shares: uint256, receiver: address, owner: address) -> uint256:
...
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.