lib

package
v0.3.2 Latest Latest
Warning

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

Go to latest
Published: Oct 7, 2023 License: AGPL-3.0 Imports: 20 Imported by: 0

Documentation

Index

Constants

View Source
const (
	OneMillion        = uint32(1_000_000)
	TenThousand       = uint32(10_000)
	OneHundred        = uint32(100)
	MaxPriceChangePpm = uint32(10_000)
	// 10^6 quantums == 1 USD.
	QuoteCurrencyAtomicResolution = int32(-6)
	UsdcAssetId                   = uint32(0)

	ZeroUint64 = uint64(0)
)
View Source
const (
	AvgInt32MaxArrayLength = 2 << 31
)

Variables

This section is empty.

Functions

func AbsDiffUint64

func AbsDiffUint64(x uint64, y uint64) uint64

func AbsInt32

func AbsInt32(i int32) uint32

func AbsInt64

func AbsInt64(i int64) uint64

func AddUint32

func AddUint32(a int64, b uint32) (int64, error)

AddUint32 returns the sum of a and b. If the sum underflows or overflows, this method returns an error.

func AssertCheckTxMode

func AssertCheckTxMode(ctx sdk.Context)

func AssertDeliverTxMode

func AssertDeliverTxMode(ctx sdk.Context)

func AvgInt32

func AvgInt32(nums []int32) int32

AvgInt32 returns average of the input int32 array. Result is rounded towards zero.

func BaseToQuoteQuantums

func BaseToQuoteQuantums(
	bigBaseQuantums *big.Int,
	baseCurrencyAtomicResolution int32,
	priceValue uint64,
	priceExponent int32,
) (bigNotional *big.Int)

BaseToQuoteQuantums converts an amount denoted in base quantums, to an equivalent amount denoted in quote quantums. To determine the equivalent amount, an oracle price is used.

  • `priceValue * 10^priceExponent` represents the conversion rate from one full coin of base currency to one full coin of quote currency.
  • `10^baseCurrencyAtomicResolution` represents the amount of one full coin that a base quantum is equal to.
  • `10^quoteCurrencyAtomicResolution` represents the amount of one full coin that a quote quantum is equal to.

To convert from base to quote quantums, we use the following equation:

quoteQuantums =
  (baseQuantums * 10^baseCurrencyAtomicResolution) *
  (priceValue * 10^priceExponent) /
  (10^quoteCurrencyAtomicResolution)
=
  baseQuantums * priceValue *
  10^(priceExponent + baseCurrencyAtomicResolution - quoteCurrencyAtomicResolution)

The result is rounded down.

func BigFloat0

func BigFloat0() *big.Float

BigFloat0 returns a `big.Float` that is set to 0.

func BigFloatMaxUint64

func BigFloatMaxUint64() *big.Float

BigFloatMaxUint64 returns a `big.Float` that is set to MaxUint64.

func BigInt0

func BigInt0() *big.Int

BigInt0 returns a `big.Int` that is set to 0.

func BigInt32Clamp

func BigInt32Clamp(n *big.Int, lowerBound, upperBound int32) int32

BigInt32Clamp takes a `big.Int` as input, and `int32` upper and lower bounds. It returns `int32` bounded within the upper and lower bound, inclusive. Note that if there is overlap between the bounds (`lower > upper`), this function will do the following: - If `n < lower`, the lower bound is returned. - Else, the upper bound is returned (since `n >= lower`, then `n > upper` must be true).

func BigIntClamp

func BigIntClamp(n *big.Int, lowerBound *big.Int, upperBound *big.Int) *big.Int

See `bigGenericClamp` for specification.

func BigIntMulPpm

func BigIntMulPpm(input *big.Int, ppm uint32) *big.Int

BigIntMulPpm takes a `big.Int` and returns the result of `input * ppm / 1_000_000`.

func BigIntMulSignedPpm

func BigIntMulSignedPpm(input *big.Int, ppm int32, roundUp bool) *big.Int

BigIntMulSignedPpm takes a `big.Int` and returns the result of `input * ppm / 1_000_000`.

func BigIntOneMillion

func BigIntOneMillion() *big.Int

BigIntOneMillion returns a `big.Int` that is set to 1_000_000.

func BigIntOneTrillion

func BigIntOneTrillion() *big.Int

BigIntOneTrillion returns a `big.Int` that is set to 1_000_000_000_000.

func BigIntRoundToMultiple

func BigIntRoundToMultiple(
	n *big.Int,
	multiple *big.Int,
	roundUp bool,
) *big.Int

BigIntRoundToMultiple takes an input, a multiple, and a direction to round (true for up, false for down). It returns a rounded result such that it is evenly divided by `multiple`. This function always expects the `multiple` parameter to be positive, otherwise it will panic.

func BigMax

func BigMax(a, b *big.Int) *big.Int

BigMax takes two `big.Int` as parameters and returns the larger one.

func BigMaxInt32

func BigMaxInt32() *big.Int

BigMaxInt32 returns a `big.Int` that represents `MaxInt32`.

func BigMin

func BigMin(a, b *big.Int) *big.Int

BigMin takes two `big.Int` as parameters and returns the smaller one.

func BigMulPow10

func BigMulPow10(
	val *big.Int,
	exponent int32,
) (
	result *big.Rat,
)

BigMulPow10 returns the result of `val * 10^exponent`, in *big.Rat.

func BigNegMaxUint64

func BigNegMaxUint64() *big.Int

BigNegMaxUint64 returns a `big.Int` that is set to -math.MaxUint64.

func BigPow10

func BigPow10(exponent uint64) *big.Int

BigPow10 returns the result of `10^exponent`. Caches all calculated values and re-uses cached values in any following calls to BigPow10.

func BigRat0

func BigRat0() *big.Rat

BigRat0 returns a `big.Rat` that is set to 0.

func BigRat1

func BigRat1() *big.Rat

BigRat1 returns a `big.Rat` that is set to 1.

func BigRatClamp

func BigRatClamp(n *big.Rat, lowerBound *big.Rat, upperBound *big.Rat) *big.Rat

See `bigGenericClamp` for specification.

func BigRatMulPpm

func BigRatMulPpm(input *big.Rat, ppm uint32) *big.Rat

BigRatMulPpm takes a `big.Rat` and returns the result of `input * ppm / 1_000_000`.

func BigRatOneMillion

func BigRatOneMillion() *big.Rat

BigRatOneMillion returns a `big.Rat` that is set to 1_000_000.

func BigRatRound

func BigRatRound(n *big.Rat, roundUp bool) *big.Int

BigRatRound takes an input and a direction to round (true for up, false for down). It returns the result rounded to a `*big.Int` in the specified direction.

func BigUint64Clamp

func BigUint64Clamp(n *big.Int, lowerBound, upperBound uint64) uint64

BigUint64Clamp takes a `big.Int` as input, and `uint64` upper and lower bounds. It returns `uint64` bounded within the upper and lower bound, inclusive. Note that if there is overlap between the bounds (`lower > upper`), this function will do the following: - If `n < lower`, the lower bound is returned. - Else, the upper bound is returned (since `n >= lower`, then `n > upper` must be true).

func BoolToString

func BoolToString(b bool) string

func BytesSliceToBytes32

func BytesSliceToBytes32(b []byte) [32]byte

func BytesToInt32

func BytesToInt32(b []byte) int32

func BytesToUint32

func BytesToUint32(b []byte) uint32

func ChangeRateUint64

func ChangeRateUint64(originalV uint64, newV uint64) (float32, error)

ChangeRateUint64 returns the rate of change between the original and the new values. result = (new - original) / original Note: the return value is truncated to fit float32 precision.

func ContainsDuplicates

func ContainsDuplicates[V comparable](values []V) bool

ContainsDuplicates returns true if the slice contains duplicates, false if not.

func ConvertBigFloatSliceToUint64Slice

func ConvertBigFloatSliceToUint64Slice(values []*big.Float) ([]uint64, error)

ConvertBigFloatSliceToUint64Slice attempts to convert all values in a slice from big Float to uint64 and return an error if any conversions fail. Note: during conversion, will always round down.

func ConvertBigFloatToUint64

func ConvertBigFloatToUint64(value *big.Float) (uint64, error)

ConvertBigFloatToUint64 attempts to convert a big Float into a uint64 and returns an error if the conversion would fail. Note: during conversion, will always round down.

func ConvertStringSliceToBigFloatSlice

func ConvertStringSliceToBigFloatSlice(values []string) ([]*big.Float, error)

ConvertStringSliceToBigFloatSlice attempts to convert all values in a slice from string to big Float and return an error if any conversions fail.

func DenomTraceToIBCDenom

func DenomTraceToIBCDenom(denomTraceStr string) (
	ibcDenom string,
	err error,
)

Given a denom trace string (e.g. `transfer/channel-141/uosmo`), output the IBC denom. For more information on IBC denom, see: https://interchainacademy.cosmos.network/tutorials/5-ibc-dev/#how-are-ibc-denoms-derived

func DivisionUint32RoundUp

func DivisionUint32RoundUp(x, y uint32) uint32

DivisionUint32RoundUp returns the result of x/y, rounded up.

func FilterSlice

func FilterSlice[V any](values []V, filterFunc func(V) bool) []V

FilterSlice takes a function that returns a boolean on whether to include the element in the final result, and returns a slice of elements where the function returned true when called with each element.

func FundingRateToIndex

func FundingRateToIndex(
	proratedFundingRate *big.Rat,
	baseCurrencyAtomicResolution int32,
	priceValue uint64,
	priceExponent int32,
) (fundingIndex *big.Int)

FundingRateToIndex converts funding rate (in ppm) to FundingIndex given the oracle price.

To get funding index from funding rate, we know that:

  • `fundingPaymentQuoteQuantum = fundingRatePpm / 1_000_000 * time * quoteQuantums`
  • Divide both sides by `baseQuantums`:
  • Left side: `fundingPaymentQuoteQuantums / baseQuantums = fundingIndexDelta / 1_000_000`
  • right side: ``` fundingRate * time * quoteQuantums / baseQuantums = fundingRatePpm / 1_000_000 * priceValue * 10^(priceExponent + baseCurrencyAtomicResolution - quoteCurrencyAtomicResolution) ```

Hence, further multiplying both sides by 1_000_000, we have:

fundingIndexDelta =
  (fundingRatePpm * time) * priceValue *
  10^(priceExponent + baseCurrencyAtomicResolution - quoteCurrencyAtomicResolution)

Arguments:

proratedFundingRate: prorated funding rate adjusted by time delta, in parts-per-million
timeSinceLastFunding: time (in seconds) since last funding index update
baseCurrencyAtomicResolution: atomic resolution of the base currency
priceValue: index price of the perpetual market according to the pricesKeeper
priceExponent: priceExponent of the market according to the pricesKeeper

func GetSortedKeys added in v0.3.0

func GetSortedKeys[R interface {
	~[]K
	sort.Interface
}, K comparable, V any](m map[K]V) []K

GetSortedKeys returns the keys of the map in sorted order.

func Int32ToBytes

func Int32ToBytes(i int32) []byte

func Int32ToString

func Int32ToString(i int32) string

func Int64MulPpm

func Int64MulPpm(x int64, ppm uint32) int64

func Int64ToBytesForState

func Int64ToBytesForState(id int64) []byte

Int64ToBytesForState converts the int64 to 8 bytes + '/' to be used as state key prefixes.

func IsDeliverTxMode

func IsDeliverTxMode(ctx sdk.Context) bool

func MapSlice

func MapSlice[V any, E any](values []V, mapFunc func(V) E) []E

MapSlice takes a function and executes that function on each element of a slice, returning the result. Note the function must return one result for each element of the slice.

func Max

func Max[T constraints.Ordered](x, y T) T

func Median added in v0.3.0

func Median[V uint64 | uint32 | int64 | int32](input []V) (V, error)

Median is a generic median calculator. If the input has an even number of elements, then the average of the two middle numbers is rounded away from zero.

func MergeAllMapsMustHaveDistinctKeys added in v0.3.0

func MergeAllMapsMustHaveDistinctKeys[K comparable, V any](maps ...map[K]V) map[K]V

MergeAllMapsMustHaveDistinctKeys merges all the maps into a single map. Panics if there are duplicate keys.

func Min

func Min[T constraints.Ordered](x, y T) T

func MustConvertBigIntToInt32

func MustConvertBigIntToInt32(n *big.Int) int32

`MustConvertBigIntToInt32` converts a `big.Int` to an `int32` and panics if the input value overflows or underflows `int32`.

func MustConvertIntegerToUint32

func MustConvertIntegerToUint32[T constraints.Integer](value T) uint32

func MustGetMedian added in v0.3.0

func MustGetMedian[V uint64 | uint32 | int64 | int32](input []V) V

MustGetMedian is a wrapper around `Median` that panics if input length is zero.

func QuoteToBaseQuantums

func QuoteToBaseQuantums(
	bigQuoteQuantums *big.Int,
	baseCurrencyAtomicResolution int32,
	priceValue uint64,
	priceExponent int32,
) (bigNotional *big.Int)

QuoteToBaseQuantums converts an amount denoted in quote quantums, to an equivalent amount denoted in base quantums. To determine the equivalent amount, an oracle price is used.

  • `priceValue * 10^priceExponent` represents the conversion rate from one full coin of base currency to one full coin of quote currency.
  • `10^baseCurrencyAtomicResolution` represents the amount of one full coin that a base quantum is equal to.
  • `10^quoteCurrencyAtomicResolution` represents the amount of one full coin that a quote quantum is equal to.

To convert from quote to base quantums, we use the following equation:

baseQuantums =
  quoteQuantums / priceValue /
  10^(priceExponent + baseCurrencyAtomicResolution - quoteCurrencyAtomicResolution)

The result is rounded down.

func RandomBytesBetween

func RandomBytesBetween(start []byte, end []byte, rand *rand.Rand) []byte

RandomBytesBetween returns a random byte slice that is in the range [start, end] when compared lexicographically. The slice will have a length in the range [len(start), len(end)]. In the current implementation, all possible permutations are not equally likely. Nil slices for start and end will be treated as empty byte slices. Will panic if:

  • start compares lexicographically greater than end
  • nil rand is provided

func RatPow10

func RatPow10(exponent int32) *big.Rat

RatPow10 returns the result of `10^exponent`. Re-uses the cached values by calling bigPow10Helper.

func SliceToSet

func SliceToSet[K comparable](values []K) map[K]struct{}

SliceToSet converts a slice to a set. Function will panic if there are duplicate values.

func StringToUint32

func StringToUint32(s string) (uint32, error)

func TxMode

func TxMode(ctx sdk.Context) string

TxMode returns a textual representation of the tx mode, one of `CheckTx`, `ReCheckTx`, or `DeliverTx`.

func Uint32ToBytes

func Uint32ToBytes(i uint32) []byte

func Uint32ToBytesForState

func Uint32ToBytesForState(id uint32) []byte

Uint32ToBytesForState converts the uint32 to 4 bytes + '/' to be used as state key prefixes

func Uint32ToString

func Uint32ToString(i uint32) string

func Uint64LinearInterpolate

func Uint64LinearInterpolate(v0 uint64, v1 uint64, cPpm uint32) (uint64, error)

Uint64LinearInterpolate interpolates value v0 towards v1 by a small constant value c, typically expected to be between 0 and 1. Here, the input value of c is represented in ppm. In order to avoid overflows, if 0 <= cPpm <= 1_000_000 then an error is returned.

func Uint64MulPpm

func Uint64MulPpm(x uint64, ppm uint32) uint64

Uint64MulPpm multiplies a uint64 value by a scaling factor represented in ppm. If the integer overflows, this method panics.

func Uint64ToString

func Uint64ToString(i uint64) string

Types

type FileHandler

type FileHandler interface {
	RemoveAll(path string) error
}

FileHandler is an interface that encapsulates the os function `RemoveAll`.

type FileHandlerImpl

type FileHandlerImpl struct{}

FileHandlerImpl is the struct that implements the `FileHandler` interface.

func (*FileHandlerImpl) RemoveAll

func (r *FileHandlerImpl) RemoveAll(path string) error

RemoveAll wraps `os.RemoveAll` which removes everything at a given path.

type GrpcClient

type GrpcClient interface {
	NewGrpcConnection(ctx context.Context, socketAddress string) (*grpc.ClientConn, error)
	NewTcpConnection(ctx context.Context, endpoint string) (*grpc.ClientConn, error)
	CloseConnection(grpcConn *grpc.ClientConn) error
}

GrpcClient is an interface that encapsulates the `NewGrpcConnection` function and `CloseConnection`.

type GrpcClientImpl

type GrpcClientImpl struct{}

GrpcClientImpl is the struct that implements the `GrpcClient` interface.

func (*GrpcClientImpl) CloseConnection

func (g *GrpcClientImpl) CloseConnection(grpcConn *grpc.ClientConn) error

CloseConnection calls `grpc.ClientConn.Close()` to close a grpc connection.

func (*GrpcClientImpl) NewGrpcConnection

func (g *GrpcClientImpl) NewGrpcConnection(
	ctx context.Context,
	socketAddress string,
) (*grpc.ClientConn, error)

NewGrpcConnection calls `grpc.Dial` with custom parameters to create a secure connection with context that blocks until the underlying connection is up.

func (*GrpcClientImpl) NewTcpConnection

func (g *GrpcClientImpl) NewTcpConnection(
	ctx context.Context,
	endpoint string,
) (*grpc.ClientConn, error)

NewTcpConnection calls `grpc.Dial` to create an insecure tcp connection.

type GrpcServer

type GrpcServer interface {
	Serve(lis net.Listener) error
	Stop()
	RegisterService(sd *grpc.ServiceDesc, ss interface{})
}

GrpcServer is an interface that encapsulates a `Grpc.Server` object.

type MsgRouter

type MsgRouter interface {
	Handler(msg sdk.Msg) baseapp.MsgServiceHandler
}

type RequestHandler

type RequestHandler interface {
	Get(ctx context.Context, url string) (*http.Response, error)
}

RequestHandler is an interface that handles making HTTP requests.

type RequestHandlerImpl

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

RequestHandlerImpl is the struct that implements the `RequestHandler` interface.

func NewRequestHandlerImpl

func NewRequestHandlerImpl(client *http.Client) *RequestHandlerImpl

NewRequestHandlerImpl creates a new RequestHandlerImpl. It manages making HTTP requests.

func (*RequestHandlerImpl) Get

Get wraps `http.Get` which makes an HTTP GET request to a URL and returns a response.

type Sortable added in v0.3.0

type Sortable[K constraints.Ordered] []K

Sortable[K] attaches the methods of sort.Interface to []K, sorting in increasing order.

func (Sortable[K]) Len added in v0.3.0

func (s Sortable[K]) Len() int

func (Sortable[K]) Less added in v0.3.0

func (s Sortable[K]) Less(i, j int) bool

func (Sortable[K]) Swap added in v0.3.0

func (s Sortable[K]) Swap(i, j int)

type TxHash

type TxHash string

func GetTxHash

func GetTxHash(tx []byte) TxHash

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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