utils

package
v1.4.257 Latest Latest
Warning

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

Go to latest
Published: Jun 8, 2023 License: GPL-2.0 Imports: 35 Imported by: 12

Documentation

Index

Constants

View Source
const (
	UNIV2_FEE_FACTOR = 997
	UNIV2_FACTOR     = 1000
)

Variables

This section is empty.

Functions

func AfterDay

func AfterDay(date1, date2 time.Time) bool

AfterDay returns true if date1 is a date after date2, irrespective of the daytime. The go method "After" respects daytime.

func Average added in v1.4.2

func Average(series []float64) (average float64)

Average returns the average of @samples.

func CheckDuplicates added in v1.4.224

func CheckDuplicates(arr []string) bool

func CheckWeekDay

func CheckWeekDay(date time.Time) bool

CheckWeekDay returns true if @date is not weekend and false otherwise.

func CloseHTTPResp added in v1.2.0

func CloseHTTPResp(resp *http.Response)

CloseHTTPResp is a wrapper for closing http response bodies while complying with the linter.

func ComputeMedian added in v1.4.2

func ComputeMedian(samples []float64) (median float64)

ComputeMedian returns the median of @samples.

func Contains

func Contains(s *[]string, str string) bool

Contains takes a slice of strings and a string and checks if it is contained in the slice.

func ContainsDay

func ContainsDay(s []time.Time, date time.Time) bool

ContainsDay returns true if day @date is contained in slice @s, independent of the daytime. As a consequence, be cautious when comparing days in different timezones.

func CopyBytes added in v1.4.43

func CopyBytes(data []byte) []byte

func CountDays

func CountDays(dateInit, dateFinal time.Time, business bool) (days int, err error)

CountDays returns the number of days between @dateInit and @dateFinal, both given as converted from a string in the format yyyy-mm-dd, excluding the last day. @bool If true only business days are counted.

func DiscardOutliers added in v1.4.2

func DiscardOutliers(prices []float64, volumes []float64, basispoints float64) (newPrices []float64, newVolumes []float64, discarded []int, err error)

DiscardOutliers discards every data point from @prices and @volumes that deviates from the price median by more than @basispoints basis points.

func DownloadResource

func DownloadResource(filepath, url string) (err error)

DownloadResource is a simple utility that downloads a resource from @url and stores it into @filepath.

func GenerateAutoname added in v1.4.94

func GenerateAutoname(delimiter string) string

Generate returns a random name from the list of adjectives, colors and surnames.

func GetCoinPrice

func GetCoinPrice(coin string) (float64, error)

GetCoinPrice Gets the price in USD of coin through our API. Looks it up on coingecko in case it doesn't find it there.

func GetHolidays

func GetHolidays(workdays []time.Time, dateInit, dateFinal time.Time) []time.Time

GetHolidays returns "holidays" as non-weekend complement of given days @workdays

func GetRequest

func GetRequest(url string) ([]byte, int, error)

GetRequest performs a get request on @url and returns the response body as a slice of byte data.

func GetRequestWithStatus added in v1.2.0

func GetRequestWithStatus(url string) ([]byte, int, error)

GetRequest performs a get request on @url and returns the response body as a slice of byte data.

func GetSigner added in v1.4.46

func GetSigner(chainID, creator, oracleaddress, message, signed string) (common.Address, error)

func GetTomorrow

func GetTomorrow(date, layout string) string

GetTomorrow returns the day before @date in the world of strings, formatted as @layout

func GetYesterday

func GetYesterday(date, layout string) string

GetYesterday returns the day before @date in the world of strings, formatted as @layout

func Getenv added in v1.2.0

func Getenv(key, fallback string) string

func GraphQLGet

func GraphQLGet(url string, query []byte, bearer string) ([]byte, int, error)

GraphQLGet returns the body of the result of a graphQL GET query. @url is the base url of the graphQL API @query is a byte slice representing the graphQL query message @bearer contains the API key if present

func HTTPRequest added in v1.2.0

func HTTPRequest(request *http.Request) (body []byte, statusCode int, err error)

HTTPRequest returns the request body and defers the closing compliant to linting.

func Has0xPrefix added in v1.4.43

func Has0xPrefix(str string) bool

func HexDecode added in v1.4.43

func HexDecode(s string) ([]byte, error)

func IsEnvExist added in v1.2.0

func IsEnvExist(key string) bool

func IsInBin added in v1.4.113

func IsInBin(timestamp time.Time, bin TimeBin) bool

IsInBin returns true in case @timestamp is in half-open interval @bin.

func MakeTimeRanges added in v1.4.2

func MakeTimeRanges(timeInit, timeFinal time.Time, numRanges int) (starttimes, endtimes []time.Time)

MakeTimeRanges returns @numRanges start- and endtimes partitioning [@timeInit, @timeFinal] in intervals of identical size.

func MakeTimerange added in v1.4.2

func MakeTimerange(starttimeString string, endtimeString string, timeRange time.Duration) (starttime time.Time, endtime time.Time, err error)

MakeTimerange parses Unix timestamps given as strings. In case one of the two is empty, it returns a time-range based on @timeRange.

func MaxString

func MaxString(sl []string) (string, int64)

MaxString return the maximum of a slice of strings along with its index

func MinString

func MinString(sl []string) (string, int64)

MinString return the maximum of a slice of strings along with its index

func NewKeyPair added in v1.4.43

func NewKeyPair() (publickey, privatekey string)

func OpenseaGetRequest added in v1.2.0

func OpenseaGetRequest(OpenseaURL string) ([]byte, int, error)

OpenseaGetRequest returns the data for a get request on @url with an Opensea API key.

func PostRequest

func PostRequest(url string, body io.Reader) ([]byte, error)

PostRequest performs a POST request on @url and returns the response body as a slice of byte data.

func SameDays

func SameDays(date1, date2 time.Time) bool

SameDays returns true if @date1 is the same date as @date2, independent of the daytime.

func SliceDifference

func SliceDifference(slice1, slice2 []string) []string

SliceDifference returns the elements in @slice1 that aren't in @slice2.

func StandardDeviation added in v1.4.2

func StandardDeviation(series []float64) float64

func StrToUnixtime

func StrToUnixtime(s string) (t time.Time, err error)

StrToUnixtime converts a string corresponding to an int to Unix time

func TypedDataAndHash added in v1.4.43

func TypedDataAndHash(typedData TypedData) ([]byte, string, error)

TypedDataAndHash is a helper function that calculates a hash for typed data conforming to EIP-712. This hash can then be safely used to calculate a signature.

See https://eips.ethereum.org/EIPS/eip-712 for the full specification.

This gives context to the signed typed data and prevents signing of transactions.

func UniV2AmountOut added in v1.4.65

func UniV2AmountOut(amountIn float64, reserveIn float64, reserveOut float64) (float64, error)

func UniV2PriceAfterTrade added in v1.4.65

func UniV2PriceAfterTrade(amountIn float64, reserveIn float64, reserveOut float64) (price float64, err error)

func UniV2PriceReserveIn added in v1.4.65

func UniV2PriceReserveIn(reserveIn float64, reserveOut float64) (float64, error)

func UniqueStrings

func UniqueStrings(s []string) []string

UniqueStrings returns a subslice of @s such that each entry only appears once

func ValidTimeRange added in v1.4.138

func ValidTimeRange(starttime time.Time, endtime time.Time, maxDuration time.Duration) (ok bool)

ValidTimeRange returns true if the interval [@starttime, @endtime] is at most @maxDuration.

func Variance added in v1.4.2

func Variance(series []float64) (variance float64)

func VerifyTypedData added in v1.4.43

func VerifyTypedData(primaryType string, domain TypedDataDomain, types Types, message TypedDataMessage, signature []byte) (common.Address, error)

func Vwap added in v1.4.2

func Vwap(prices []float64, volumes []float64) (float64, error)

vwap returns the volume weighted average price for the slices @prices and @volumes.

Types

type ArgsortableSlice added in v1.2.0

type ArgsortableSlice struct {
	sort.Interface
	// contains filtered or unexported fields
}

ArgsortableSlice is a wrapper struct around the sort interface. It allows for implemetation of argsort for all sortable types.

func NewFloat64Slice added in v1.2.0

func NewFloat64Slice(sf sort.Float64Slice) *ArgsortableSlice

NewFloat64Slice returns the wrapped float64slice that can be argsorted.

func (ArgsortableSlice) Ind added in v1.2.0

func (as ArgsortableSlice) Ind() []int

func (ArgsortableSlice) Swap added in v1.2.0

func (s ArgsortableSlice) Swap(i, j int)

Swap swaps the corresponding indices together with the values.

type AssetQuotationSigner added in v1.4.171

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

func NewAssetQuotationSigner added in v1.4.171

func NewAssetQuotationSigner(privateKey string) *AssetQuotationSigner

func (*AssetQuotationSigner) Sign added in v1.4.171

func (aqs *AssetQuotationSigner) Sign(symbol, address, blockchain string, price float64, time time.Time) (string, error)

type EthFilteredTx added in v1.2.0

type EthFilteredTx struct {
	BlockNum  uint64
	BlockHash common.Hash
	TXIndex   uint
	TXHash    common.Hash
	Logs      []types.Log // list of matched log records if Events or EvAddrs were used, otherwise all logs of the transaction
}

EthFilteredTx holds limited info for found transactions

type EthTxFilterCriteria added in v1.2.0

type EthTxFilterCriteria struct {
	StartBlockNum      uint64           // inclusive. filter transactions from the specific block
	StartTxIndex       uint             // inclusive. filter transactions from specific index in the given StartBlockNum
	LimitBlocks        int              // filter transactions in the specific number of blocks, zero means up to highest possible block
	BehindHighestBlock int              // stay behind the highest synched block if StartBlockNum+LimitBlocks in excess of the head
	EvAddrs            []common.Address // list of addresses from which transaction events should originate
	Events             []common.Hash    // list of events from which transactions should contain
}

EthTxFilterCriteria used for filtering transaction records

type EthTxFilterResult added in v1.2.0

type EthTxFilterResult struct {
	Synced       bool             // it means the most recent inspected block matches the highest known block (see BehindHighestBlock)
	NumBlocks    int              // number of blocks found
	NumTXs       int              // number of transactions found
	NumLogs      int              // number of log records found
	TXs          []*EthFilteredTx // list of found transactions
	LastBlockNum uint64           // block number of most recent transaction inspected
}

EthTxFilterResult describes filter results and holds found transactions

func EthFilterTXs added in v1.2.0

func EthFilterTXs(ctx context.Context, ethClient *ethclient.Client, filter EthTxFilterCriteria) (*EthTxFilterResult, error)

EthFilterTXs returns transactions filtered by log records

type NameValueType added in v1.4.43

type NameValueType struct {
	Name  string      `json:"name"`
	Value interface{} `json:"value"`
	Typ   string      `json:"type"`
}

NameValueType is a very simple struct with Name, Value and Type. It's meant for simple json structures used to communicate signing-info about typed data with the UI

func (*NameValueType) Pprint added in v1.4.43

func (nvt *NameValueType) Pprint(depth int) string

Pprint returns a pretty-printed version of nvt

type TimeBin added in v1.4.113

type TimeBin struct {
	Starttime time.Time
	Endtime   time.Time
}

func MakeBins added in v1.4.113

func MakeBins(starttime time.Time, endtime time.Time, blockSizeSeconds int64, blockShiftSeconds int64) (bins []TimeBin)

MakeBins returns a slice of @TimeBin according to block sizes and time shifts.

type Type added in v1.4.43

type Type struct {
	Name string `json:"name"`
	Type string `json:"type"`
}

Type is the inner type of an EIP-712 message

type TypePriority added in v1.4.43

type TypePriority struct {
	Type  string
	Value uint
}

type TypedData added in v1.4.43

type TypedData struct {
	Types       Types            `json:"types"`
	PrimaryType string           `json:"primaryType"`
	Domain      TypedDataDomain  `json:"domain"`
	Message     TypedDataMessage `json:"message"`
}

func (*TypedData) Dependencies added in v1.4.43

func (typedData *TypedData) Dependencies(primaryType string, found []string) []string

Dependencies returns an array of custom types ordered by their hierarchical reference tree

func (*TypedData) EncodeData added in v1.4.43

func (typedData *TypedData) EncodeData(primaryType string, data map[string]interface{}, depth int) (hexutil.Bytes, error)

EncodeData generates the following encoding: `enc(value₁) ‖ enc(value₂) ‖ … ‖ enc(valueₙ)`

each encoded member is 32-byte long

func (*TypedData) EncodePrimitiveValue added in v1.4.43

func (typedData *TypedData) EncodePrimitiveValue(encType string, encValue interface{}, depth int) ([]byte, error)

EncodePrimitiveValue deals with the primitive values found while searching through the typed data

func (*TypedData) EncodeType added in v1.4.43

func (typedData *TypedData) EncodeType(primaryType string) hexutil.Bytes

EncodeType generates the following encoding: `name ‖ "(" ‖ member₁ ‖ "," ‖ member₂ ‖ "," ‖ … ‖ memberₙ ")"`

each member is written as `type ‖ " " ‖ name` encodings cascade down and are sorted by name

func (*TypedData) Format added in v1.4.43

func (typedData *TypedData) Format() ([]*NameValueType, error)

Format returns a representation of typedData, which can be easily displayed by a user-interface without in-depth knowledge about 712 rules

func (*TypedData) HashStruct added in v1.4.43

func (typedData *TypedData) HashStruct(primaryType string, data TypedDataMessage) (hexutil.Bytes, error)

HashStruct generates a keccak256 hash of the encoding of the provided data

func (*TypedData) Map added in v1.4.43

func (typedData *TypedData) Map() map[string]interface{}

Map generates a map version of the typed data

func (*TypedData) TypeHash added in v1.4.43

func (typedData *TypedData) TypeHash(primaryType string) hexutil.Bytes

TypeHash creates the keccak256 hash of the data

type TypedDataDomain added in v1.4.43

type TypedDataDomain struct {
	Name              string                `json:"name"`
	Version           string                `json:"version"`
	ChainId           *math.HexOrDecimal256 `json:"chainId"`
	VerifyingContract string                `json:"verifyingContract"`
	Salt              string                `json:"salt"`
}

TypedDataDomain represents the domain part of an EIP-712 message.

func (*TypedDataDomain) Map added in v1.4.43

func (domain *TypedDataDomain) Map() map[string]interface{}

Map is a helper function to generate a map version of the domain

type TypedDataMessage added in v1.4.43

type TypedDataMessage = map[string]interface{}

type Types added in v1.4.43

type Types map[string][]Type

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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