Uniswap / v3-sdk

🛠 An SDK for building applications on top of Uniswap V3
MIT License
547 stars 425 forks source link

Swap and add atomically is not working when both token balances are non-zero #117

Closed Eyon42 closed 2 years ago

Eyon42 commented 2 years ago

Tx: https://polygonscan.com/tx/0x946104cc9f0370ada9a10bc500a8504b9d7280d5877bb87a79e1b163109fbc79 Network: Polygon Versions:

{
  "devDependencies": {
    "@uniswap/sdk-core": "^3.0.1",
    "@uniswap/smart-order-router": "^2.5.26",
    "@uniswap/v3-sdk": "^3.8.2"
  },
  "dependencies": {
    "dotenv": "^16.0.0",
    "ethers": "^5.6.4",
    "ts-node": "^10.7.0",
    "typescript": "^4.6.4"
  }
}

Code:

    const router = new AlphaRouter({ chainId: appData.chainId, provider: provider })
    const pool = await getPool(appData, provider)

    const TokenA = new Token(appData.chainId, pool.token0.address, appData.decimals[0])
    const TokenB = new Token(appData.chainId, pool.token1.address, appData.decimals[1])

    const token0Balance = CurrencyAmount.fromRawAmount(TokenA, "5000000000")
    const token1Balance = CurrencyAmount.fromRawAmount(TokenB, "10000000000"])

    const marginInTicks = Math.round((50 * marginPercent) / pool.tickSpacing)

    const routeToRatioResponse = await router.routeToRatio(
        token0Balance,
        token1Balance,
        new Position({
          pool,
          tickLower: nearestUsableTick(pool.tickCurrent, pool.tickSpacing) - pool.tickSpacing * marginInTicks,
          tickUpper: nearestUsableTick(pool.tickCurrent, pool.tickSpacing) + pool.tickSpacing * marginInTicks,
          liquidity: 1,
         }),
        { // SwapAndAddConfig
           ratioErrorTolerance: new Fraction(1, 100),
           maxIterations: 6,
         },
        { // routingConfig
           swapOptions: {
             recipient: signer.address,
             slippageTolerance: new Percent(5, 100),
             deadline: Math.floor(Date.now()/1000 +1800)
           },
           addLiquidityOptions: {
             recipient: signer.address
           }
         }
      );

    if (routeToRatioResponse.status == SwapToRatioStatus.SUCCESS) {
        const route = routeToRatioResponse.result
        console.log("Route successfull. Swapping...")
        console.log(route)
        const transaction = {
            data: route.methodParameters.calldata,
            to: V3_SWAP_ROUTER_ADDRESS,
            value: BigNumber.from(route.methodParameters.value),
            from: signer.address,
            gasPrice: await provider.getGasPrice(),
            gasLimit: 1000000
        };
        const tx = await signer.sendTransaction(transaction);
        console.log("Waiting for tx")
        console.log(await tx.wait())
        console.log("Tx confirmed")
    }
    else {
        console.log("Route failed")
    }

Output:


Route successfull. Swapping...
{
  quote: CurrencyAmount {
    numerator: JSBI(3) [ 496369429, 630108033, 31, sign: false ],
    denominator: JSBI(1) [ 1, sign: false ],
    currency: Token {
      chainId: 137,
      decimals: 18,
      symbol: undefined,
      name: undefined,
      isNative: false,
      isToken: true,
      address: '0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270'
    },
    decimalScale: JSBI(2) [ 660865024, 931322574, sign: false ]
  },
  quoteGasAdjusted: CurrencyAmount {
    numerator: JSBI(3) [ 893998725, 626950154, 31, sign: false ],
    denominator: JSBI(1) [ 1, sign: false ],
    currency: Token {
      chainId: 137,
      decimals: 18,
      symbol: undefined,
      name: undefined,
      isNative: false,
      isToken: true,
      address: '0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270'
    },
    decimalScale: JSBI(2) [ 660865024, 931322574, sign: false ]
  },
  estimatedGasUsed: BigNumber { _hex: '0x01b968', _isBigNumber: true },
  estimatedGasUsedQuoteToken: CurrencyAmount {
    numerator: JSBI(2) [ 676112528, 3157878, sign: false ],
    denominator: JSBI(1) [ 1, sign: false ],
    currency: Token {
      chainId: 137,
      decimals: 18,
      symbol: 'WMATIC',
      name: 'Wrapped MATIC',
      isNative: false,
      isToken: true,
      address: '0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270'
    },
    decimalScale: JSBI(2) [ 660865024, 931322574, sign: false ]
  },
  estimatedGasUsedUSD: CurrencyAmount {
    numerator: JSBI(1) [ 3931, sign: false ],
    denominator: JSBI(1) [ 1, sign: false ],
    currency: Token {
      chainId: 137,
      decimals: 6,
      symbol: 'USDC',
      name: 'USD//C',
      isNative: false,
      isToken: true,
      address: '0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174'
    },
    decimalScale: JSBI(1) [ 1000000, sign: false ]
  },
  gasPriceWei: BigNumber { _hex: '0x06fc88749a', _isBigNumber: true },
  route: [
    V3RouteWithValidQuote {
      protocol: 'V3',
      amount: [CurrencyAmount],
      rawQuote: [BigNumber],
      sqrtPriceX96AfterList: [Array],
      initializedTicksCrossedList: [Array],
      quoterGasEstimate: [BigNumber],
      quote: [CurrencyAmount],
      percent: 100,
      route: [V3Route],
      gasModel: [Object],
      quoteToken: [Token],
      tradeType: 0,
      gasCostInToken: [CurrencyAmount],
      gasCostInUSD: [CurrencyAmount],
      gasEstimate: [BigNumber],
      quoteAdjustedForGas: [CurrencyAmount],
      poolAddresses: [Array],
      tokenPath: [Array]
    }
  ],
  trade: Trade {
    swaps: [ [Object] ],
    routes: [ [RouteV3] ],
    tradeType: 0,
    _inputAmount: CurrencyAmount {
      numerator: [JSBI],
      denominator: [JSBI],
      currency: [Token],
      decimalScale: [JSBI]
    },
    _outputAmount: CurrencyAmount {
      numerator: [JSBI],
      denominator: [JSBI],
      currency: [Token],
      decimalScale: [JSBI]
    }
  },
  methodParameters: {
    calldata: '0x5ae401dc000000000000000000000000000000000000000000000000000000006272f9f00000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000500000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000001c000000000000000000000000000000000000000000000000000000000000002400000000000000000000000000000000000000000000000000000000000000380000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000e404e45aaf0000000000000000000000002791bca1f2de4661ed88a30c99a7a9449aa841740000000000000000000000000d500b1d8e8ef31e21c99d1db9a6444d3adf127000000000000000000000000000000000000000000000000000000000000001f40000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000285cbf6000000000000000000000000000000000000000000000001e152bc12a245b5fb0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000044f2d5d56b0000000000000000000000002791bca1f2de4661ed88a30c99a7a9449aa84174000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010411ed56c90000000000000000000000000d500b1d8e8ef31e21c99d1db9a6444d3adf12700000000000000000000000002791bca1f2de4661ed88a30c99a7a9449aa8417400000000000000000000000000000000000000000000000000000000000001f4fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffbcbd4fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffbcc9c00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000d91eccad3707603a759020f2ece22b63e455ef9f000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000044e90a182f0000000000000000000000002791bca1f2de4661ed88a30c99a7a9449aa841740000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000044e90a182f0000000000000000000000000d500b1d8e8ef31e21c99d1db9a6444d3adf1270000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
    value: '0'
  },
  blockNumber: BigNumber { _hex: '0x01aa2812', _isBigNumber: true },
  optimalRatio: Fraction {
    numerator: JSBI(0) [ sign: false ],
    denominator: JSBI(1) [ 1, sign: false ]
  },
  postSwapTargetPool: Pool {
    token0: Token {
      chainId: 137,
      decimals: 18,
      symbol: undefined,
      name: undefined,
      isNative: false,
      isToken: true,
      address: '0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270'
    },
    token1: Token {
      chainId: 137,
      decimals: 6,
      symbol: undefined,
      name: undefined,
      isNative: false,
      isToken: true,
      address: '0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174'
    },
    fee: 500,
    sqrtRatioX96: JSBI(3) [ 565056120, 992157865, 74063, sign: false ],
    liquidity: JSBI(3) [ 441080078, 478360270, 14, sign: false ],
    tickCurrent: -274827,
    tickDataProvider: NoTickDataProvider {}
  }
}
Waiting for tx
1.16162 -274826
/home/eyon/code/UniSWBot/uniswap-sdk/node_modules/@ethersproject/logger/lib/index.js:233
        var error = new Error(message);
                    ^

Error: transaction failed [ See: https://links.ethers.org/v5-errors-CALL_EXCEPTION ] (transactionHash="0x946104cc9f0370ada9a10bc500a8504b9d7280d5877bb87a79e1b163109fbc79", transaction={"type":2,"chainId":137,"nonce":45,"maxPriorityFeePerGas":{"type":"BigNumber","hex":"0x06fc88749a"},"maxFeePerGas":{"type":"BigNumber","hex":"0x06fc88749a"},"gasPrice":null,"gasLimit":{"type":"BigNumber","hex":"0x0f4240"},"to":"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45","value":{"type":"BigNumber","hex":"0x00"},"data":"0x5ae401dc000000000000000000000000000000000000000000000000000000006272f9f00000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000500000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000001c000000000000000000000000000000000000000000000000000000000000002400000000000000000000000000000000000000000000000000000000000000380000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000e404e45aaf0000000000000000000000002791bca1f2de4661ed88a30c99a7a9449aa841740000000000000000000000000d500b1d8e8ef31e21c99d1db9a6444d3adf127000000000000000000000000000000000000000000000000000000000000001f40000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000285cbf6000000000000000000000000000000000000000000000001e152bc12a245b5fb0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000044f2d5d56b0000000000000000000000002791bca1f2de4661ed88a30c99a7a9449aa84174000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010411ed56c90000000000000000000000000d500b1d8e8ef31e21c99d1db9a6444d3adf12700000000000000000000000002791bca1f2de4661ed88a30c99a7a9449aa8417400000000000000000000000000000000000000000000000000000000000001f4fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffbcbd4fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffbcc9c00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000d91eccad3707603a759020f2ece22b63e455ef9f000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000044e90a182f0000000000000000000000002791bca1f2de4661ed88a30c99a7a9449aa841740000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000044e90a182f0000000000000000000000000d500b1d8e8ef31e21c99d1db9a6444d3adf1270000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","accessList":[],"hash":"0x946104cc9f0370ada9a10bc500a8504b9d7280d5877bb87a79e1b163109fbc79","v":0,"r":"0x073da5ba048bf4517b8421e679f6c9e83b434ee788b4114fa3459dd5933180b8","s":"0x1daca54cd65af6bab25a73f1d1db60718d65b8efb3b714a3deaa7738296d5ef8","from":"0xD91EccAD3707603a759020f2Ece22b63e455eF9f","confirmations":0}, receipt={"to":"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45","from":"0xD91EccAD3707603a759020f2Ece22b63e455eF9f","contractAddress":null,"transactionIndex":66,"gasUsed":{"type":"BigNumber","hex":"0x021855"},"logsBloom":"0x00000000000000000000000000000000000000000000000000000000000000000000000000000040000000000000000000008000000000000000000000000000000000000000000000000000000000800000000000000000000100000000000000000000000008000000000000000000000000000000000080000000000000000000000000000000000400000000000000000000000000000000000000000000200000000000000000000000000000000004000000000000000000000000004000000000000000000001000000000000000000000000000000100000000000004000000000000000000000000200000000000000000000000000000000100000","blockHash":"0x7890b227e1a75d122512b5fc47dc37a7b11a8d4f48e93d043e179b819f3a52b0","transactionHash":"0x946104cc9f0370ada9a10bc500a8504b9d7280d5877bb87a79e1b163109fbc79","logs":[{"transactionIndex":66,"blockNumber":27928605,"transactionHash":"0x946104cc9f0370ada9a10bc500a8504b9d7280d5877bb87a79e1b163109fbc79","address":"0x0000000000000000000000000000000000001010","topics":["0x4dfe1bbbcf077ddc3e01291eea2d5c70c2b422b415d95645b9adcfd678cb1d63","0x0000000000000000000000000000000000000000000000000000000000001010","0x000000000000000000000000d91eccad3707603a759020f2ece22b63e455ef9f","0x000000000000000000000000e4cd4c302befddf3d544301369ae3ed1481652fd"],"data":"0x000000000000000000000000000000000000000000000000000ea30f8d4d897d0000000000000000000000000000000000000000000000008706e13bb1cca3de000000000000000000000000000000000000000000000d6fe0cea215fd49d2a000000000000000000000000000000000000000000000000086f83e2c247f1a61000000000000000000000000000000000000000000000d6fe0dd45258a975c1d","logIndex":293,"blockHash":"0x7890b227e1a75d122512b5fc47dc37a7b11a8d4f48e93d043e179b819f3a52b0"}],"blockNumber":27928605,"confirmations":1,"cumulativeGasUsed":{"type":"BigNumber","hex":"0xa2eb92"},"effectiveGasPrice":{"type":"BigNumber","hex":"0x06fc88749a"},"status":0,"type":2,"byzantium":true}, code=CALL_EXCEPTION, version=providers/5.6.4)
    at Logger.makeError (/home/eyon/code/UniSWBot/uniswap-sdk/node_modules/@ethersproject/logger/lib/index.js:233:21)
    at Logger.throwError (/home/eyon/code/UniSWBot/uniswap-sdk/node_modules/@ethersproject/logger/lib/index.js:242:20)
    at JsonRpcProvider.<anonymous> (/home/eyon/code/UniSWBot/uniswap-sdk/node_modules/@ethersproject/providers/lib/base-provider.js:1676:36)
    at step (/home/eyon/code/UniSWBot/uniswap-sdk/node_modules/@ethersproject/providers/lib/base-provider.js:48:23)
    at Object.next (/home/eyon/code/UniSWBot/uniswap-sdk/node_modules/@ethersproject/providers/lib/base-provider.js:29:53)
    at fulfilled (/home/eyon/code/UniSWBot/uniswap-sdk/node_modules/@ethersproject/providers/lib/base-provider.js:20:58) {
  reason: 'transaction failed',
  code: 'CALL_EXCEPTION',
  transactionHash: '0x946104cc9f0370ada9a10bc500a8504b9d7280d5877bb87a79e1b163109fbc79',
  transaction: {
    type: 2,
    chainId: 137,
    nonce: 45,
    maxPriorityFeePerGas: BigNumber { _hex: '0x06fc88749a', _isBigNumber: true },
    maxFeePerGas: BigNumber { _hex: '0x06fc88749a', _isBigNumber: true },
    gasPrice: null,
    gasLimit: BigNumber { _hex: '0x0f4240', _isBigNumber: true },
    to: '0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45',
    value: BigNumber { _hex: '0x00', _isBigNumber: true },
    data: '0x5ae401dc000000000000000000000000000000000000000000000000000000006272f9f00000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000500000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000001c000000000000000000000000000000000000000000000000000000000000002400000000000000000000000000000000000000000000000000000000000000380000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000e404e45aaf0000000000000000000000002791bca1f2de4661ed88a30c99a7a9449aa841740000000000000000000000000d500b1d8e8ef31e21c99d1db9a6444d3adf127000000000000000000000000000000000000000000000000000000000000001f40000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000285cbf6000000000000000000000000000000000000000000000001e152bc12a245b5fb0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000044f2d5d56b0000000000000000000000002791bca1f2de4661ed88a30c99a7a9449aa84174000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010411ed56c90000000000000000000000000d500b1d8e8ef31e21c99d1db9a6444d3adf12700000000000000000000000002791bca1f2de4661ed88a30c99a7a9449aa8417400000000000000000000000000000000000000000000000000000000000001f4fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffbcbd4fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffbcc9c00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000d91eccad3707603a759020f2ece22b63e455ef9f000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000044e90a182f0000000000000000000000002791bca1f2de4661ed88a30c99a7a9449aa841740000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000044e90a182f0000000000000000000000000d500b1d8e8ef31e21c99d1db9a6444d3adf1270000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
    accessList: [],
    hash: '0x946104cc9f0370ada9a10bc500a8504b9d7280d5877bb87a79e1b163109fbc79',
    v: 0,
    r: '0x073da5ba048bf4517b8421e679f6c9e83b434ee788b4114fa3459dd5933180b8',
    s: '0x1daca54cd65af6bab25a73f1d1db60718d65b8efb3b714a3deaa7738296d5ef8',
    from: '0xD91EccAD3707603a759020f2Ece22b63e455eF9f',
    confirmations: 0,
    wait: [Function (anonymous)]
  },
  receipt: {
    to: '0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45',
    from: '0xD91EccAD3707603a759020f2Ece22b63e455eF9f',
    contractAddress: null,
    transactionIndex: 66,
    gasUsed: BigNumber { _hex: '0x021855', _isBigNumber: true },
    logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000040000000000000000000008000000000000000000000000000000000000000000000000000000000800000000000000000000100000000000000000000000008000000000000000000000000000000000080000000000000000000000000000000000400000000000000000000000000000000000000000000200000000000000000000000000000000004000000000000000000000000004000000000000000000001000000000000000000000000000000100000000000004000000000000000000000000200000000000000000000000000000000100000',
    blockHash: '0x7890b227e1a75d122512b5fc47dc37a7b11a8d4f48e93d043e179b819f3a52b0',
    transactionHash: '0x946104cc9f0370ada9a10bc500a8504b9d7280d5877bb87a79e1b163109fbc79',
    logs: [
      {
        transactionIndex: 66,
        blockNumber: 27928605,
        transactionHash: '0x946104cc9f0370ada9a10bc500a8504b9d7280d5877bb87a79e1b163109fbc79',
        address: '0x0000000000000000000000000000000000001010',
        topics: [
          '0x4dfe1bbbcf077ddc3e01291eea2d5c70c2b422b415d95645b9adcfd678cb1d63',
          '0x0000000000000000000000000000000000000000000000000000000000001010',
          '0x000000000000000000000000d91eccad3707603a759020f2ece22b63e455ef9f',
          '0x000000000000000000000000e4cd4c302befddf3d544301369ae3ed1481652fd'
        ],
        data: '0x000000000000000000000000000000000000000000000000000ea30f8d4d897d0000000000000000000000000000000000000000000000008706e13bb1cca3de000000000000000000000000000000000000000000000d6fe0cea215fd49d2a000000000000000000000000000000000000000000000000086f83e2c247f1a61000000000000000000000000000000000000000000000d6fe0dd45258a975c1d',
        logIndex: 293,
        blockHash: '0x7890b227e1a75d122512b5fc47dc37a7b11a8d4f48e93d043e179b819f3a52b0'
      }
    ],
    blockNumber: 27928605,
    confirmations: 1,
    cumulativeGasUsed: BigNumber { _hex: '0xa2eb92', _isBigNumber: true },
    effectiveGasPrice: BigNumber { _hex: '0x06fc88749a', _isBigNumber: true },
    status: 0,
    type: 2,
    byzantium: true
  }
}
``
Eyon42 commented 2 years ago

Nevermind. One of my tokens wasn't approved.

saburo-super commented 2 years ago

how to import smart-order-router on vue-vite?

a-straus commented 2 years ago

Hi Eyon, I see that you just put gasLimit: 1000000 on your transaction, rather than relying on the gas that the routeToRatio method returned. We also saw that the routeToRatio function was perhaps underestimating gas. Curious if you saw that it was underestimating too.

Also wondering if you had any Fraction parsing issues. We had to change some of the Fraction code to get the AlphaRouter working

Eyon42 commented 2 years ago

Yes, It was directly failing to estimate gas and throwing an error. Haven't had Fraction issues yet.