entities

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2022 License: MIT Imports: 8 Imported by: 23

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrFeeTooHigh               = errors.New("Fee too high")
	ErrInvalidSqrtRatioX96      = errors.New("Invalid sqrtRatioX96")
	ErrTokenNotInvolved         = errors.New("Token not involved in pool")
	ErrSqrtPriceLimitX96TooLow  = errors.New("SqrtPriceLimitX96 too low")
	ErrSqrtPriceLimitX96TooHigh = errors.New("SqrtPriceLimitX96 too high")
)
View Source
var (
	ErrTickOrder = errors.New("tick order error")
	ErrTickLower = errors.New("tick lower error")
	ErrTickUpper = errors.New("tick upper error")
)
View Source
var (
	ErrRouteNoPools      = errors.New("route must have at least one pool")
	ErrAllOnSameChain    = errors.New("all pools must be on the same chain")
	ErrInputNotInvolved  = errors.New("input token not involved in route")
	ErrOutputNotInvolved = errors.New("output token not involved in route")
	ErrPathNotContinuous = errors.New("path not continuous")
)
View Source
var (
	ErrZeroTickSpacing    = errors.New("tick spacing must be greater than 0")
	ErrInvalidTickSpacing = errors.New("invalid tick spacing")
	ErrZeroNet            = errors.New("tick net delta must be zero")
	ErrSorted             = errors.New("ticks must be sorted")
)
View Source
var (
	ErrTradeHasMultipleRoutes   = errors.New("trade has multiple routes")
	ErrInvalidAmountForRoute    = errors.New("invalid amount for route")
	ErrInputCurrencyMismatch    = errors.New("input currency mismatch")
	ErrOutputCurrencyMismatch   = errors.New("output currency mismatch")
	ErrDuplicatePools           = errors.New("duplicate pools")
	ErrInvalidSlippageTolerance = errors.New("invalid slippage tolerance")
	ErrNoPools                  = errors.New("no pools")
	ErrInvalidMaxHops           = errors.New("invalid max hops")
	ErrInvalidRecursion         = errors.New("invalid recursion")
	ErrInvalidMaxSize           = errors.New("invalid max size")
	ErrMaxSizeExceeded          = errors.New("max size exceeded")
)

Functions

func GetAddress

func GetAddress(tokenA, tokenB *entities.Token, fee constants.FeeAmount, initCodeHashManualOverride string) (common.Address, error)

func IsAtOrAboveLargest added in v0.0.2

func IsAtOrAboveLargest(ticks []Tick, tick int) bool

func IsBelowSmallest added in v0.0.2

func IsBelowSmallest(ticks []Tick, tick int) bool

func NearestUsableTick added in v0.0.2

func NearestUsableTick(tick int, tickSpacing int) int

*

  • Returns the closest tick that is nearest a given tick and usable for the given tick spacing
  • @param tick the target tick
  • @param tickSpacing the spacing of the pool

func NextInitializedTickWithinOneWord added in v0.0.2

func NextInitializedTickWithinOneWord(ticks []Tick, tick int, lte bool, tickSpacing int) (int, bool)

func Round added in v0.0.2

func Round(x float64) float64

Round like javascript Math.round Note that this differs from many languages' round() functions, which often round this case to the next integer away from zero, instead giving a different result in the case of negative numbers with a fractional part of exactly 0.5. For example, -1.5 rounds to -2, but -1.5 rounds to -1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round#description

func ValidateList added in v0.0.2

func ValidateList(ticks []Tick, tickSpacing int) error

Types

type BestTradeOptions

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

type Pool

type Pool struct {
	Token0           *entities.Token
	Token1           *entities.Token
	Fee              constants.FeeAmount
	SqrtRatioX96     *big.Int
	Liquidity        *big.Int
	TickCurrent      int
	TickDataProvider TickDataProvider
	// contains filtered or unexported fields
}

Represents a V3 pool

func NewPool

func NewPool(tokenA, tokenB *entities.Token, fee constants.FeeAmount, sqrtRatioX96 *big.Int, liquidity *big.Int, tickCurrent int, ticks TickDataProvider) (*Pool, error)

*

  • Construct a pool
  • @param tokenA One of the tokens in the pool
  • @param tokenB The other token in the pool
  • @param fee The fee in hundredths of a bips of the input amount of every swap that is collected by the pool
  • @param sqrtRatioX96 The sqrt of the current ratio of amounts of token1 to token0
  • @param liquidity The current value of in range liquidity
  • @param tickCurrent The current tick of the pool
  • @param ticks The current state of the pool ticks or a data provider that can return tick data

func (*Pool) ChainID

func (p *Pool) ChainID() uint

ChainId returns the chain ID of the tokens in the pool.

func (*Pool) GetInputAmount

func (p *Pool) GetInputAmount(outputAmount *entities.CurrencyAmount, sqrtPriceLimitX96 *big.Int) (*entities.CurrencyAmount, *Pool, error)

*

  • Given a desired output amount of a token, return the computed input amount and a pool with state updated after the trade
  • @param outputAmount the output amount for which to quote the input amount
  • @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this value after the swap. If one for zero, the price cannot be greater than this value after the swap
  • @returns The input amount and the pool with updated state

func (*Pool) GetOutputAmount

func (p *Pool) GetOutputAmount(inputAmount *entities.CurrencyAmount, sqrtPriceLimitX96 *big.Int) (*entities.CurrencyAmount, *Pool, error)

*

  • Given an input amount of a token, return the computed output amount, and a pool with state updated after the trade
  • @param inputAmount The input amount for which to quote the output amount
  • @param sqrtPriceLimitX96 The Q64.96 sqrt price limit
  • @returns The output amount and the pool with updated state

func (*Pool) InvolvesToken

func (p *Pool) InvolvesToken(token *entities.Token) bool

*

  • Returns true if the token is either token0 or token1
  • @param token The token to check
  • @returns True if token is either token0 or token

func (*Pool) PriceOf

func (p *Pool) PriceOf(token *entities.Token) (*entities.Price, error)

*

  • Return the price of the given token in terms of the other token in the pool.
  • @param token The token to return price of
  • @returns The price of the given token, in terms of the other.

func (*Pool) Token0Price

func (p *Pool) Token0Price() *entities.Price

Token0Price returns the current mid price of the pool in terms of token0, i.e. the ratio of token1 over token0

func (*Pool) Token1Price

func (p *Pool) Token1Price() *entities.Price

Token1Price returns the current mid price of the pool in terms of token1, i.e. the ratio of token0 over token1

type Position added in v0.2.0

type Position struct {
	Pool      *Pool
	TickLower int
	TickUpper int
	Liquidity *big.Int
	// contains filtered or unexported fields
}

Position Represents a position on a Uniswap V3 Pool

func FromAmount0 added in v0.2.0

func FromAmount0(pool *Pool, tickLower, tickUpper int, amount0 *big.Int, useFullPrecision bool) (*Position, error)

*

  • Computes a position with the maximum amount of liquidity received for a given amount of token0, assuming an unlimited amount of token1
  • @param pool The pool for which the position is created
  • @param tickLower The lower tick
  • @param tickUpper The upper tick
  • @param amount0 The desired amount of token0
  • @param useFullPrecision If true, liquidity will be maximized according to what the router can calculate,
  • not what core can theoretically support
  • @returns The position

func FromAmount1 added in v0.2.0

func FromAmount1(pool *Pool, tickLower, tickUpper int, amount1 *big.Int) (*Position, error)

*

  • Computes a position with the maximum amount of liquidity received for a given amount of token1, assuming an unlimited amount of token0
  • @param pool The pool for which the position is created
  • @param tickLower The lower tick
  • @param tickUpper The upper tick
  • @param amount1 The desired amount of token1
  • @returns The position

func FromAmounts added in v0.2.0

func FromAmounts(pool *Pool, tickLower, tickUpper int, amount0, amount1 *big.Int, useFullPrecision bool) (*Position, error)

*

  • Computes the maximum amount of liquidity received for a given amount of token0, token1,
  • and the prices at the tick boundaries.
  • @param pool The pool for which the position should be created
  • @param tickLower The lower tick of the position
  • @param tickUpper The upper tick of the position
  • @param amount0 token0 amount
  • @param amount1 token1 amount
  • @param useFullPrecision If false, liquidity will be maximized according to what the router can calculate,
  • not what core can theoretically support
  • @returns The amount of liquidity for the position

func NewPosition added in v0.2.0

func NewPosition(pool *Pool, liquidity *big.Int, tickLower int, tickUpper int) (*Position, error)

*

  • Constructs a position for a given pool with the given liquidity
  • @param pool For which pool the liquidity is assigned
  • @param liquidity The amount of liquidity that is in the position
  • @param tickLower The lower tick of the position
  • @param tickUpper The upper tick of the position

func (*Position) Amount0 added in v0.2.0

func (p *Position) Amount0() (*entities.CurrencyAmount, error)

Amount0 Returns the amount of token0 that this position's liquidity could be burned for at the current pool price

func (*Position) Amount1 added in v0.2.0

func (p *Position) Amount1() (*entities.CurrencyAmount, error)

Amount1 Returns the amount of token1 that this position's liquidity could be burned for at the current pool price

func (*Position) BurnAmountsWithSlippage added in v0.2.0

func (p *Position) BurnAmountsWithSlippage(slippageTolerance *entities.Percent) (amount0, amount1 *big.Int, err error)

*

  • Returns the minimum amounts that should be requested in order to safely burn the amount of liquidity held by the
  • position with the given slippage tolerance
  • @param slippageTolerance tolerance of unfavorable slippage from the current price
  • @returns The amounts, with slippage

func (*Position) MintAmounts added in v0.2.0

func (p *Position) MintAmounts() (amount0, amount1 *big.Int, err error)

*

  • Returns the minimum amounts that must be sent in order to mint the amount of liquidity held by the position at
  • the current price for the pool

func (*Position) MintAmountsWithSlippage added in v0.2.0

func (p *Position) MintAmountsWithSlippage(slippageTolerance *entities.Percent) (amount0, amount1 *big.Int, err error)

* * Returns the minimum amounts that must be sent in order to safely mint the amount of liquidity held by the position * with the given slippage tolerance * @param slippageTolerance Tolerance of unfavorable slippage from the current price * @returns The amounts, with slippage

func (*Position) Token0PriceLower added in v0.2.0

func (p *Position) Token0PriceLower() (*entities.Price, error)

Token0PriceLower Returns the price of token0 at the lower tick

func (*Position) Token0PriceUpper added in v0.2.0

func (p *Position) Token0PriceUpper() (*entities.Price, error)

Token0PriceUpper Returns the price of token0 at the upper tick

type Route

type Route struct {
	Pools     []*Pool
	TokenPath []*entities.Token
	Input     entities.Currency
	Output    entities.Currency
	// contains filtered or unexported fields
}

Route represents a list of pools through which a swap can occur

func NewRoute

func NewRoute(pools []*Pool, input, output entities.Currency) (*Route, error)

*

  • Creates an instance of route.
  • @param pools An array of `Pool` objects, ordered by the route the swap will take
  • @param input The input token
  • @param output The output token

func (*Route) ChainID

func (r *Route) ChainID() uint

func (*Route) MidPrice

func (r *Route) MidPrice() (*entities.Price, error)

MidPrice Returns the mid price of the route

type StepComputations

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

type Swap

type Swap struct {
	Route        *Route
	InputAmount  *entities.CurrencyAmount
	OutputAmount *entities.CurrencyAmount
}

type Tick

type Tick struct {
	Index          int
	LiquidityGross *big.Int
	LiquidityNet   *big.Int
}

func GetTick added in v0.0.2

func GetTick(ticks []Tick, index int) Tick

func NextInitializedTick added in v0.0.2

func NextInitializedTick(ticks []Tick, tick int, lte bool) Tick

type TickDataProvider

type TickDataProvider interface {
	/**
	 * Return information corresponding to a specific tick
	 * @param tick the tick to load
	 */
	GetTick(tick int) Tick

	/**
	 * Return the next tick that is initialized within a single word
	 * @param tick The current tick
	 * @param lte Whether the next tick should be lte the current tick
	 * @param tickSpacing The tick spacing of the pool
	 */
	NextInitializedTickWithinOneWord(tick int, lte bool, tickSpacing int) (int, bool)
}

Provides information about ticks

type TickListDataProvider added in v0.0.2

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

A data provider for ticks that is backed by an in-memory array of ticks.

func NewTickListDataProvider added in v0.0.2

func NewTickListDataProvider(ticks []Tick, tickSpacing int) (*TickListDataProvider, error)

func (*TickListDataProvider) GetTick added in v0.0.2

func (p *TickListDataProvider) GetTick(tick int) Tick

func (*TickListDataProvider) NextInitializedTickWithinOneWord added in v0.0.2

func (p *TickListDataProvider) NextInitializedTickWithinOneWord(tick int, lte bool, tickSpacing int) (int, bool)

type Trade

type Trade struct {
	Swaps     []*Swap            // The swaps of the trade, i.e. which routes and how much is swapped in each that make up the trade.
	TradeType entities.TradeType // The type of trade, i.e. exact input or exact output
	// contains filtered or unexported fields
}

*

  • Represents a trade executed against a set of routes where some percentage of the input is
  • split across each route. *
  • Each route has its own set of pools. Pools can not be re-used across routes. *
  • Does not account for slippage, i.e., changes in price environment that can occur between
  • the time the trade is submitted and when it is executed.

func BestTradeExactIn

func BestTradeExactIn(pools []*Pool, currencyAmountIn *entities.CurrencyAmount, currencyOut entities.Currency, opts *BestTradeOptions, currentPools []*Pool, nextAmountIn *entities.CurrencyAmount, bestTrades []*Trade) ([]*Trade, error)

*

  • Given a list of pools, 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 pools the pools to consider in finding the best trade
  • @param nextAmountIn 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 pool
  • @param currentPools used in recursion; the current list of pools
  • @param currencyAmountIn used in recursion; the original value of the currencyAmountIn parameter
  • @param bestTrades used in recursion; the current list of best trades
  • @returns The exact in trade

func BestTradeExactOut

func BestTradeExactOut(pools []*Pool, currencyIn entities.Currency, currencyAmountOut *entities.CurrencyAmount, opts *BestTradeOptions, currentPools []*Pool, nextAmountOut *entities.CurrencyAmount, bestTrades []*Trade) ([]*Trade, error)

*

  • similar to the above method but instead targets a fixed output amount
  • given a list of pools, 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 pools the pools to consider in finding the best trade
  • @param currencyIn the currency to spend
  • @param currencyAmountOut the desired currency amount out
  • @param nextAmountOut 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 pool
  • @param currentPools used in recursion; the current list of pools
  • @param bestTrades used in recursion; the current list of best trades
  • @returns The exact out trade

func CreateUncheckedTrade

func CreateUncheckedTrade(route *Route, inputAmount, outputAmount *entities.CurrencyAmount, tradeType entities.TradeType) (*Trade, error)

*

  • Creates a trade without computing the result of swapping through the route. Useful when you have simulated the trade
  • elsewhere and do not have any tick data
  • @template TInput The input token, either Ether or an ERC-20
  • @template TOutput The output token, either Ether or an ERC-20
  • @template TTradeType The type of the trade, either exact in or exact out
  • @param constructorArguments The arguments passed to the trade constructor
  • @returns The unchecked trade

func CreateUncheckedTradeWithMultipleRoutes

func CreateUncheckedTradeWithMultipleRoutes(routes []*Swap, tradeType entities.TradeType) (*Trade, error)

*

  • Creates a trade without computing the result of swapping through the routes. Useful when you have simulated the trade
  • elsewhere and do not have any tick data
  • @template TInput The input token, either Ether or an ERC-20
  • @template TOutput The output token, either Ether or an ERC-20
  • @template TTradeType The type of the trade, either exact in or exact out
  • @param constructorArguments The arguments passed to the trade constructor
  • @returns The unchecked trade

func ExactIn

func ExactIn(route *Route, amountIn *entities.CurrencyAmount) (*Trade, error)

*

  • Constructs an exact in trade with the given amount in and route
  • @template TInput The input token, either Ether or an ERC-20
  • @template TOutput The output token, either Ether or an ERC-20
  • @param route The route of the exact in trade
  • @param amountIn The amount being passed in
  • @returns The exact in trade

func ExactOut

func ExactOut(route *Route, amountOut *entities.CurrencyAmount) (*Trade, error)

*

  • Constructs an exact out trade with the given amount out and route
  • @template TInput The input token, either Ether or an ERC-20
  • @template TOutput The output token, either Ether or an ERC-20
  • @param route The route of the exact out trade
  • @param amountOut The amount returned by the trade
  • @returns The exact out trade

func FromRoute

func FromRoute(route *Route, amount *entities.CurrencyAmount, tradeType entities.TradeType) (*Trade, error)

*

  • Constructs a trade by simulating swaps through the given route
  • @template TInput The input token, either Ether or an ERC-20.
  • @template TOutput The output token, either Ether or an ERC-20.
  • @template TTradeType The type of the trade, either exact in or exact out.
  • @param route route to swap through
  • @param amount the amount specified, either input or output, depending on tradeType
  • @param tradeType whether the trade is an exact input or exact output swap
  • @returns The route

func FromRoutes

func FromRoutes(wrappedRoutes []*WrappedRoute, tradeType entities.TradeType) (*Trade, error)

*

  • Constructs a trade from routes by simulating swaps *
  • @template TInput The input token, either Ether or an ERC-20.
  • @template TOutput The output token, either Ether or an ERC-20.
  • @template TTradeType The type of the trade, either exact in or exact out.
  • @param routes the routes to swap through and how much of the amount should be routed through each
  • @param tradeType whether the trade is an exact input or exact output swap
  • @returns The trade

func (*Trade) ExecutionPrice

func (t *Trade) ExecutionPrice() *entities.Price

ExecutionPrice the price expressed in terms of output amount/input amount.

func (*Trade) InputAmount

func (t *Trade) InputAmount() *entities.CurrencyAmount

InputAmount the input amount for the trade assuming no slippage.

func (*Trade) MaximumAmountIn

func (t *Trade) MaximumAmountIn(slippageTolerance *entities.Percent, amountIn *entities.CurrencyAmount) (*entities.CurrencyAmount, error)

*

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

func (*Trade) MinimumAmountOut

func (t *Trade) MinimumAmountOut(slippageTolerance *entities.Percent, amountOut *entities.CurrencyAmount) (*entities.CurrencyAmount, error)

*

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

func (*Trade) OutputAmount

func (t *Trade) OutputAmount() *entities.CurrencyAmount

OutputAmount the output amount for the trade assuming no slippage.

func (*Trade) PriceImpact

func (t *Trade) PriceImpact() (*entities.Percent, error)

PriceImpact returns the percent difference between the route's mid price and the price impact

func (*Trade) Route

func (t *Trade) Route() (*Route, error)

*

  • @deprecated Deprecated in favor of 'swaps' property. If the trade consists of multiple routes
  • this will return an error. *
  • When the trade consists of just a single route, this returns the route of the trade,
  • i.e. which pools the trade goes through.

func (*Trade) WorstExecutionPrice

func (t *Trade) WorstExecutionPrice(slippageTolerance *entities.Percent) (*entities.Price, error)

*

  • Return the execution price after accounting for slippage tolerance
  • @param slippageTolerance the allowed tolerated slippage
  • @returns The execution price

type WrappedRoute

type WrappedRoute struct {
	Amount *entities.CurrencyAmount
	Route  *Route
}

Jump to

Keyboard shortcuts

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