1

Can someone tell me how to calculate the amountOutMin parameter in the swapRouter.exactInputSingle() function using an onchain oracle? I've got a working uniswapV3 oracle that can retrieve the price of a token and my V3 swap function works as expected. We can easily change the oracle implementation to retreive two prices if needed. I've included some of the code below - see TODO

    function swapExactInputSingle(
        address _tokenIn,
        address _tokenOut,
        uint256 _amountIn
    ) private returns (uint256 amountOut) {
        TransferHelper.safeApprove(_tokenIn, address(swapRouter), _amountIn);

        uint32 secondsIn = 10;
        uint256 price = IUniswapV3PriceOracle(uniswapV3PriceOracle).estimateAmountOut(_tokenIn, uint128(_amountIn), secondsIn);

        // TODO: We need to use the price from the oracle to calculate amountOutMinimum
        uint256 amountOutMinimum = 1;

        ISwapRouter.ExactInputSingleParams memory params = ISwapRouter
            .ExactInputSingleParams({
                tokenIn: _tokenIn,
                tokenOut: _tokenOut,
                fee: poolFee,
                recipient: address(this),
                deadline: block.timestamp,
                amountIn: _amountIn,
                amountOutMinimum: amountOutMinimum,
                sqrtPriceLimitX96: 0
            });

        amountOut = swapRouter.exactInputSingle(params);
    }
1
  • Can you please share the code for the oracle you're using? I guess it is a TWAP oracle and I'm curious about the TWAP duration you're using in production. Did you use a 10s TWAP?
    – Gervin
    Commented Feb 1, 2023 at 23:30

1 Answer 1

0

I bet that you need to change:

amountOutMinimum: amountOutMinimum,

for

amountOutMinimum: price,
1
  • Yeah turns out the price from the price oracle was all I needed. For some reason I thought it may be complicated than that - thanks. I later calculated what 99% of the price would be and passed that into amountOutMin - this meant I allowed for 1% slippage. Commented Jul 14, 2022 at 14:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.