uniswap

package
v0.0.6 Latest Latest
Warning

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

Go to latest
Published: May 2, 2022 License: MIT Imports: 8 Imported by: 0

README

🦄 Uniswap v2 SDK

An implementation of the uniswap v2 sdk in golang.

Differences to the original SDK

  • Pair addresses aren't generated automatically and must be looked up on-chain to create a pair
  • Chain ids aren't checked, it's up to the developer to make sure they match
  • No hardcoded implementation of the token from the native currency, must be created like any other token by passing the contract
  • Internal changes:
    • currency is an interface representing tokens and the native currency
    • less functions and types are exported

Documentation

Index

Constants

View Source
const (
	Decimals18  = 18
	Univ2Symbol = "UNI-V2"
	Univ2Name   = "Uniswap V2"
)
View Source
const Zero = "0x0000000000000000000000000000000000000000"

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")
	// ErrNilCurrency currency is nil.
	ErrNilCurrency = errors.New("currency is nil")
)
View Source
var (
	// ErrInvalidLiquidity invalid liquidity.
	ErrInvalidLiquidity = errors.New("invalid liquidity")
	// ErrInvalidKLast invalid kLast.
	ErrInvalidKLast = errors.New("invalid kLast")
	// ErrTokenAmountNil token amount is nil.
	ErrTokenAmountNil = errors.New("token amount is nil")
)
View Source
var (
	ErrInvalidPairs         = errors.New("invalid pairs")
	ErrInvalidPairsChainIDs = errors.New("invalid pairs chainIDs")
	ErrInvalidInput         = errors.New("invalid token input")
	ErrInvalidOutput        = errors.New("invalid token output")
	ErrInvalidPath          = errors.New("invalid pairs for path")
)
View Source
var (
	ErrSameAddrss     = errors.New("same address")
	ErrDiffToken      = errors.New("diff token")
	ErrInvalidAddress = errors.New("invalid address")
)
View Source
var (
	ErrNilToken  = errors.New("token is nil")
	ErrNilAmount = errors.New("amount is nil")
)
View Source
var (
	ErrInvalidOption    = errors.New("invalid maxHops")
	ErrInvalidRecursion = errors.New("invalid recursion")
)
View Source
var ErrInvalidCurrency = errors.New("diff currency")

ErrInvalidCurrency diff currency error.

View Source
var ErrInvalidSlippageTolerance = errors.New("invalid slippage tolerance")
View Source
var ErrRouteNil = errors.New("Route is nil")
View Source
var (
	MinimumLiquidity = big.NewInt(1000)
)
View Source
var Percent100 = NewFraction(big.NewInt(100), big.NewInt(1))

Percent100 percent 100.

View Source
var ZeroFraction = NewFraction(big.NewInt(0), nil)

ZeroFraction zero fraction instance.

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 NewFraction

func NewFraction(numerator, denominator *big.Int) *fraction

NewFraction is the constructor for a fraction.

func SortedInsert

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

SortedInsert is 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

TradeComparator is an 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
	// the exchange fee (9970 = 0.3%)
	DexFee *big.Int
}

func NewDefaultBestTradeOptions

func NewDefaultBestTradeOptions() *BestTradeOptions

NewDefaultBestTradeOptions returns a new BestTradeOptions with default values.

func (*BestTradeOptions) ReduceHops

func (o *BestTradeOptions) ReduceHops() *BestTradeOptions

ReduceHops reduces the number of hops in a trade by 1.

type CurrencyAmount

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

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 NewNative

func NewNative(name, symbol string, decimals uint8, amount *big.Int) (*CurrencyAmount, error)

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

func (CurrencyAmount) Decimal

func (f CurrencyAmount) Decimal() decimal.Decimal

func (CurrencyAmount) Quotient

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

quotient performs floor division.

func (*CurrencyAmount) Raw

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

Raw returns Fraction's Numerator.

func (CurrencyAmount) ToFixed

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

ToFixed format output.

func (CurrencyAmount) ToSignificant

func (f CurrencyAmount) 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 NativeCurrency

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

func NewNativeCurrency

func NewNativeCurrency(name, symbol string, decimals uint8) *NativeCurrency

NewNativeCurrency is the constructor for the native currency.

func (*NativeCurrency) Address

func (c *NativeCurrency) Address() string

Address is the contract address of the currency.

func (*NativeCurrency) CommonAddress

func (c *NativeCurrency) CommonAddress() common.Address

CommonAddress is the common address of the currency.

func (*NativeCurrency) Decimals

func (c *NativeCurrency) Decimals() uint8

Decimals returns the number of decimals for the currency.

func (*NativeCurrency) Name

func (c *NativeCurrency) Name() string

Name returns the name of the currency.

func (*NativeCurrency) Symbol

func (c *NativeCurrency) Symbol() string

Symbol returns the symbol of the currency.

type Pair

type Pair struct {
	LiquidityToken *Token
	// sorted tokens
	TokenAmounts
}

Pair warps uniswap pair.

func NewPair

func NewPair(address common.Address, tokenAmountA, tokenAmountB *TokenAmount) (*Pair, error)

NewPair creates Pair address must be looked up on-chain.

func (*Pair) GetInputAmount

func (p *Pair) GetInputAmount(outputAmount *TokenAmount, dexFee *big.Int) (*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, dexFee *big.Int) (*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.

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.

type Percent

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

Percent warps Fraction.

func NewPercent

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

NewPercent creates Percent.

func (*Percent) Decimal

func (p *Percent) Decimal() decimal.Decimal

func (Percent) Quotient

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

quotient performs floor division.

func (*Percent) Raw

func (p *Percent) Raw() *fraction

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 {
	// contains filtered or unexported fields
}

func NewPrice

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

NewPrice constructs a Price from two currencies and two raw values 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) Decimal

func (p *Price) Decimal() decimal.Decimal

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) Quotient

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

quotient performs floor division.

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) GetAddresses

func (r *Route) GetAddresses() []common.Address

GetAddresses returns the addresses of the tokens involved in the route.

type Token

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

func NewToken

func NewToken(address common.Address, name, symbol string, decimals uint8) (*Token, error)

NewToken is the constructor for a token.

func (*Token) Address

func (c *Token) Address() string

Address is the contract address of the currency.

func (*Token) CommonAddress

func (c *Token) CommonAddress() common.Address

CommonAddress returns the common address of the token and the other token.

func (*Token) Decimals

func (c *Token) Decimals() uint8

Decimals returns the number of decimals for the currency.

func (*Token) Name

func (c *Token) Name() string

Name returns the name of the token.

func (*Token) SortsBefore

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

SortsBefore returns true if the address of this token sorts before the address of the other token other is token to compare throws ErrSameAddrss if the tokens have the same address.

func (*Token) Symbol

func (c *Token) Symbol() string

Symbol returns the symbol of the token.

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) Decimal

func (f TokenAmount) Decimal() decimal.Decimal

func (TokenAmount) Quotient

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

quotient performs floor division.

func (TokenAmount) ToFixed

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

ToFixed format output.

func (TokenAmount) ToSignificant

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

ToSignificant format output.

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 {
	// Route is the route of the trade, i.e. which pairs the trade goes through.
	Route *Route
	// TradeType is the type of the trade, either exact in or exact out.
	TradeType TradeType

	// ExecutionPrice is the price expressed in terms of output amount/input amount.
	ExecutionPrice *Price
	// NextMidPrice is the mid price after the trade executes assuming no slippage.
	NextMidPrice *Price
	// PriceImpact is 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)

BestTradeExactIn is 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. pairs are the pairs to consider in finding the best trade currencyAmountIn is the exact amount of input currency to spend currencyOut is the desired currency out maxNumResults is maximum number of results to return maxHops is the maximum number of hops a returned trade can make, e.g. 1 hop goes through a single pair currentPairs is used in recursion; the current list of pairs originalAmountIn is used in recursion; the original value of the currencyAmountIn parameter bestTrades is 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)

BestTradeExactOut is 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. pairs are the pairs to consider in finding the best trade currencyIn is the currency to spend currencyAmountOut is the exact amount of currency out maxNumResults is the maximum number of results to return maxHops is the maximum number of hops a returned trade can make, e.g. 1 hop goes through a single pair currentPairs is used in recursion; the current list of pairs originalAmountOut is used in recursion; the original value of the currencyAmountOut parameter bestTrades is used in recursion; the current list of best trades.

func ExactIn

func ExactIn(route *Route, amountIn *TokenAmount, dexFee *big.Int) (*Trade, error)

ExactIn constructs an exact in trade with the given amount in and route route is route of the exact in trade amountIn is the amount being passed in.

func ExactOut

func ExactOut(route *Route, amountOut *TokenAmount, dexFee *big.Int) (*Trade, error)

ExactOut constructs an exact out trade with the given amount out and route route is the route of the exact out trade amountOut is the amount returned by the trade.

func NewTrade

func NewTrade(route *Route, amount *TokenAmount, tradeType TradeType, dexFee *big.Int) (*Trade, error)

NewTrade creates a new trade.

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)

MinimumAmountOut gets the minimum amount that must be received from this trade for the given slippage tolerance slippageTolerance tolerance of unfavorable slippage from the execution price of this trade.

func (*Trade) OutputAmount

func (t *Trade) OutputAmount() *TokenAmount

type TradeType

type TradeType int
const (
	ExactInput TradeType = iota
	ExactOutput
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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