entities

package
v0.1.6 Latest Latest
Warning

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

Go to latest
Published: Jun 16, 2023 License: MIT Imports: 13 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInsufficientReserves doesn't have insufficient reserves
	ErrInsufficientReserves = errors.New("doesn't have insufficient reserves")
	// ErrInsufficientInputAmount the input amount insufficient reserves
	ErrInsufficientInputAmount = errors.New("the input amount insufficient reserves")
)
View Source
var (

	// ErrInvalidLiquidity invalid liquidity
	ErrInvalidLiquidity = fmt.Errorf("invalid liquidity")
	// ErrInvalidKLast invalid kLast
	ErrInvalidKLast = fmt.Errorf("invalid kLast")
)
View Source
var (
	ErrInvalidPairs         = fmt.Errorf("invalid pairs")
	ErrInvalidPairsChainIDs = fmt.Errorf("invalid pairs chainIDs")
	ErrInvalidInput         = fmt.Errorf("invalid token input")
	ErrInvalidOutput        = fmt.Errorf("invalid token output")
	ErrInvalidPath          = fmt.Errorf("invalid pairs for path")
)
View Source
var (
	ErrDiffChainID = fmt.Errorf("diff chain id")
	ErrDiffToken   = fmt.Errorf("diff token")
	ErrSameAddrss  = fmt.Errorf("same address")

	WETH = map[constants.ChainID]*Token{
		constants.Mainnet: {
			Currency: _WETHCurrency,
			ChainID:  constants.Mainnet,
			Address:  utils.ValidateAndParseAddress("0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c"),
		},
		constants.Testnet: {
			Currency: _WETHCurrency,
			ChainID:  constants.Testnet,
			Address:  utils.ValidateAndParseAddress("0xaE8E19eFB41e7b96815649A6a60785e1fbA84C1e"),
		},
	}
)
View Source
var (
	ErrInvalidOption    = fmt.Errorf("invalid maxHops")
	ErrInvalidRecursion = fmt.Errorf("invalid recursion")
)
View Source
var (
	ETHER, _ = newCurrency(constants.Decimals18, "ETH", "Ether")
)

*

  • The only instance of the base class `Currency`.
View Source
var (
	// ErrInvalidCurrency diff currency error
	ErrInvalidCurrency = fmt.Errorf("diff currency")
)
View Source
var (
	ErrInvalidSlippageTolerance = fmt.Errorf("invalid slippage tolerance")
)
View Source
var (
	// Percent100 percent 100
	Percent100 = NewFraction(constants.B100, constants.One)
)
View Source
var (
	// ZeroFraction zero fraction instance
	ZeroFraction = NewFraction(constants.Zero, nil)
)

Functions

func InputOutputComparator

func InputOutputComparator(a, b InputOutput) int

comparator function that allows sorting trades by their output amounts, in decreasing order, and then input amounts in increasing order. i.e. the best trades have the most outputs for the least inputs and are sorted first

func SortedInsert

func SortedInsert(items []*Trade, add *Trade, maxSize int, comparator func(a, b *Trade) int) (sortedItems []*Trade, pop *Trade, err error)

given an array of items sorted by `comparator`, insert an item into its sort index and constrain the size to `maxSize` by removing the last item

func TradeComparator

func TradeComparator(a, b *Trade) int

extension of the input output comparator that also considers other dimensions of the trade in ranking them

Types

type BestTradeOptions

type BestTradeOptions struct {
	// how many results to return
	MaxNumResults int
	// the maximum number of hops a trade should contain
	MaxHops int
}

func NewDefaultBestTradeOptions

func NewDefaultBestTradeOptions() *BestTradeOptions

func (*BestTradeOptions) ReduceHops

func (o *BestTradeOptions) ReduceHops() *BestTradeOptions

type Currency

type Currency struct {
	Decimals int
	Symbol   string
	Name     string
}

Currency is any fungible financial instrument on Ethereum, including Ether and all ERC20 tokens.

func (*Currency) Equals

func (c *Currency) Equals(other *Currency) bool

Equals identifies whether A and B are equal

type CurrencyAmount

type CurrencyAmount struct {
	*Fraction
	*Currency
}

CurrencyAmount warps Fraction and Currency

func NewCurrencyAmount

func NewCurrencyAmount(currency *Currency, amount *big.Int) (*CurrencyAmount, error)

NewCurrencyAmount creates a CurrencyAmount amount _must_ be raw, i.e. in the native representation

func NewEther

func NewEther(amount *big.Int) (*CurrencyAmount, error)

NewEther Helper that calls the constructor with the ETHER currency @param amount ether amount in wei

func (*CurrencyAmount) Raw

func (c *CurrencyAmount) Raw() *big.Int

Raw returns Fraction's Numerator

type Fraction

type Fraction struct {
	Numerator   *big.Int
	Denominator *big.Int
	// contains filtered or unexported fields
}

Fraction warps math franction

func NewFraction

func NewFraction(num, deno *big.Int) *Fraction

NewFraction creates a fraction

func (*Fraction) Add

func (f *Fraction) Add(other *Fraction) *Fraction

Add adds two fraction and returns a new fraction nolint dupl

func (*Fraction) Divide

func (f *Fraction) Divide(other *Fraction) *Fraction

Divide mul div two fraction and returns a new fraction

func (*Fraction) EqualTo

func (f *Fraction) EqualTo(other *Fraction) bool

EqualTo identifies whether the caller is equal to the other

func (*Fraction) GreaterThan

func (f *Fraction) GreaterThan(other *Fraction) bool

GreaterThan identifies whether the caller is greater than the other

func (*Fraction) Invert

func (f *Fraction) Invert() *Fraction

Invert inverts a fraction

func (*Fraction) LessThan

func (f *Fraction) LessThan(other *Fraction) bool

LessThan identifies whether the caller is less than the other

func (*Fraction) Multiply

func (f *Fraction) Multiply(other *Fraction) *Fraction

Multiply mul two fraction and returns a new fraction

func (*Fraction) Quotient

func (f *Fraction) Quotient() *big.Int

Quotient performs floor division

func (*Fraction) Remainder

func (f *Fraction) Remainder() *Fraction

Remainder remainder after floor division

func (*Fraction) Subtract

func (f *Fraction) Subtract(other *Fraction) *Fraction

Add subtracts two fraction and returns a new fraction nolint dupl

func (*Fraction) ToFixed

func (f *Fraction) ToFixed(decimalPlaces uint, opt ...number.Option) string

ToFixed format output

func (*Fraction) ToSignificant

func (f *Fraction) ToSignificant(significantDigits uint, opt ...number.Option) string

ToSignificant format output

type InputOutput

type InputOutput interface {
	InputAmount() *TokenAmount
	OutputAmount() *TokenAmount
}

minimal interface so the input output comparator may be shared across types

type Pair

type Pair struct {
	LiquidityToken *Token
	// sorted tokens
	TokenAmounts
	Rate          *big.Int
	Price0Float64 float64
	Price1Float64 float64
}

Pair warps uniswap pair

func NewPair

func NewPair(tokenAmountA, tokenAmountB *TokenAmount) (*Pair, error)

NewPair creates Pair

func (*Pair) ChainID

func (p *Pair) ChainID() constants.ChainID

ChainID Returns the chain ID of the tokens in the pair.

func (*Pair) GetAddress

func (p *Pair) GetAddress() common.Address

GetAddress returns a contract's address for a pair

func (*Pair) GetInputAmount

func (p *Pair) GetInputAmount(outputAmount *TokenAmount) (*TokenAmount, *Pair, error)

GetInputAmount returns InputAmout and a Pair for the OutputAmount

func (*Pair) GetLiquidityMinted

func (p *Pair) GetLiquidityMinted(totalSupply, tokenAmountA, tokenAmountB *TokenAmount) (*TokenAmount, error)

GetLiquidityMinted returns liquidity minted TokenAmount

func (*Pair) GetLiquidityValue

func (p *Pair) GetLiquidityValue(token *Token, totalSupply, liquidity *TokenAmount, feeOn bool, kLast *big.Int) (*TokenAmount, error)

GetLiquidityValue returns liquidity value TokenAmount

func (*Pair) GetOutputAmount

func (p *Pair) GetOutputAmount(inputAmount *TokenAmount) (*TokenAmount, *Pair, error)

GetOutputAmount returns OutputAmount and a Pair for the InputAmout

func (*Pair) InvolvesToken

func (p *Pair) InvolvesToken(token *Token) bool

InvolvesToken Returns true if the token is either token0 or token1 @param token to check

func (*Pair) PriceOf

func (p *Pair) PriceOf(token *Token) (*Price, error)

PriceOf Returns the price of the given token in terms of the other token in the pair. @param token token to return price of

func (*Pair) Reserve0

func (p *Pair) Reserve0() *TokenAmount

Reserve0 returns the first TokenAmount in the pair

func (*Pair) Reserve1

func (p *Pair) Reserve1() *TokenAmount

Reserve1 returns the last TokenAmount in the pair

func (*Pair) ReserveOf

func (p *Pair) ReserveOf(token *Token) (*TokenAmount, error)

ReserveOf returns the TokenAmount that equals to the token

func (*Pair) Token0

func (p *Pair) Token0() *Token

Token0 returns the first token in the pair

func (*Pair) Token0Price

func (p *Pair) Token0Price() *Price

Token0Price Returns the current mid price of the pair in terms of token0, i.e. the ratio of reserve1 to reserve0

func (*Pair) Token1

func (p *Pair) Token1() *Token

Token1 returns the last token in the pair

func (*Pair) Token1Price

func (p *Pair) Token1Price() *Price

Token1Price Returns the current mid price of the pair in terms of token1, i.e. the ratio of reserve0 to reserve1

func (*Pair) UpdatePrice added in v0.1.6

func (p *Pair) UpdatePrice() bool

type PairAddressCache

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

PairAddressCache warps pair address cache

func (*PairAddressCache) GetAddress

func (p *PairAddressCache) GetAddress(addressA, addressB common.Address) common.Address

GetAddress returns contract address addressA < addressB

type Percent

type Percent struct {
	*Fraction
}

Percent warps Fraction

func NewPercent

func NewPercent(num, deno *big.Int) *Percent

NewPercent creates Percent

func (*Percent) ToFixed

func (p *Percent) ToFixed(decimalPlaces uint, opt ...number.Option) string

ToFixed format output

func (*Percent) ToSignificant

func (p *Percent) ToSignificant(significantDigits uint, opt ...number.Option) string

ToSignificant format output

type Price

type Price struct {
	*Fraction
	BaseCurrency  *Currency // input i.e. denominator
	QuoteCurrency *Currency // output i.e. numerator
	Scalar        *Fraction // used to adjust the raw fraction w/r/t the decimals of the {base,quote}Token
}

func NewPrice

func NewPrice(baseCurrency, quoteCurrency *Currency, denominator, numerator *big.Int) *Price

denominator and numerator _must_ be raw, i.e. in the native representation

func NewPriceFromRoute

func NewPriceFromRoute(route *Route) (*Price, error)

func (*Price) Adjusted

func (p *Price) Adjusted() *Fraction

func (*Price) Invert

func (p *Price) Invert() *Price

func (*Price) Multiply

func (p *Price) Multiply(other *Price) (*Price, error)

func (*Price) Quote

func (p *Price) Quote(currencyAmount *CurrencyAmount) (*CurrencyAmount, error)

performs floor division on overflow

func (*Price) Raw

func (p *Price) Raw() *Fraction

func (*Price) ToFixed

func (p *Price) ToFixed(decimalPlaces uint, opt ...number.Option) string

func (*Price) ToSignificant

func (p *Price) ToSignificant(significantDigits uint, opt ...number.Option) string

type Route

type Route struct {
	Pairs    []*Pair
	Path     []*Token
	Input    *Token
	Output   *Token
	MidPrice *Price
}

func NewRoute

func NewRoute(pairs []*Pair, input, output *Token) (*Route, error)

func (*Route) ChainID

func (r *Route) ChainID() constants.ChainID

type Token

type Token struct {
	*Currency

	constants.ChainID
	common.Address
}

*

  • Represents an ERC20 token with a unique address and some metadata.

func NewETHRToken

func NewETHRToken(chainID constants.ChainID, address common.Address) *Token

NewETHRToken creates a token that currency is ETH

func NewToken

func NewToken(chainID constants.ChainID, address common.Address, decimals int, symbol, name string) (*Token, error)

func (*Token) Equals

func (t *Token) Equals(other *Token) bool

*

  • Returns true if the two tokens are equivalent, i.e. have the same chainId and address.
  • @param other other token to compare

func (*Token) SortsBefore

func (t *Token) SortsBefore(other *Token) (bool, error)

*

  • Returns true if the address of this token sorts before the address of the other token
  • @param other other token to compare
  • @throws if the tokens have the same address
  • @throws if the tokens are on different chains

type TokenAmount

type TokenAmount struct {
	*CurrencyAmount
	Token *Token
}

func NewTokenAmount

func NewTokenAmount(token *Token, amount *big.Int) (*TokenAmount, error)

amount _must_ be raw, i.e. in the native representation

func (*TokenAmount) Add

func (t *TokenAmount) Add(other *TokenAmount) (*TokenAmount, error)

func (*TokenAmount) Equals

func (t *TokenAmount) Equals(other *TokenAmount) bool

func (*TokenAmount) Subtract

func (t *TokenAmount) Subtract(other *TokenAmount) (*TokenAmount, error)

type TokenAmounts

type TokenAmounts [2]*TokenAmount

TokenAmounts warps TokenAmount array

func NewTokenAmounts

func NewTokenAmounts(tokenAmountA, tokenAmountB *TokenAmount) (TokenAmounts, error)

NewTokenAmounts creates a TokenAmount

type Tokens

type Tokens [2]*Token

Tokens warps Token array

type Trade

type Trade struct {
	/**
	 * The route of the trade, i.e. which pairs the trade goes through.
	 */
	Route *Route
	/**
	 * The type of the trade, either exact in or exact out.
	 */
	TradeType constants.TradeType

	/**
	 * The price expressed in terms of output amount/input amount.
	 */
	ExecutionPrice *Price
	/**
	 * The mid price after the trade executes assuming no slippage.
	 */
	NextMidPrice *Price
	/**
	 * The percent difference between the mid price before the trade and the trade execution price.
	 */
	PriceImpact *Percent
	// contains filtered or unexported fields
}

Trade Represents a trade executed against a list of pairs. Does not account for slippage, i.e. trades that front run this trade and move the price.

func BestTradeExactIn

func BestTradeExactIn(
	pairs []*Pair,
	currencyAmountIn *TokenAmount,
	currencyOut *Token,
	options *BestTradeOptions,

	currentPairs []*Pair,
	originalAmountIn *TokenAmount,
	bestTrades []*Trade,
) (sortedItems []*Trade, err error)

*

  • Given a list of pairs, and a fixed amount in, returns the top `maxNumResults` trades that go from an input token
  • amount to an output token, making at most `maxHops` hops.
  • Note this does not consider aggregation, as routes are linear. It's possible a better route exists by splitting
  • the amount in among multiple routes.
  • @param pairs the pairs to consider in finding the best trade
  • @param currencyAmountIn exact amount of input currency to spend
  • @param currencyOut the desired currency out
  • @param maxNumResults maximum number of results to return
  • @param maxHops maximum number of hops a returned trade can make, e.g. 1 hop goes through a single pair
  • @param currentPairs used in recursion; the current list of pairs
  • @param originalAmountIn used in recursion; the original value of the currencyAmountIn parameter
  • @param bestTrades used in recursion; the current list of best trades

func BestTradeExactOut

func BestTradeExactOut(
	pairs []*Pair,
	currencyIn *Token,
	currencyAmountOut *TokenAmount,
	options *BestTradeOptions,

	currentPairs []*Pair,
	originalAmountOut *TokenAmount,
	bestTrades []*Trade,
) (sortedItems []*Trade, err error)

*

  • similar to the above method but instead targets a fixed output amount
  • given a list of pairs, and a fixed amount out, returns the top `maxNumResults` trades that go from an input token
  • to an output token amount, making at most `maxHops` hops
  • note this does not consider aggregation, as routes are linear. it's possible a better route exists by splitting
  • the amount in among multiple routes.
  • @param pairs the pairs to consider in finding the best trade
  • @param currencyIn the currency to spend
  • @param currencyAmountOut the exact amount of currency out
  • @param maxNumResults maximum number of results to return
  • @param maxHops maximum number of hops a returned trade can make, e.g. 1 hop goes through a single pair
  • @param currentPairs used in recursion; the current list of pairs
  • @param originalAmountOut used in recursion; the original value of the currencyAmountOut parameter
  • @param bestTrades used in recursion; the current list of best trades

func ExactIn

func ExactIn(route *Route, amountIn *TokenAmount) (*Trade, error)

*

  • Constructs an exact in trade with the given amount in and route
  • @param route route of the exact in trade
  • @param amountIn the amount being passed in

func ExactOut

func ExactOut(route *Route, amountOut *TokenAmount) (*Trade, error)

*

  • Constructs an exact out trade with the given amount out and route
  • @param route route of the exact out trade
  • @param amountOut the amount returned by the trade

func NewTrade

func NewTrade(route *Route, amount *TokenAmount, tradeType constants.TradeType) (*Trade, error)

NewTrade creates a new trade nolint gocyclo

func (*Trade) InputAmount

func (t *Trade) InputAmount() *TokenAmount

func (*Trade) MaximumAmountIn

func (t *Trade) MaximumAmountIn(slippageTolerance *Percent) (*TokenAmount, error)

*

  • Get the maximum amount in that can be spent via this trade for the given slippage tolerance
  • @param slippageTolerance tolerance of unfavorable slippage from the execution price of this trade

func (*Trade) MinimumAmountOut

func (t *Trade) MinimumAmountOut(slippageTolerance *Percent) (*TokenAmount, error)

*

  • Get the minimum amount that must be received from this trade for the given slippage tolerance
  • @param slippageTolerance tolerance of unfavorable slippage from the execution price of this trade

func (*Trade) OutputAmount

func (t *Trade) OutputAmount() *TokenAmount

Jump to

Keyboard shortcuts

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