Giter Club home page Giter Club logo

v3-sdk's Introduction

@uniswap/v3-sdk - Now at Uniswap/sdks

All versions after 3.11.0 of this SDK can be found in the SDK monorepo! Please file all future issues, PR’s, and discussions there.

Old Issues and PR’s

If you have an issue or open PR that is still active on this SDK in this repository, please recreate it in the new repository. Some existing issues and PR’s may be automatically migrated by the Uniswap Labs team.

v3-sdk's People

Contributors

cmcewen avatar daoleno avatar dependabot[bot] avatar felipebrahm avatar feltespt avatar ianlapham avatar jesse-sawa avatar jfrankfurt avatar jsy1218 avatar just-toby avatar lint-action avatar marktoda avatar moodysalem avatar noahzinsmeister avatar snreynolds avatar willpote avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

v3-sdk's Issues

How do i send a tx to a wallet?

Hi, I want to write a swap api for my native mobile dapp using this sdk. But I have a question, how do i send the transaction to user's wallet? I mean my user's wallet is connected to my app via walletconnect, i got their public wallet address but i cant find the 'send this tx to' part. (Sorry I ask this question here because I can't join uniswap discord channel (it says cant accept invite))

How to get an amount of both tokens of my position? Uni V3

Hi!

Is there a way to get amount of both tokens of my position in a pool (Uni v3 )? I found method "positions" of NonfungiblePositionManager but it returns something weird and the result doesn't look like my position:

const positionManager = require('@uniswap/v3-periphery/artifacts/contracts/NonfungiblePositionManager.sol/NonfungiblePositionManager.json');
var contractAddress = "0xc36442b4a4522e871399cd717abdd847ab11fe88";
var contract = new web3.eth.Contract(positionManager.abi, contractAddress);
var tokenId = 77777; //my tokenId
contract.methods.positions(tokenId).call().then(function(result){
  console.log(result);
});

Result:
image

is `encodeRouteToPath` second param really `exactOutput` ?

Hello,

Lets start by the contract I'm writing. It is supposed to swap arbitrary user token to the one my system uses, before actually doing stuff.

function deposit(address receiver, uint256 amountIn, uint256 amountOutMinimum, bytes memory path) external payable {
    uint256 balanceBefore = USDC.balanceOf(receiver);

    if (value > 0) { 
        ...
    } else if (path.length == 0) {
        ...
    } else {
        // get first asset in path
        IERC20 assetIn = IERC20(path.toAddress(23));

        // take custody
        SafeERC20.safeTransferFrom(assetIn, msg.sender, address(this), amountIn);
        SafeERC20.safeApprove(assetIn, address(uniswapRouter), type(uint256).max);

        // start routing
        uniswapRouter.exactInput(ISwapRouter.ExactInputParams({
            path:              path,
            recipient:         owner,
            deadline:          block.timestamp,
            amountIn:          amountIn,
            amountOutMinimum:  amountOutMinimum
        }));
    }

    uint256 received = USDC.balanceOf(receiver) - balanceBefore;

    // DO STUFF
}

My issue is in building the path

So far I've been doing

const router = new AlphaRouter({ chainId: 1, provider });
const trade = await router.route(
    CurrencyAmount.fromRawAmount(TOKENS.USDT, amount),
    TOKENS.USDC,
    TradeType.EXACT_IN,
).then(({ trade }) => encodeRouteToPath(trade.routes[0]));

the resulting trade is USDC.address | fee | USDT.address ... hence the path.toAddress(23) in the contract.
→ but that fails with STF.

So what I did is changing encodeRouteToPath(trade.routes[0]) to encodeRouteToPath(trade.routes[0], true) and path.toAddress(23) to path.toAddress(0)
→ this works!

So I'm confused, because the true params is supposed to be for exactOutput ... and I'm using exactInput. I'm afraid this might break with longer paths ...

Am I doing things wrong, or is the docs mistaken?

share token

i hope uniswap can share all the members 1000 UNI token

JSBI misbehaving with v3 sdk utils

Trying to use the sdk swapMath utils (computeSwapStep) and keep running into this error:

TypeError: _.__digit is not a function
    at Function.__leftShiftByAbsolute (/home/rachita/Projects/crypto/swap_arbitrage/node_modules/jsbi/lib/jsbi.ts:1661:21)
    at Function.leftShift (/home/rachita/Projects/crypto/swap_arbitrage/node_modules/jsbi/lib/jsbi.ts:293:17)
    at Function.getAmount0Delta (/home/rachita/Projects/crypto/swap_arbitrage/node_modules/@uniswap/v3-sdk/src/utils/sqrtPriceMath.ts:30:29)
    at Function.computeSwapStep (/home/rachita/Projects/crypto/swap_arbitrage/node_modules/@uniswap/v3-sdk/src/utils/swapMath.ts:38:25)

Running using npx ts-node if relevant

NonfungiblePositionManager.removeCallParameters() assumes the position liquidity is a fraction

Partial stack trace:

/home/e/r/node_modules/@uniswap/sdk-core/src/entities/fractions/fraction.ts:38
    throw new Error('Could not parse fraction')
          ^
Error: Could not parse fraction
    at Function.tryParseFraction (/home/e/r/node_modules/@uniswap/sdk-core/src/entities/fractions/fraction.ts:38:11)
    at Percent.multiply (/home/e/r/node_modules/@uniswap/sdk-core/src/entities/fractions/fraction.ts:108:34)
    at Percent.multiply (/home/e/r/node_modules/@uniswap/sdk-core/src/entities/fractions/percent.ts:30:21)
    at Function.removeCallParameters (/home/e/r/node_modules/@uniswap/v3-sdk/src/nonfungiblePositionManager.ts:364:46)

Steps to repro:

  • Create a v3 position programmatically.
  • Find the position's token ID
  • Get a Position instance for it using const position: Position = await positionManagerContract.positions(tokenId)
  • Assume you want to remove all liquidity, so RemoveLiquidityOptions.liquidityPercentage is new Percent(1)
  • Call removeCallParameters
  • On this line: https://github.com/Uniswap/v3-sdk/blob/main/src/nonfungiblePositionManager.ts#L350, the options liquidity percentage is multiplied by the existing position liquidity, which requires that the existing position liquidity is a Fraction. Its not - it's a BigNumber

Also note that the docs don't explain how to get hold of an existing v3 position for passing to removeCallParameters()

Difference outputAmount returned by Pool.getOutputAmount() in uniV3-SDK and SwapRouter.exactInputSingle() in uniV3-periphery for only one pool

Hello everyone,
I tried to use Pool.getOutputAmount() in uniV3-SDK and SwapRouter.exactInputSingle() in uniV3-periphery to perform a swap within a given pool then compare the two results. I use hardhat for forking the mainnet and execute the script for Pool.getOutputAmount() at first (because it doesn't change the state of EVM) then the script for SwapRouter.exactInputSingle() at the seconds. I take 6 pools for the test:

  1. ZDEX - WETH: '0x46087cEeD975CFfC0074C5d4A7e8f1150E7CECf6'
  2. USDC - WETH: '0x8ad599c3A0ff1De082011EFDDc58f1908eb6e6D8'
  3. YAY - WETH: '0xC3e4E5c19984BE13bB52F5D14FfBf6a13ea0838B'
  4. DFM - WETH: '0x919F58bc429c7cF96905EB79395F5B77D9b98b52'
  5. WETH - MRXe: '0x7eC0bE8aa9fBc1d8aB40Aa5b1fd0E46d66120eDf'
  6. WETH - R64X: '0xAb44Da6A8180D0f75d214d3616970E0C93BBFBAa'

In each test, I swap 1 WETH for another token in each pool. I have only one pair of outputAmount which has difference result for the pool DFM - WETH: '0x919F58bc429c7cF96905EB79395F5B77D9b98b52' . The results of the others pools are good.
Here is my SDK scripts :

swap-sdk-01
swap-sdk-02

And here is my periphery script:

swap-periphery-01
swap-periphery-02

For example of the result:

  • Pool 2 (USDC - WETH): Input 1 WETH
    +) SDK output: 3243438919
    +) Periphery output: 3243438919
  • Pool 4 (DFM - WETH): input 1 WETH (the problem is here)
    +) SDK output: 28785598159162986664347
    +) Periphery output: 28785598159162986644716

I don't know why. Can you explain to me please? Thank you!

How to use SDK for getAmountOut?

image
And than i use poolExample.getOutputAmount(inputAmount) but its always 1ETH trade 1000000USDT...
so how init ticks?Please help

Q32X128 to decimals

From my understanding the fees of a position are expressed in Q32X128. How to convert that value into human readable decimal value. It might be obvious for math expert but not for all of us. If you can provide an example on the calculation to do (with JSBI).?

"feeGrowthInside0LastX128": "946473287707704477165742195067358332049286",
"feeGrowthInside1LastX128": "24104081653194999825509743111198"

TickDataProvider not defined in docs for creating new pool

I am trying to create a new pool so that I can use the getOutputAmount method to estimate probability of swaps. It appears nowhere in the docs is an example of a TickDataProvider provided. And everywhere a new pool is create in the uniswap-interface code a black array is used for this input. Are there any examples of where or how to get this tick data?

missing export SwapMath

I'm trying to use the function computeSwapStep inside the SwapMath class to compute the result of a swap, but I can't import it.
I saw that it's missing in utils/index.d.ts

Got an Unhandled Rejection (Error): Convert JSBI instances to native numbers using `toNumber`.

I recently updated my npm packages, with the v3-sdk going from ^3.5.1-optimism-regensis to ^3.7.1. Because of this JSBI started to act weird.
At first I was getting an error saying Argument of type 'JSBI' is not assignable to parameter of type 'BigintIsh', even though BigintIsh should contain JSBI, I changed those to strings and that seemed to have solved the problem at first.
But then later when I'm trying to get the midPrice for a v3 swap route, I'm getting an error saying "Convert JSBI instances to native numbers using toNumber". This never happened before with my past package.
It might have something to do with the JSBI package. I tried updating to what the uniswap interface is using and back, but nothing is working. I created the route object using one token that is the native network's token and the other is any token, and I'm passing only one pool into the route.

What is the right price amongst 3 Liquidity Pools of the same Token Pair on V3?

I would post this issue on uniswap/uniswap-v3-core by posting issues there is forbidden:

image

(why is that?)

anyway, setting this aside... querying the subgraph I discovered that there can be multiple Liquidity Pools for a given token pair, as having a different fee tier, one can create a new LP for an already existing pair.

The question is, how do we determine price given multiple LPs for the same token pair? How does frontend tackle this?

Example using DAI/USDC Pair

The Query

{ 
  token(id:"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48") {
    id
    symbol
    whitelistPools(where:{token0:"0x6b175474e89094c44da98b954eedeac495271d0f"}) {
      id
			feeTier
      liquidity
      token0Price
      token1Price
      token0 {
        symbol
      }
   }
  }
}

The Response

{
  "data": {
    "token": {
      "id": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
      "symbol": "USDC",
      "whitelistPools": [
        {
          "feeTier": "10000",
          "id": "0x6958686b6348c3d6d5f2dca3106a5c09c156873a",
          "liquidity": "24405430160684491",
          "token0": {
            "symbol": "DAI"
          },
          "token0Price": "1.000097347797523468560923036695158",
          "token1Price": "0.9999026616781477783833621614227994"
        },
        {
          "feeTier": "500",
          "id": "0x6c6bc977e13df9b0de53b251522280bb72383700",
          "liquidity": "166739955719276340984048",
          "token0": {
            "symbol": "DAI"
          },
          "token0Price": "0.999375896994654300981013045872989",
          "token1Price": "1.000624492753149756391698159238136"
        },
        {
          "feeTier": "3000",
          "id": "0xa63b490aa077f541c9d64bfc1cc0db2a752157b5",
          "liquidity": "1983087073471302739",
          "token0": {
            "symbol": "DAI"
          },
          "token0Price": "0.9998697244241236777590508333027245",
          "token1Price": "1.000130292549813281560606342941779"
        }
      ]
    }
  }
}

TickMath.getSqrtRatioAtTick not reporting same value as slot0 onchain

When using the SDK I get slightly different values for sqrtPriceX96 when using the SDK helper function than the reported onchain slot0 for the pool (on mainnet and rinkeby).

Pool address on mainnet 0xcB0C5d9D92f4F2F80cce7aa271a1E148c226e19D (as an example)
For tick 11026, slot0 reports 137503933239637586571196885609.
Using the sdk for tick 11026 I get 137497297140448246835764898549.

However Wolfram Alpha says that the sdk math is actually the correct value so how come slot0 is reporting something different? Should I expect this to be the same value? The discrepancy is large enough to be affecting slippage calculations on low slippage levels so I'm unsure how to handle this.

How to I get price?

How do I get the price of Token in a pool in V3 in JavaScript with web3?
Do I need to have the address of the UniswapV3Pool and what is address of the UniswapV3Pool?

V2 Methods on V3 SDK

Hello Uniswap Team!

I would like to request the following methods on the new SDK to mirror V2 methods:

  • Router
    --swapExactTokensForETH
    -- swapExactETHForTokens
    -- approve

  • Factory
    --PairCreated

v3 router and some other questions

Hi, I got some questions about how v3 does some "things". Can you take a look and answer them for me?
1- When we add (we will sate fee ratio like (0.05, 0.3, 1.0)) to any liquidity pool in uniswap-v3, how do we get our earnings according to the share distribution of the nft token in the pool? Can we get UNI tokens just like v2?
2- We use router02 right now, but should we use router02 to connect v3?
3- Will there be a router03 for for liquidity and swap transactions?

A bug in tickList.ts(line 122) which will cause different rounds in swap and sqrtPriceX96 error

Recently I'm trying to build a simulator with my team based on Uniswap V3 CorePool maths model as well as contract implementation. My teammate found the repo and your help is greatly appreciated.

I know the tickList.ts do the same thing as TickBitmap.sol do. It's wonderful work. However, I believe there is a small accident in

const maximum = ((wordPos + 1) << 8) * tickSpacing - 1

and that will be correct if we adjust the subtraction to the proper position.

const maximum = (((wordPos + 1) << 8) - 1) * tickSpacing;

As fas as the test result I know, this error can result in less swap rounds under certain condition. Thus sqrtPriceX96 will be different and swap result like amount will be different from actual mainnet data bit by bit.

Please check if it is right. Thank you.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.