types

package
v23.0.9-iavl-v1 Latest Latest
Warning

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

Go to latest
Published: Mar 29, 2024 License: Apache-2.0 Imports: 22 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ModuleName = "twap"

	StoreKey          = ModuleName
	TransientStoreKey = "transient_" + ModuleName // this is silly we have to do this
	RouterKey         = ModuleName

	QuerierRoute = ModuleName
	// Contract: Coin denoms cannot contain this character
	KeySeparator = "|"
)

Variables

View Source
var (
	ErrInvalidLengthGenesis        = fmt.Errorf("proto: negative length found during unmarshaling")
	ErrIntOverflowGenesis          = fmt.Errorf("proto: integer overflow")
	ErrUnexpectedEndOfGroupGenesis = fmt.Errorf("proto: unexpected end of group")
)
View Source
var (
	PruningStateKey = []byte{0x01}

	// format is time | pool id | denom1 | denom2
	// made for efficiently deleting records by time in pruning
	HistoricalTWAPTimeIndexPrefix = historicalTWAPTimeIndexNoSeparator + KeySeparator
	// format is pool id | denom1 | denom2 | time
	// made for efficiently getting records given (pool id, denom1, denom2) and time bounds
	HistoricalTWAPPoolIndexPrefix = historicalTWAPPoolIndexNoSeparator + KeySeparator
)
View Source
var (
	KeyPruneEpochIdentifier    = []byte("PruneEpochIdentifier")
	KeyRecordHistoryKeepPeriod = []byte("RecordHistoryKeepPeriod")
)

Parameter store keys.

View Source
var (
	ErrInvalidLengthTwapRecord        = fmt.Errorf("proto: negative length found during unmarshaling")
	ErrIntOverflowTwapRecord          = fmt.Errorf("proto: integer overflow")
	ErrUnexpectedEndOfGroupTwapRecord = fmt.Errorf("proto: unexpected end of group")
)
View Source
var (
	MaxSpotPrice       = osmomath.NewDec(2).Power(128).Sub(osmomath.OneDec())
	MaxSpotPriceBigDec = osmomath.BigDecFromDec(MaxSpotPrice)
)

Functions

func AccumDiffDivDuration

func AccumDiffDivDuration(accumDiff osmomath.Dec, timeDeltaMs int64) osmomath.Dec

AccumDiffDivDuration returns the osmomath.Decated difference dividosmomath.Deche the time delta, that is the spot price between the current and last TWAP record.

func CanonicalTimeMs

func CanonicalTimeMs(twapTime time.Time) int64

CanonicalTimeMs returns the canonical time in milliseconds used for twap math computations in UTC. Removes any monotonic clock reading prior to conversion to ms. In twap, we assume all calculations are done in milliseconds. Therefore, this conversion is necessary to make sure that there are no rounding errors.

func FormatHistoricalPoolIndexTWAPKey

func FormatHistoricalPoolIndexTWAPKey(poolId uint64, denom1, denom2 string, accumulatorWriteTime time.Time) []byte

func FormatHistoricalPoolIndexTWAPKeyFromStrTime

func FormatHistoricalPoolIndexTWAPKeyFromStrTime(poolId uint64, denom1, denom2 string, accumulatorWriteTimeString string) []byte

func FormatHistoricalPoolIndexTimePrefix

func FormatHistoricalPoolIndexTimePrefix(poolId uint64, denom1, denom2 string) []byte

func FormatHistoricalPoolIndexTimeSuffix

func FormatHistoricalPoolIndexTimeSuffix(poolId uint64, denom1, denom2 string, accumulatorWriteTime time.Time) []byte

func FormatHistoricalTimeIndexTWAPKey

func FormatHistoricalTimeIndexTWAPKey(accumulatorWriteTime time.Time, poolId uint64, denom1, denom2 string) []byte

TODO: Replace historical management with ORM, we currently accept 2x write amplification right now.

func FormatKeyPoolTwapRecords

func FormatKeyPoolTwapRecords(poolId uint64) []byte

func FormatMostRecentTWAPKey

func FormatMostRecentTWAPKey(poolId uint64, denom1, denom2 string) []byte

func LexicographicalOrderDenoms

func LexicographicalOrderDenoms(denom0, denom1 string) (string, string, error)

LexicographicalOrderDenoms takes two denoms and returns them to be in lexicographically ascending order. In other words, the first returned denom string will be the lexicographically smaller of the two denoms. If the denoms are equal, an error will be returned.

func ParamKeyTable

func ParamKeyTable() paramtypes.KeyTable

ParamTable for twap module.

func ParseFieldsFromHistoricalTimeKey

func ParseFieldsFromHistoricalTimeKey(bz []byte) (string, uint64, string, string, error)

returns timeString, poolIdString, denom1, denom2, error nolint: revive

func SpotPriceMulDuration

func SpotPriceMulDuration(sp osmomath.Dec, timeDeltaMs int64) osmomath.Dec

SpotPriceMulDuration returns the spot price multiplied by the time delta, that is the spot price between the current and last TWAP record. A single second accounts for 1_000_000_000 when converted to int64.

Types

type DenomPair

type DenomPair struct {
	Denom0 string
	Denom1 string
}

DenomPair contains pair of assetA and assetB denoms which belong to a pool.

func GetAllUniqueDenomPairs

func GetAllUniqueDenomPairs(denoms []string) []DenomPair

GetAllUniqueDenomPairs returns all unique pairs of denoms, where for every pair (X, Y), X < Y. The pair (X,Y) should only appear once in the list. Denoms are lexicographically sorted. Panics if finds duplicate pairs.

NOTE: Sorts the input denoms slice.

type EndTimeInFutureError

type EndTimeInFutureError struct {
	EndTime   time.Time
	BlockTime time.Time
}

func (EndTimeInFutureError) Error

func (e EndTimeInFutureError) Error() string

type GenesisState

type GenesisState struct {
	// twaps is the collection of all twap records.
	Twaps []TwapRecord `protobuf:"bytes,1,rep,name=twaps,proto3" json:"twaps"`
	// params is the container of twap parameters.
	Params Params `protobuf:"bytes,2,opt,name=params,proto3" json:"params"`
}

GenesisState defines the twap module's genesis state.

func DefaultGenesis

func DefaultGenesis() *GenesisState

DefaultGenesis returns the default twap genesis state.

func NewGenesisState

func NewGenesisState(params Params, twapRecords []TwapRecord) *GenesisState

NewGenesisState returns genesis state with the given parameters and twap records.

func (*GenesisState) Descriptor

func (*GenesisState) Descriptor() ([]byte, []int)

func (*GenesisState) GetParams

func (m *GenesisState) GetParams() Params

func (*GenesisState) GetTwaps

func (m *GenesisState) GetTwaps() []TwapRecord

func (*GenesisState) Marshal

func (m *GenesisState) Marshal() (dAtA []byte, err error)

func (*GenesisState) MarshalTo

func (m *GenesisState) MarshalTo(dAtA []byte) (int, error)

func (*GenesisState) MarshalToSizedBuffer

func (m *GenesisState) MarshalToSizedBuffer(dAtA []byte) (int, error)

func (*GenesisState) ProtoMessage

func (*GenesisState) ProtoMessage()

func (*GenesisState) Reset

func (m *GenesisState) Reset()

func (*GenesisState) Size

func (m *GenesisState) Size() (n int)

func (*GenesisState) String

func (m *GenesisState) String() string

func (*GenesisState) Unmarshal

func (m *GenesisState) Unmarshal(dAtA []byte) error

func (*GenesisState) Validate

func (g *GenesisState) Validate() error

Validate validates the genesis state. Returns nil on success, error otherwise.

func (*GenesisState) XXX_DiscardUnknown

func (m *GenesisState) XXX_DiscardUnknown()

func (*GenesisState) XXX_Marshal

func (m *GenesisState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error)

func (*GenesisState) XXX_Merge

func (m *GenesisState) XXX_Merge(src proto.Message)

func (*GenesisState) XXX_Size

func (m *GenesisState) XXX_Size() int

func (*GenesisState) XXX_Unmarshal

func (m *GenesisState) XXX_Unmarshal(b []byte) error

type InvalidRecordCountError

type InvalidRecordCountError struct {
	Actual   int
	Expected int
}

func (InvalidRecordCountError) Error

func (e InvalidRecordCountError) Error() string

type InvalidUpdateRecordError

type InvalidUpdateRecordError struct {
	RecordBlockHeight int64
	RecordTime        time.Time
	ActualBlockHeight int64
	ActualTime        time.Time
}

func (InvalidUpdateRecordError) Error

func (e InvalidUpdateRecordError) Error() string

type KeySeparatorLengthError

type KeySeparatorLengthError struct {
	ExpectedLength int
	ActualLength   int
}

func (KeySeparatorLengthError) Error

func (e KeySeparatorLengthError) Error() string

type Params

type Params struct {
	PruneEpochIdentifier    string        `protobuf:"bytes,1,opt,name=prune_epoch_identifier,json=pruneEpochIdentifier,proto3" json:"prune_epoch_identifier,omitempty"`
	RecordHistoryKeepPeriod time.Duration `` /* 170-byte string literal not displayed */
}

Params holds parameters for the twap module

func DefaultParams

func DefaultParams() Params

default twap module parameters.

func NewParams

func NewParams(pruneEpochIdentifier string, recordHistoryKeepPeriod time.Duration) Params

func (*Params) Descriptor

func (*Params) Descriptor() ([]byte, []int)

func (*Params) GetPruneEpochIdentifier

func (m *Params) GetPruneEpochIdentifier() string

func (*Params) GetRecordHistoryKeepPeriod

func (m *Params) GetRecordHistoryKeepPeriod() time.Duration

func (*Params) Marshal

func (m *Params) Marshal() (dAtA []byte, err error)

func (*Params) MarshalTo

func (m *Params) MarshalTo(dAtA []byte) (int, error)

func (*Params) MarshalToSizedBuffer

func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error)

func (*Params) ParamSetPairs

func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs

Implements params.ParamSet.

func (*Params) ProtoMessage

func (*Params) ProtoMessage()

func (*Params) Reset

func (m *Params) Reset()

func (*Params) Size

func (m *Params) Size() (n int)

func (*Params) String

func (m *Params) String() string

func (*Params) Unmarshal

func (m *Params) Unmarshal(dAtA []byte) error

func (Params) Validate

func (p Params) Validate() error

validate params.

func (*Params) XXX_DiscardUnknown

func (m *Params) XXX_DiscardUnknown()

func (*Params) XXX_Marshal

func (m *Params) XXX_Marshal(b []byte, deterministic bool) ([]byte, error)

func (*Params) XXX_Merge

func (m *Params) XXX_Merge(src proto.Message)

func (*Params) XXX_Size

func (m *Params) XXX_Size() int

func (*Params) XXX_Unmarshal

func (m *Params) XXX_Unmarshal(b []byte) error

type PoolManagerInterface

type PoolManagerInterface interface {
	RouteGetPoolDenoms(ctx sdk.Context, poolId uint64) (denoms []string, err error)
	// CalculateSpotPrice returns the spot price of the quote asset in terms of the base asset,
	// using the specified pool.
	// E.g. if pool 1 traded 2 atom for 3 osmo, the quote asset was atom, and the base asset was osmo,
	// this would return 1.5. (Meaning that 1 atom costs 1.5 osmo)
	RouteCalculateSpotPrice(
		ctx sdk.Context,
		poolID uint64,
		quoteAssetDenom string,
		baseAssetDenom string,
	) (price osmomath.BigDec, err error)
}

AmmInterface is the functionality needed from a given pool ID, in order to maintain records and serve TWAPs.

type PruningState

type PruningState struct {
	// is_pruning is true if the pruning process is ongoing.
	// This tells the module to continue pruning the TWAP records
	// at the EndBlock.
	IsPruning bool `protobuf:"varint,1,opt,name=is_pruning,json=isPruning,proto3" json:"is_pruning,omitempty"`
	// last_kept_time is the time of the last kept TWAP record.
	// This is used to determine all TWAP records that are older than
	// last_kept_time and should be pruned.
	LastKeptTime time.Time `protobuf:"bytes,2,opt,name=last_kept_time,json=lastKeptTime,proto3,stdtime" json:"last_kept_time" yaml:"last_kept_time"`
	// last_key_seen is the last key of the TWAP records that were pruned
	// before reaching the block's prune limit
	LastKeySeen []byte `protobuf:"bytes,3,opt,name=last_key_seen,json=lastKeySeen,proto3" json:"last_key_seen,omitempty"`
}

PruningState allows us to spread out the pruning of TWAP records over time, instead of pruning all at once at the end of the epoch.

func (*PruningState) Descriptor

func (*PruningState) Descriptor() ([]byte, []int)

func (*PruningState) GetIsPruning

func (m *PruningState) GetIsPruning() bool

func (*PruningState) GetLastKeptTime

func (m *PruningState) GetLastKeptTime() time.Time

func (*PruningState) GetLastKeySeen

func (m *PruningState) GetLastKeySeen() []byte

func (*PruningState) Marshal

func (m *PruningState) Marshal() (dAtA []byte, err error)

func (*PruningState) MarshalTo

func (m *PruningState) MarshalTo(dAtA []byte) (int, error)

func (*PruningState) MarshalToSizedBuffer

func (m *PruningState) MarshalToSizedBuffer(dAtA []byte) (int, error)

func (*PruningState) ProtoMessage

func (*PruningState) ProtoMessage()

func (*PruningState) Reset

func (m *PruningState) Reset()

func (*PruningState) Size

func (m *PruningState) Size() (n int)

func (*PruningState) String

func (m *PruningState) String() string

func (*PruningState) Unmarshal

func (m *PruningState) Unmarshal(dAtA []byte) error

func (*PruningState) XXX_DiscardUnknown

func (m *PruningState) XXX_DiscardUnknown()

func (*PruningState) XXX_Marshal

func (m *PruningState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error)

func (*PruningState) XXX_Merge

func (m *PruningState) XXX_Merge(src proto.Message)

func (*PruningState) XXX_Size

func (m *PruningState) XXX_Size() int

func (*PruningState) XXX_Unmarshal

func (m *PruningState) XXX_Unmarshal(b []byte) error

type StartTimeAfterEndTimeError

type StartTimeAfterEndTimeError struct {
	StartTime time.Time
	EndTime   time.Time
}

func (StartTimeAfterEndTimeError) Error

type TimeStringKeyFormatError

type TimeStringKeyFormatError struct {
	Key string
	Err error
}

func (TimeStringKeyFormatError) Error

func (e TimeStringKeyFormatError) Error() string

type TwapRecord

type TwapRecord struct {
	PoolId uint64 `protobuf:"varint,1,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"`
	// Lexicographically smaller denom of the pair
	Asset0Denom string `protobuf:"bytes,2,opt,name=asset0_denom,json=asset0Denom,proto3" json:"asset0_denom,omitempty"`
	// Lexicographically larger denom of the pair
	Asset1Denom string `protobuf:"bytes,3,opt,name=asset1_denom,json=asset1Denom,proto3" json:"asset1_denom,omitempty"`
	// height this record corresponds to, for debugging purposes
	Height int64 `protobuf:"varint,4,opt,name=height,proto3" json:"record_height" yaml:"record_height"`
	// This field should only exist until we have a global registry in the state
	// machine, mapping prior block heights within {TIME RANGE} to times.
	Time time.Time `protobuf:"bytes,5,opt,name=time,proto3,stdtime" json:"time" yaml:"record_time"`
	// We store the last spot prices in the struct, so that we can interpolate
	// accumulator values for times between when accumulator records are stored.
	P0LastSpotPrice             cosmossdk_io_math.LegacyDec `` /* 139-byte string literal not displayed */
	P1LastSpotPrice             cosmossdk_io_math.LegacyDec `` /* 139-byte string literal not displayed */
	P0ArithmeticTwapAccumulator cosmossdk_io_math.LegacyDec `` /* 175-byte string literal not displayed */
	P1ArithmeticTwapAccumulator cosmossdk_io_math.LegacyDec `` /* 175-byte string literal not displayed */
	GeometricTwapAccumulator    cosmossdk_io_math.LegacyDec `` /* 165-byte string literal not displayed */
	// This field contains the time in which the last spot price error occurred.
	// It is used to alert the caller if they are getting a potentially erroneous
	// TWAP, due to an unforeseen underlying error.
	LastErrorTime time.Time `protobuf:"bytes,11,opt,name=last_error_time,json=lastErrorTime,proto3,stdtime" json:"last_error_time" yaml:"last_error_time"`
}

A TWAP record should be indexed in state by pool_id, (asset pair), timestamp The asset pair assets should be lexicographically sorted. Technically (pool_id, asset_0_denom, asset_1_denom, height) do not need to appear in the struct however we view this as the wrong performance tradeoff given SDK today. Would rather we optimize for readability and correctness, than an optimal state storage format. The system bottleneck is elsewhere for now.

func GetAllMostRecentTwapsForPool

func GetAllMostRecentTwapsForPool(store sdk.KVStore, poolId uint64) ([]TwapRecord, error)

GetAllMostRecentTwapsForPool returns all of the most recent twap records for a pool id. if the pool id doesn't exist, then this returns a blank list.

func GetMostRecentTwapForPool

func GetMostRecentTwapForPool(store sdk.KVStore, poolId uint64, denom1, denom2 string) (TwapRecord, error)

func ParseTwapFromBz

func ParseTwapFromBz(bz []byte) (twap TwapRecord, err error)

func (*TwapRecord) Descriptor

func (*TwapRecord) Descriptor() ([]byte, []int)

func (*TwapRecord) GetAsset0Denom

func (m *TwapRecord) GetAsset0Denom() string

func (*TwapRecord) GetAsset1Denom

func (m *TwapRecord) GetAsset1Denom() string

func (*TwapRecord) GetHeight

func (m *TwapRecord) GetHeight() int64

func (*TwapRecord) GetLastErrorTime

func (m *TwapRecord) GetLastErrorTime() time.Time

func (*TwapRecord) GetPoolId

func (m *TwapRecord) GetPoolId() uint64

func (*TwapRecord) GetTime

func (m *TwapRecord) GetTime() time.Time

func (*TwapRecord) Marshal

func (m *TwapRecord) Marshal() (dAtA []byte, err error)

func (*TwapRecord) MarshalTo

func (m *TwapRecord) MarshalTo(dAtA []byte) (int, error)

func (*TwapRecord) MarshalToSizedBuffer

func (m *TwapRecord) MarshalToSizedBuffer(dAtA []byte) (int, error)

func (*TwapRecord) ProtoMessage

func (*TwapRecord) ProtoMessage()

func (*TwapRecord) Reset

func (m *TwapRecord) Reset()

func (*TwapRecord) Size

func (m *TwapRecord) Size() (n int)

func (*TwapRecord) String

func (m *TwapRecord) String() string

func (*TwapRecord) Unmarshal

func (m *TwapRecord) Unmarshal(dAtA []byte) error

func (*TwapRecord) XXX_DiscardUnknown

func (m *TwapRecord) XXX_DiscardUnknown()

func (*TwapRecord) XXX_Marshal

func (m *TwapRecord) XXX_Marshal(b []byte, deterministic bool) ([]byte, error)

func (*TwapRecord) XXX_Merge

func (m *TwapRecord) XXX_Merge(src proto.Message)

func (*TwapRecord) XXX_Size

func (m *TwapRecord) XXX_Size() int

func (*TwapRecord) XXX_Unmarshal

func (m *TwapRecord) XXX_Unmarshal(b []byte) error

type UnexpectedSeparatorError

type UnexpectedSeparatorError struct {
	ExpectedSeparator string
	ActualSeparator   string
}

func (UnexpectedSeparatorError) Error

func (e UnexpectedSeparatorError) Error() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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