keeper

package
v4.2.0-rc1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 14, 2023 License: Apache-2.0 Imports: 20 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ApproxExponential

func ApproxExponential(x sdk.Dec) sdk.Dec

ApproxExponential is the taylor series expansion of e^x centered around x=0, truncated to the cubic term. It can be used with great accuracy to determine e^x when x is very small. Note that e^x = 1 + x/1! + x^2/2! + x^3 / 3! + ...

func BorrowAPYInvariant

func BorrowAPYInvariant(k Keeper) sdk.Invariant

BorrowAPYInvariant checks that Borrow APY have all positive values

func ComputeCloseFactor

func ComputeCloseFactor(
	borrowedValue sdk.Dec,
	collateralValue sdk.Dec,
	liquidationThreshold sdk.Dec,
	smallLiquidationSize sdk.Dec,
	minimumCloseFactor sdk.Dec,
	completeLiquidationThreshold sdk.Dec,
) (closeFactor sdk.Dec)

ComputeCloseFactor derives the maximum portion of a borrower's current borrowedValue that can currently be repaid in a single liquidate transaction.

closeFactor scales linearly between minimumCloseFactor and 1.0, reaching its maximum when borrowedValue has reached a critical value between liquidationThreshold to collateralValue. This critical value is defined as:

B = critical borrowedValue
C = collateralValue
L = liquidationThreshold
CLT = completeLiquidationThreshold

B = L + (C-L) * CLT

closeFactor is zero for borrowers that are not eligible for liquidation, i.e. borrowedValue < liquidationThreshold

Finally, if borrowedValue is less than smallLiquidationSize, closeFactor will always be 1 as long as the borrower is eligible for liquidation.

func ComputeLiquidation

func ComputeLiquidation(
	availableRepay,
	availableCollateral,
	availableReward sdkmath.Int,
	priceRatio,
	uTokenExchangeRate,
	liquidationIncentive sdk.Dec,
) (tokenRepay sdkmath.Int, collateralBurn sdkmath.Int, tokenReward sdkmath.Int)

ComputeLiquidation takes the conditions preceding a liquidation and outputs the amounts of base token that should be repaid, collateral uToken burned, and reward token allocated as a result of the transaction, after accounting for limiting factors with as little rounding as possible. Inputs are as follows: - availableRepay: The lowest (in repay denom) of either liquidator balance, max repayment, or borrowed amount. - availableCollateral: The amount of the reward uToken denom which borrower has as collateral - availableReward: The amount of unreserved reward tokens in the module balance - priceRatio: The ratio of repayPrice / rewardPrice, which is used when computing rewards - uTokenExchangeRate: The uToken exchange rate from collateral uToken denom to reward base denom - liquidationIncentive: The liquidation incentive of the token reward denomination

func ExchangeRatesInvariant

func ExchangeRatesInvariant(k Keeper) sdk.Invariant

ExchangeRatesInvariant checks that all denoms have an uToken exchange rate >= 1

func InefficientBorrowAmountInvariant

func InefficientBorrowAmountInvariant(k Keeper) sdk.Invariant

InefficientBorrowAmountInvariant checks that borrow amounts have all positive values This runs in O(N) time where N is the number of participating addresses, so it should not be enabled in production.

func InefficientCollateralAmountInvariant

func InefficientCollateralAmountInvariant(k Keeper) sdk.Invariant

InefficientCollateralAmountInvariant checks that collateral amounts have all positive values. This runs in O(N) time where N is the number of participating addresses, so it should not be enabled in production.

func InterestScalarsInvariant

func InterestScalarsInvariant(k Keeper) sdk.Invariant

InterestScalarsInvariant checks that all denoms have an interest scalar >= 1

func Interpolate

func Interpolate(x, xMin, yMin, xMax, yMax sdk.Dec) sdk.Dec

Interpolate takes a line defined by two points (xMin, yMin) and (xMax, yMax), then finds the y-value of the point on that line for an input x-value. It will return yMin if xMin = xMax (i.e. a vertical line). While this function is intended for interpolation (xMin < x < xMax), it works correctly even when x is outside that range or when xMin > xMax.

func NewMsgServerImpl

func NewMsgServerImpl(keeper Keeper) types.MsgServer

NewMsgServerImpl returns an implementation of MsgServer for the x/leverage module.

func RegisterInvariants

func RegisterInvariants(ir sdk.InvariantRegistry, k Keeper)

RegisterInvariants registers the leverage module invariants

func ReserveAmountInvariant

func ReserveAmountInvariant(k Keeper) sdk.Invariant

ReserveAmountInvariant checks that reserve amounts have non-negative balances

func SupplyAPYInvariant

func SupplyAPYInvariant(k Keeper) sdk.Invariant

SupplyAPYInvariant checks that Supply APY have all positive values

Types

type Keeper

type Keeper struct {
	// contains filtered or unexported fields
}

func NewKeeper

func NewKeeper(
	cdc codec.Codec,
	storeKey storetypes.StoreKey,
	paramSpace paramtypes.Subspace,
	bk types.BankKeeper,
	ok types.OracleKeeper,
	enableLiquidatorQuery bool,
) Keeper

func (Keeper) AccrueAllInterest

func (k Keeper) AccrueAllInterest(ctx sdk.Context) error

AccrueAllInterest is called by EndBlock to update borrow positions. It accrues interest on all open borrows, increase reserves, funds oracle rewards, and sets LastInterestTime to BlockTime.

func (Keeper) AvailableLiquidity

func (k Keeper) AvailableLiquidity(ctx sdk.Context, denom string) sdkmath.Int

AvailableLiquidity gets the unreserved module balance of a given token.

func (Keeper) Borrow

func (k Keeper) Borrow(ctx sdk.Context, borrowerAddr sdk.AccAddress, borrow sdk.Coin) error

Borrow attempts to borrow tokens from the leverage module account using collateral uTokens. If asset type is invalid, or module balance is insufficient, we return an error. This function does NOT check that a borrower remains under their borrow limit or that collateral liquidity remains healthy - those assertions have been moved to MsgServer.

func (Keeper) CalculateBorrowLimit

func (k Keeper) CalculateBorrowLimit(ctx sdk.Context, collateral sdk.Coins) (sdk.Dec, error)

CalculateBorrowLimit uses the price oracle to determine the borrow limit (in USD) provided by collateral sdk.Coins, using each token's uToken exchange rate and collateral weight. The lower of spot price or historic price is used for each collateral token. An error is returned if any input coins are not uTokens or if value calculation fails.

func (Keeper) CalculateCollateralValue

func (k Keeper) CalculateCollateralValue(ctx sdk.Context, collateral sdk.Coins) (sdk.Dec, error)

CalculateCollateralValue uses the price oracle to determine the value (in USD) provided by collateral sdk.Coins, using each token's uToken exchange rate. Always uses spot price. An error is returned if any input coins are not uTokens or if value calculation fails.

func (Keeper) CalculateLiquidationThreshold

func (k Keeper) CalculateLiquidationThreshold(ctx sdk.Context, collateral sdk.Coins) (sdk.Dec, error)

CalculateLiquidationThreshold determines the maximum borrowed value (in USD) that a borrower with given collateral could reach before being eligible for liquidation, using each token's oracle price, uToken exchange rate, and liquidation threshold. An error is returned if any input coins are not uTokens or if value calculation fails. Always uses spot prices.

func (Keeper) CleanTokenRegistry added in v4.1.0

func (k Keeper) CleanTokenRegistry(ctx sdk.Context) error

CleanTokenRegistry deletes all blacklisted tokens in the leverage registry whose uToken supplies are zero. Called automatically on registry update.

func (Keeper) CollateralLiquidity

func (k Keeper) CollateralLiquidity(ctx sdk.Context, denom string) sdk.Dec

CollateralLiquidity calculates the current collateral liquidity of a token denom, which is defined as the token's liquidity, divided by the base token equivalent of associated uToken's total collateral. Ranges from 0 to 1.0

func (Keeper) Collateralize

func (k Keeper) Collateralize(ctx sdk.Context, borrowerAddr sdk.AccAddress, uToken sdk.Coin) error

Collateralize enables selected uTokens for use as collateral by a single borrower. This function does NOT check that collateral share and collateral liquidity remain healthy. Those assertions have been moved to MsgServer.

func (Keeper) Decollateralize

func (k Keeper) Decollateralize(ctx sdk.Context, borrowerAddr sdk.AccAddress, uToken sdk.Coin) error

Decollateralize disables selected uTokens for use as collateral by a single borrower. This function does NOT check that a borrower remains under their borrow limit. That assertion has been moved to MsgServer.

func (Keeper) DeriveBorrowAPY

func (k Keeper) DeriveBorrowAPY(ctx sdk.Context, denom string) sdk.Dec

DeriveBorrowAPY derives the current borrow interest rate on a token denom using its supply utilization and token-specific params. Returns zero on invalid asset.

func (Keeper) DeriveExchangeRate

func (k Keeper) DeriveExchangeRate(ctx sdk.Context, denom string) sdk.Dec

DeriveExchangeRate calculated the token:uToken exchange rate of a base token denom.

func (Keeper) DeriveSupplyAPY

func (k Keeper) DeriveSupplyAPY(ctx sdk.Context, denom string) sdk.Dec

DeriveSupplyAPY derives the current supply interest rate on a token denom using its supply utilization and borrow APY. Returns zero on invalid asset.

func (Keeper) ExchangeToken

func (k Keeper) ExchangeToken(ctx sdk.Context, token sdk.Coin) (sdk.Coin, error)

ExchangeToken converts an sdk.Coin containing a base asset to its value as a uToken.

func (Keeper) ExchangeUToken

func (k Keeper) ExchangeUToken(ctx sdk.Context, uToken sdk.Coin) (sdk.Coin, error)

ExchangeUToken converts an sdk.Coin containing a uToken to its value in a base token.

func (Keeper) ExchangeUTokens

func (k Keeper) ExchangeUTokens(ctx sdk.Context, uTokens sdk.Coins) (sdk.Coins, error)

ExchangeUTokens converts an sdk.Coins containing uTokens to their values in base tokens.

func (Keeper) ExportGenesis

func (k Keeper) ExportGenesis(ctx sdk.Context) *types.GenesisState

ExportGenesis returns the x/leverage module's exported genesis state.

func (Keeper) FundOracle

func (k Keeper) FundOracle(ctx sdk.Context, requested sdk.Coins) error

FundOracle transfers requested coins to the oracle module account, as long as the leverage module account has sufficient unreserved assets.

func (Keeper) GetAllRegisteredTokens

func (k Keeper) GetAllRegisteredTokens(ctx sdk.Context) []types.Token

GetAllRegisteredTokens returns all the registered tokens from the x/leverage module's KVStore.

func (Keeper) GetAllReserves

func (k Keeper) GetAllReserves(ctx sdk.Context) sdk.Coins

GetAllReserves returns all reserves.

func (Keeper) GetAllSupplied

func (k Keeper) GetAllSupplied(ctx sdk.Context, supplierAddr sdk.AccAddress) (sdk.Coins, error)

GetAllSupplied returns the total tokens supplied by a user, including any interest accrued.

func (Keeper) GetAllTotalCollateral

func (k Keeper) GetAllTotalCollateral(ctx sdk.Context) sdk.Coins

GetAllTotalCollateral returns total collateral across all uTokens.

func (Keeper) GetAllUTokenSupply

func (k Keeper) GetAllUTokenSupply(ctx sdk.Context) sdk.Coins

GetAllUTokenSupply returns total supply of all uToken denoms.

func (Keeper) GetBorrow

func (k Keeper) GetBorrow(ctx sdk.Context, borrowerAddr sdk.AccAddress, denom string) sdk.Coin

GetBorrow returns an sdk.Coin representing how much of a given denom a borrower currently owes.

func (Keeper) GetBorrowerBorrows

func (k Keeper) GetBorrowerBorrows(ctx sdk.Context, borrowerAddr sdk.AccAddress) sdk.Coins

GetBorrowerBorrows returns an sdk.Coins object containing all open borrows associated with an address.

func (Keeper) GetBorrowerCollateral

func (k Keeper) GetBorrowerCollateral(ctx sdk.Context, borrowerAddr sdk.AccAddress) sdk.Coins

GetBorrowerCollateral returns an sdk.Coins containing all of a borrower's collateral.

func (Keeper) GetCollateral

func (k Keeper) GetCollateral(ctx sdk.Context, borrowerAddr sdk.AccAddress, denom string) sdk.Coin

GetCollateral returns an sdk.Coin representing how much of a given denom the x/leverage module account currently holds as collateral for a given borrower.

func (Keeper) GetEligibleLiquidationTargets

func (k Keeper) GetEligibleLiquidationTargets(ctx sdk.Context) ([]sdk.AccAddress, error)

GetEligibleLiquidationTargets returns a list of borrower addresses eligible for liquidation.

func (Keeper) GetParams

func (k Keeper) GetParams(ctx sdk.Context) (params types.Params)

GetParams gets the x/leverage module's parameters.

func (Keeper) GetReserves

func (k Keeper) GetReserves(ctx sdk.Context, denom string) sdk.Coin

GetReserves gets the reserved amount of a specified token. On invalid asset, the reserved amount is zero.

func (Keeper) GetSupplied

func (k Keeper) GetSupplied(ctx sdk.Context, supplierAddr sdk.AccAddress, denom string) (sdk.Coin, error)

GetSupplied returns an sdk.Coin representing how much of a given denom a user has supplied, including interest accrued.

func (Keeper) GetTokenSettings

func (k Keeper) GetTokenSettings(ctx sdk.Context, denom string) (types.Token, error)

GetTokenSettings gets a token from the x/leverage module's KVStore.

func (Keeper) GetTotalBorrowed

func (k Keeper) GetTotalBorrowed(ctx sdk.Context, denom string) sdk.Coin

GetTotalBorrowed returns the total borrowed in a given denom.

func (Keeper) GetTotalCollateral

func (k Keeper) GetTotalCollateral(ctx sdk.Context, denom string) sdk.Coin

GetTotalCollateral returns an sdk.Coin representing how much of a given uToken the x/leverage module account currently holds as collateral. Non-uTokens return zero.

func (Keeper) GetTotalSupply

func (k Keeper) GetTotalSupply(ctx sdk.Context, denom string) (sdk.Coin, error)

GetTotalSupply returns the total supplied by all suppliers in a given denom, including any interest accrued.

func (Keeper) GetUTokenSupply

func (k Keeper) GetUTokenSupply(ctx sdk.Context, denom string) sdk.Coin

GetUTokenSupply gets the total supply of a specified utoken, as tracked by module state. On invalid asset or non-uToken, the supply is zero.

func (Keeper) InitGenesis

func (k Keeper) InitGenesis(ctx sdk.Context, genState types.GenesisState)

InitGenesis initializes the x/leverage module state from a provided genesis state.

func (Keeper) Liquidate

func (k Keeper) Liquidate(
	ctx sdk.Context, liquidatorAddr, borrowerAddr sdk.AccAddress, requestedRepay sdk.Coin, rewardDenom string,
) (repaid sdk.Coin, liquidated sdk.Coin, reward sdk.Coin, err error)

Liquidate attempts to repay one of an eligible borrower's borrows (in part or in full) in exchange for some of the borrower's uToken collateral or associated base tokens. If the borrower is not over their liquidation limit, or the repayment or reward denominations are invalid, an error is returned. If the attempted repayment is greater than the amount owed or the maximum that can be repaid due to parameters or available balances, then a partial liquidation, equal to the maximum valid amount, is performed. Because partial liquidation is possible and exchange rates vary, Liquidate returns the actual amount of tokens repaid, collateral liquidated, and base tokens or uTokens rewarded.

func (Keeper) Logger

func (k Keeper) Logger(ctx sdk.Context) log.Logger

func (Keeper) ModuleBalance

func (k Keeper) ModuleBalance(ctx sdk.Context, denom string) sdk.Coin

ModuleBalance returns the amount of a given token held in the x/leverage module account

func (Keeper) PriceRatio

func (k Keeper) PriceRatio(ctx sdk.Context, fromDenom, toDenom string, mode types.PriceMode) (sdk.Dec, error)

PriceRatio computes the ratio of the USD prices of two base tokens, as sdk.Dec(fromPrice/toPrice). Will return an error if either token price is not positive, and guarantees a positive output. Computation uses price of token's symbol denom to avoid rounding errors for exponent >= 18 tokens, but returns in terms of base tokens. Uses the same price mode for both token denoms involved.

func (Keeper) Repay

func (k Keeper) Repay(ctx sdk.Context, borrowerAddr sdk.AccAddress, payment sdk.Coin) (sdk.Coin, error)

Repay attempts to repay a borrow position. If asset type is invalid, account balance is insufficient, or borrower has no borrows in payment denom to repay, we return an error. Additionally, if the amount provided is greater than the full repayment amount, only the necessary amount is transferred. Because amount repaid may be less than the repayment attempted, Repay returns the actual amount repaid.

func (Keeper) RepayBadDebt

func (k Keeper) RepayBadDebt(ctx sdk.Context, borrowerAddr sdk.AccAddress, denom string) (bool, error)

RepayBadDebt uses reserves to repay borrower's debts of a given denom. It returns a boolean representing whether full repayment was achieved. This function assumes the borrower has already been verified to have no collateral remaining.

func (Keeper) SaveOrUpdateTokenSettingsToRegistry

func (k Keeper) SaveOrUpdateTokenSettingsToRegistry(
	ctx sdk.Context, tokens []types.Token, registeredTokenDenoms map[string]bool, update bool,
) error

SaveOrUpdateTokenSettingsToRegistry adds new tokens or updates the new tokens settings to registry.

func (*Keeper) SetHooks

func (k *Keeper) SetHooks(h types.Hooks) *Keeper

SetHooks sets the module's hooks. Note, hooks can only be set once.

func (Keeper) SetParams

func (k Keeper) SetParams(ctx sdk.Context, params types.Params)

SetParams sets the x/leverage module's parameters.

func (Keeper) SetTokenSettings

func (k Keeper) SetTokenSettings(ctx sdk.Context, token types.Token) error

SetTokenSettings stores a Token into the x/leverage module's KVStore.

func (Keeper) Supply

func (k Keeper) Supply(ctx sdk.Context, supplierAddr sdk.AccAddress, coin sdk.Coin) (sdk.Coin, error)

Supply attempts to deposit assets into the leverage module account in exchange for uTokens. If asset type is invalid or account balance is insufficient, we return an error. Returns the amount of uTokens minted.

func (Keeper) SupplyUtilization

func (k Keeper) SupplyUtilization(ctx sdk.Context, denom string) sdk.Dec

SupplyUtilization calculates the current supply utilization of a token denom.

func (Keeper) SweepBadDebts

func (k Keeper) SweepBadDebts(ctx sdk.Context) error

SweepBadDebts attempts to repay all bad debts in the system.

func (Keeper) TokenPrice

func (k Keeper) TokenPrice(ctx sdk.Context, baseDenom string, mode types.PriceMode) (sdk.Dec, uint32, error)

TokenPrice returns the USD value of a token's symbol denom, e.g. `UMEE` (rather than `uumee`). Note, the input denom must still be the base denomination, e.g. uumee. When error is nil, price is guaranteed to be positive. Also returns the token's exponent to reduce redundant registry reads.

func (Keeper) TokenValue

func (k Keeper) TokenValue(ctx sdk.Context, coin sdk.Coin, mode types.PriceMode) (sdk.Dec, error)

TokenValue returns the total token value given a Coin. An error is returned if we cannot get the token's price or if it's not an accepted token. Computation uses price of token's default denom to avoid rounding errors for exponent >= 18 tokens.

func (Keeper) TokenWithValue

func (k Keeper) TokenWithValue(ctx sdk.Context, denom string, value sdk.Dec, mode types.PriceMode) (sdk.Coin, error)

TokenWithValue creates a token of a given denom with an given USD value. Returns an error on invalid price or denom. Rounds down, i.e. the value of the token returned may be slightly less than the requested value.

func (Keeper) TotalTokenValue

func (k Keeper) TotalTokenValue(ctx sdk.Context, coins sdk.Coins, mode types.PriceMode) (sdk.Dec, error)

TotalTokenValue returns the total value of all supplied tokens. It is equivalent to the sum of TokenValue on each coin individually, except it ignores unregistered and blacklisted tokens instead of returning an error.

func (Keeper) UTokenWithValue

func (k Keeper) UTokenWithValue(ctx sdk.Context, denom string, value sdk.Dec, mode types.PriceMode) (sdk.Coin, error)

UTokenWithValue creates a uToken of a given denom with an given USD value. Returns an error on invalid price or non-uToken denom. Rounds down, i.e. the value of the uToken returned may be slightly less than the requested value.

func (Keeper) VisibleBorrowLimit added in v4.1.0

func (k Keeper) VisibleBorrowLimit(ctx sdk.Context, collateral sdk.Coins) (sdk.Dec, error)

VisibleBorrowLimit uses the price oracle to determine the borrow limit (in USD) provided by collateral sdk.Coins, using each token's uToken exchange rate and collateral weight. The lower of spot price or historic price is used for each collateral token. An error is returned if any input coins are not uTokens. This function skips assets that are missing prices, which will lead to a lower borrow limit when prices are down instead of a complete loss of borrowing ability.

func (*Keeper) VisibleCollateralShare added in v4.1.0

func (k *Keeper) VisibleCollateralShare(ctx sdk.Context, denom string) (sdk.Dec, error)

VisibleCollateralShare calculates the portion of overall collateral (measured in USD value) that a given uToken denom represents. If an asset other than the denom requested is missing an oracle price, it ignores that asset's contribution to the system's overall collateral, thus potentially overestimating the requested denom's collateral share while improving availability.

func (Keeper) VisibleCollateralValue added in v4.1.0

func (k Keeper) VisibleCollateralValue(ctx sdk.Context, collateral sdk.Coins) (sdk.Dec, error)

VisibleCollateralValue uses the price oracle to determine the value (in USD) provided by collateral sdk.Coins, using each token's uToken exchange rate. Always uses spot price. Unlike CalculateCollateralValue, this function will not return an error if value calculation fails on a token - instead, that token will contribute zero value to the total.

func (Keeper) VisibleTokenValue added in v4.1.0

func (k Keeper) VisibleTokenValue(ctx sdk.Context, coins sdk.Coins, mode types.PriceMode) (sdk.Dec, error)

VisibleTokenValue functions like TotalTokenValue, but interprets missing oracle prices as zero value instead of returning an error.

func (Keeper) Withdraw

func (k Keeper) Withdraw(ctx sdk.Context, supplierAddr sdk.AccAddress, uToken sdk.Coin) (sdk.Coin, bool, error)

Withdraw attempts to redeem uTokens from the leverage module in exchange for base tokens. If there are not enough uTokens in balance, Withdraw will attempt to withdraw uToken collateral to make up the difference. If the uToken denom is invalid or balances are insufficient to withdraw the amount requested, returns an error. Returns the amount of base tokens received. This function does NOT check that a borrower remains under their borrow limit or that collateral liquidity remains healthy - those assertions have been moved to MsgServer. Returns a boolean which is true if some or all of the withdrawn uTokens were from collateral.

type Migrator added in v4.1.0

type Migrator struct {
	// contains filtered or unexported fields
}

Migrator is a struct for handling in-place store migrations.

func NewMigrator added in v4.1.0

func NewMigrator(keeper *Keeper) Migrator

NewMigrator creates a Migrator.

func (Migrator) MigrateBNB added in v4.1.0

func (m Migrator) MigrateBNB(ctx sdk.Context) (bool, error)

MigrateBNB fixes the BNB base denom for the 4.1 upgrade. Also returns a boolean representing whether the token was changed.

type Querier

type Querier struct {
	Keeper
}

Querier implements a QueryServer for the x/leverage module.

func NewQuerier

func NewQuerier(k Keeper) Querier

func (Querier) AccountBalances

func (Querier) AccountSummary

func (Querier) BadDebts

func (q Querier) BadDebts(
	goCtx context.Context,
	req *types.QueryBadDebts,
) (*types.QueryBadDebtsResponse, error)

func (Querier) LiquidationTargets

func (Querier) MarketSummary

func (Querier) MaxBorrow

func (q Querier) MaxBorrow(
	goCtx context.Context,
	req *types.QueryMaxBorrow,
) (*types.QueryMaxBorrowResponse, error)

func (Querier) MaxWithdraw

func (Querier) Params

func (q Querier) Params(
	goCtx context.Context,
	req *types.QueryParams,
) (*types.QueryParamsResponse, error)

func (Querier) RegisteredTokens

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL