🛠 A Go SDK for building applications on top of Uniswap V3

Uniswap V3 SDK

API Reference Test Go Report Card

🛠 A Go SDK for building applications on top of Uniswap V3

Installation

go get github.com/daoleno/uniswapv3-sdk

Usage

The following example shows how to create a pool, and get the inputAmount

DAI outputAmount := core.FromRawAmount(DAI.Currency, big.NewInt(98)) inputAmount, _, err := pool.GetInputAmount(outputAmount, nil) if err != nil { panic(err) } fmt.Println(inputAmount.ToSignificant(4)) } ">
package main

import (
	"fmt"
	"math/big"

	core "github.com/daoleno/uniswap-sdk-core/entities"
	"github.com/daoleno/uniswapv3-sdk/constants"
	"github.com/daoleno/uniswapv3-sdk/entities"
	"github.com/daoleno/uniswapv3-sdk/utils"
	"github.com/ethereum/go-ethereum/common"
)

var (
	USDC     = core.NewToken(1, common.HexToAddress("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"), 6, "USDC", "USD Coin")
	DAI      = core.NewToken(1, common.HexToAddress("0x6B175474E89094C44Da98b954EedeAC495271d0F"), 18, "DAI", "Dai Stablecoin")
	OneEther = big.NewInt(1e18)
)

func main() {
	// create demo ticks
	ticks := []entities.Tick{
		{
			Index:          entities.NearestUsableTick(utils.MinTick, constants.TickSpaces[constants.FeeLow]),
			LiquidityNet:   OneEther,
			LiquidityGross: OneEther,
		},
		{
			Index:          entities.NearestUsableTick(utils.MaxTick, constants.TickSpaces[constants.FeeLow]),
			LiquidityNet:   new(big.Int).Mul(OneEther, constants.NegativeOne),
			LiquidityGross: OneEther,
		},
	}

	// create tick data provider
	p, err := entities.NewTickListDataProvider(ticks, constants.TickSpaces[constants.FeeLow])
	if err != nil {
		panic(err)
	}

	// new pool
	pool, err := entities.NewPool(USDC, DAI, constants.FeeLow, utils.EncodeSqrtRatioX96(constants.One, constants.One), OneEther, 0, p)
	if err != nil {
		panic(err)
	}

	// USDC -> DAI
	outputAmount := core.FromRawAmount(DAI.Currency, big.NewInt(98))
	inputAmount, _, err := pool.GetInputAmount(outputAmount, nil)
	if err != nil {
		panic(err)
	}
	fmt.Println(inputAmount.ToSignificant(4))
}

More Examples

Owner
daoleno
software engineer
daoleno
Comments
  • SwapCallParameters function problem

    SwapCallParameters function problem

    Hi, I have a problem for swapping tokens this is my code

    import (
    	"math/big"
    	"time"
    
    	"log"
    
    	coreEntities "github.com/daoleno/uniswap-sdk-core/entities"
    	"github.com/daoleno/uniswapv3-sdk/constants"
    	"github.com/daoleno/uniswapv3-sdk/entities"
    	"github.com/daoleno/uniswapv3-sdk/examples/helper"
    	"github.com/daoleno/uniswapv3-sdk/periphery"
    	"github.com/ethereum/go-ethereum/common"
    	"github.com/ethereum/go-ethereum/ethclient"
    )
    
    var ETHRPC = "https://kovan.infura.io/v3/{{id}}"
    
    func main() {
    	client, err := ethclient.Dial(ETHRPC)
    	if err != nil {
    		log.Fatal(err)
    	}
    	wallet := helper.InitWallet({prv_key})
    	if wallet == nil {
    		log.Fatal("init wallet failed")
    	}
    
    	usdt := coreEntities.NewToken(42, common.HexToAddress("0x07de306ff27a2b630b1141956844eb1552b956b5"), 6, "USDT", "Tether USD")
    	weth := coreEntities.NewToken(42, common.HexToAddress("0xd0a1e359811322d97991e03f863a0c30c2cf029c"), 18, "WETH", "Wrapped Ether")
    
    	pool, err := helper.ConstructV3Pool(client, usdt, weth, uint64(constants.FeeMedium))
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	//0.01%
    	slippageTolerance := coreEntities.NewPercent(big.NewInt(1), big.NewInt(1000))
    	//after 5 minutes
    	d := time.Now().Add(time.Minute * time.Duration(15)).Unix()
    	deadline := big.NewInt(d)
    
    	// single trade input
    	// single-hop exact input
    	r, err := entities.NewRoute([]*entities.Pool{pool}, usdt, weth)
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	swapValue := helper.FloatStringToBigInt("2", 6)
    	trade, err := entities.FromRoute(r, coreEntities.FromRawAmount(usdt, swapValue), coreEntities.ExactInput)
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	log.Printf("%v %v\n", trade.Swaps[0].InputAmount.Quotient(), trade.Swaps[0].OutputAmount.Wrapped().Quotient())
    	params, err := periphery.SwapCallParameters([]*entities.Trade{trade}, &periphery.SwapOptions{
    		SlippageTolerance: slippageTolerance,
    		Recipient:         wallet.PublicKey,
    		Deadline:          deadline,
    	})
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	to := common.HexToAddress("0x68b3465833fb72a70ecdf485e0e4c7bd8665fc45")
    
    	tx, err := helper.TryTX(client, to,
    		big.NewInt(0), params.Calldata, wallet)
    	if err != nil {
    		log.Fatal(err)
    	}
    	log.Println(tx.Hash().String())
    
    }
    

    and it returns me The execution failed due to an exception. this error. so I searched about this error and understood that one of the main reasons is corrupted input data so instead of using SwapCallParameters I swapped with uniswap web application and extracted its input data https://kovan.etherscan.io/tx/0xd9ba16700e54348c0e9648e4eeec7160ec523a92bff8baca237687ea86a5300c and used it in code and it generate this transaction successfully https://kovan.etherscan.io/tx/0x360d93ba9ba7f39acf5ae7931528e4ecb8666fc6fe1b4213e513abea826571af so I think maybe there is a problem with this function but I can't debug it i appreciate any help

  • Output amount is not calculated correctly in some cases

    Output amount is not calculated correctly in some cases

    Hi guys, first of all, thank you for the great library and the effort to maintain it!

    Issue:

    in some cases pool.GetOutputAmount() (and Pool.swap() ) is not calculating output amount correctly with ExactInput option

    Suspected case:

    when current tick of the pool is negative

    How to reproduce:

    try to form a swap tx for UNI/WETH/30 pool with exact input WETH amount (0.1 in my case). Current tick for the pool is something close to -55200. Check the value returned from pool.GetOutputAmount() (called from FromRoute(...,coreEntities.ExactInput) ) .

  • Implement atomic swaps

    Implement atomic swaps

  • Token has no field or method Currency

    Token has no field or method Currency

    github.com/daoleno/uniswapv3-sdk v0.3.0

    DAI.Currency undefined (type *"github.com/daoleno/uniswap-sdk-core/entities".Token has no field or method Currency)

  • abi can not pack (Standard)PermitArguments

    abi can not pack (Standard)PermitArguments

    abi: cannot use uint as type uint8 as argument when calling abi.Pack("selfPermit", token.Address, options.Amount, options.Deadline, options.V, options.R, options.S) in selfpermit.go

  • "invalid tick index" incorrect check

    https://github.com/daoleno/uniswapv3-sdk/blob/master/entities/ticklist.go#L60-L62

    func GetTick(ticks []Tick, index int) Tick {
    	tick := ticks[binarySearch(ticks, index)]
    	if tick.Index <= 0 {
    		panic("invalid tick index")
    	}
    	return tick
    }
    

    Hi @daoleno ,

    I think this function should be something like

    func GetTick(ticks []Tick, index int) Tick {
            tickIndex := binarySearch(ticks, index)
            if tickIndex < 0 {
    		panic("invalid tick index")
    	}
    	tick := ticks[tickIndex]
    
    	return tick
    }
    

    Because tick.Index can be negative. Am I right?

  • How does swap provide a pool with the correct output state?

    How does swap provide a pool with the correct output state?

    https://github.com/daoleno/uniswapv3-sdk/blob/8bd83362dcd1635e5426106bef5d9b754c51f13b/entities/pool.go#L166

    I don't understand how this is returning the correct new pool state because it just changes the tick and the price, but it doesn't actually update the tick liquidity from the tick data provider.

    Am I missing something here? If the tick liquidity isn't added or subtracted, then the liquidityNet for the consumed ticks isn't correct for pricing the next swap.

  • ConstructV3Pool failing for a live pool

    ConstructV3Pool failing for a live pool

    Hey, I was trying to use your package to interact with a pool on maiinet but I get an error when using ConstructV3Pool

            unipool = "0x82c427AdFDf2d245Ec51D8046b41c4ee87F0d29C"
            weth    = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
            osqth   = "0xf1B99e3E573A1a9C5E6B2Ce818b617F0E664E86B"
            chainID, _ := client.ChainID(context.Background())
    	c := uint(chainID.Uint64())
    	token0 := coreEntities.NewToken(c, common.HexToAddress(weth), 18, "WETH", "weth")
    	token1 := coreEntities.NewToken(c, common.HexToAddress(osqth), 18, "oSQTH", "opyn squeeth")
    	//amountIn := helper.FloatStringToBigInt("1.00", 18)
    	pool, err := ConstructV3Pool(client, token0, token1, uint64(constants.FeeMedium))
    	if err != nil {
    		log.Fatal(err)
    	}
    

    I get the following error tick net delta must be zero , which as I understand is something about validating the ticks in ValidateList. But I don't know enough of the details of uniswap to understand how to fix this or why this pool fails.

    Do you have an idea? etherscan link of the pool: https://etherscan.io/address/0x82c427adfdf2d245ec51d8046b41c4ee87f0d29c#readContract

  • How to use auto permit(allowance) when operating the position?

    How to use auto permit(allowance) when operating the position?

    Hi, guys. Thanks for sharing this SDK.

    I have a question about auto perimting allowance when calling mutilcall. I saw two parameters (Token0Permit, Token1Permit) in CommonAddLiquidityOptions:

    //  Options for producing the calldata to add liquidity
    type CommonAddLiquidityOptions struct {
    	SlippageTolerance *core.Percent  // How much the pool price is allowed to move
    	Deadline          *big.Int       // When the transaction expires, in epoch seconds
    	UseNative         *core.Ether    // Whether to spend ether. If true, one of the pool tokens must be WETH, by default false
    	Token0Permit      *PermitOptions // The optional permit parameters for spending token0
    	Token1Permit      *PermitOptions // The optional permit parameters for spending token1
    }
    

    These two permit parameters defined in https://github.com/daoleno/uniswapv3-sdk/blob/master/periphery/selfpermit.go

    I know it would be wrapped in AddCallParameters automatically. But I don't know how to wrap the VRS(signature data). Can you give me a simple example for calling AddCallParameters with perimited parameters?

A go sdk for baidu netdisk open platform 百度网盘开放平台 Go SDK

Pan Go Sdk 该代码库为百度网盘开放平台Go语言的SDK

Nov 22, 2022
Nextengine-sdk-go: the NextEngine SDK for the Go programming language

NextEngine SDK for Go nextengine-sdk-go is the NextEngine SDK for the Go programming language. Getting Started Install go get github.com/takaaki-s/nex

Dec 7, 2021
Commercetools-go-sdk is fork of original commercetools-go-sdk

commercetools-go-sdk The Commercetools Go SDK is automatically generated based on the official API specifications of Commercetools. It should therefor

Dec 13, 2021
Sdk-go - Go version of the Synapse SDK

synapsesdk-go Synapse Protocol's Go SDK. Currently in super duper alpha, do not

Jan 7, 2022
Redash-go-sdk - An SDK for the programmatic management of Redash, in Go
Redash-go-sdk - An SDK for the programmatic management of Redash, in Go

Redash Go SDK An SDK for the programmatic management of Redash. The main compone

Dec 13, 2022
Building block for mobile money api clients

base the base code for creating mobile money api clients using golang build request request := NewRequestBuilder("login request", http.MethodPost, "ht

Jan 4, 2022
AWS SDK for the Go programming language.

AWS SDK for Go aws-sdk-go is the official AWS SDK for the Go programming language. Checkout our release notes for information about the latest bug fix

Dec 31, 2022
A Facebook Graph API SDK For Go.

A Facebook Graph API SDK In Golang This is a Go package that fully supports the Facebook Graph API with file upload, batch request and marketing API.

Dec 12, 2022
A Golang SDK for Medium's OAuth2 API

Medium SDK for Go This repository contains the open source SDK for integrating Medium's OAuth2 API into your Go app. Install go get github.com/Medium/

Nov 28, 2022
MinIO Client SDK for Go

MinIO Go Client SDK for Amazon S3 Compatible Cloud Storage The MinIO Go Client SDK provides simple APIs to access any Amazon S3 compatible object stor

Dec 29, 2022
Simple no frills AWS S3 Golang Library using REST with V4 Signing (without AWS Go SDK)

simples3 : Simple no frills AWS S3 Library using REST with V4 Signing Overview SimpleS3 is a golang library for uploading and deleting objects on S3 b

Nov 4, 2022
Twilight is an unofficial Golang SDK for Twilio APIs
Twilight is an unofficial Golang SDK for Twilio APIs

Twilight is an unofficial Golang SDK for Twilio APIs. Twilight was born as a result of my inability to spell Twilio correctly. I searched for a Twillio Golang client library and couldn’t find any, I decided to build one. Halfway through building this, I realized I had spelled Twilio as Twillio when searching for a client library on Github.

Jul 2, 2021
Wechat Pay SDK(V3) Write by Go.

WechatPay GO(v3) Introduction Wechat Pay SDK(V3) Write by Go. API V3 of Office document is here. Features Signature/Verify messages Encrypt/Decrypt ce

May 23, 2022
Go Wechaty is a Conversational SDK for Chatbot Makers Written in Go
Go Wechaty is a Conversational SDK for Chatbot Makers Written in Go

go-wechaty Connecting Chatbots Wechaty is a RPA SDK for Wechat Individual Account that can help you create a chatbot in 6 lines of Go. Voice of the De

Dec 30, 2022
An easy-to-use unofficial SDK for Feishu and Lark Open Platform

go-lark go-lark is an easy-to-use unofficial SDK for Feishu and Lark Open Platform. go-lark implements messaging APIs, with full-fledged supports on b

Jan 2, 2023
A go SDK for the data available via data.gov.gr

go-data-gov-gr-sdk A Go based SDK to access the public data provided by the Greek Government and are available at https://www.data.gov.gr/ Quick Start

Jan 24, 2022
weixin/wechat/微信公众平台/微信企业号/微信商户平台/微信支付 go/golang sdk
weixin/wechat/微信公众平台/微信企业号/微信商户平台/微信支付 go/golang sdk

wechat SDK for golang https://github.com/chanxuehong/wechat 招人啦 golang 后端的坑, 趣头条集团下面的创新团队, 现在步入正常轨道了, 前景很好. 要求: golang中高级 自驱、有责任心 沟通没有问题 待遇: open, 看能力

Dec 30, 2022
SDK for Yigim Payment Gateway

Yigim gateway SDK The package provides ability to access the Yigim payment's api via the Go language. Usage To install run: go get github.com/paladium

Oct 5, 2021
DipDup Golang SDK

General instruments for DipDup in golang

Dec 14, 2022