entities

package
v0.5.2 Latest Latest
Warning

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

Go to latest
Published: Jun 14, 2024 License: MIT Imports: 10 Imported by: 4

Documentation

Index

Constants

View Source
const (
	ZeroValueTickIndex       = 0
	ZeroValueTickInitialized = false
)

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")
	ErrEmptyTickList      = errors.New("empty tick list")
	ErrBelowSmallest      = errors.New("below smallest")
	ErrAtOrAboveLargest   = errors.New("at or above largest")
	ErrInvalidTickIndex   = errors.New("invalid tick index")
)
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")
)
View Source
var (
	EmptyTick = Tick{}
)

Functions

func GetAddress

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

func IsAtOrAboveLargest

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

func IsBelowSmallest

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

func NearestUsableTick

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 NextInitializedTickIndex

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

func NextInitializedTickWithinOneWord

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

func Round

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

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 GetAmountResult

type GetAmountResult struct {
	ReturnedAmount     *entities.CurrencyAmount
	RemainingAmountIn  *entities.CurrencyAmount
	NewPoolState       *Pool
	CrossInitTickLoops int
}

type GetAmountResultV2

type GetAmountResultV2 struct {
	ReturnedAmount     *utils.Int256
	RemainingAmountIn  *utils.Int256
	SqrtRatioX96       *utils.Uint160
	Liquidity          *utils.Uint128
	CurrentTick        int
	CrossInitTickLoops int
}

type Pool

type Pool struct {
	Token0           *entities.Token
	Token1           *entities.Token
	Fee              constants.FeeAmount
	SqrtRatioX96     *utils.Uint160
	Liquidity        *utils.Uint128
	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)

deprecated

func NewPoolV2

func NewPoolV2(tokenA, tokenB *entities.Token, fee constants.FeeAmount, sqrtRatioX96 *utils.Uint160, liquidity *utils.Uint128, 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 *utils.Uint160) (*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 *utils.Uint160) (*GetAmountResult, 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) GetOutputAmountV2

func (p *Pool) GetOutputAmountV2(inputAmount *utils.Int256, zeroForOne bool, sqrtPriceLimitX96 *utils.Uint160) (*GetAmountResultV2, error)

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

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

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

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

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

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

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

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

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

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

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

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

Token0PriceLower Returns the price of token0 at the lower tick

func (*Position) Token0PriceUpper

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 SwapResult

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

type Tick

type Tick struct {
	Index          int
	LiquidityGross *uint256.Int
	LiquidityNet   *utils.Int128
}

func GetTick

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

func NextInitializedTick

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

type TickDataProvider

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

	/**
	 * 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, error)

	// NextInitializedTickIndex return the next tick that is initialized
	NextInitializedTickIndex(tick int, lte bool) (int, bool, error)
}

Provides information about ticks

type TickListDataProvider

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

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

func (*TickListDataProvider) GetTick

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

func (*TickListDataProvider) NextInitializedTickIndex

func (p *TickListDataProvider) NextInitializedTickIndex(tick int, lte bool) (int, bool, error)

func (*TickListDataProvider) NextInitializedTickWithinOneWord

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

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