1

I am writing some smart contract code that needs to add liquidity to a Uniswap V2 pair.

I have already performed some validation checks at the start of my transaction function to ensure that the current price is acceptable for providing liquidity.

My contract holds a lot of Token A and a small bit of Token B.

I would like my contract to use all remaining Token B for providing liquidity, along with whatever amount of Token A that is neccessary.

This means I would like to specify an exact amount of Token B, and let Uniswap calculate how much Token A to take away from me.

Is this the correct way to achieve this?

uint exactTokenBAmount = _tokenB.balanceOf(address(this));
_tokenA.approve(address(_router), 2 ** 256 - 1);
_tokenB.approve(address(_router), exactTokenBAmount);
_router.addLiquidity(address(_tokenA), address(_tokenB), 0, exactTokenBAmount, 0, exactTokenBAmount, address(this), block.timestamp);

As you can see, I am specifying the exact amount for Token B, but specifying 0 for Token A in the hopes that Uniswap can calculate this amount itself.

Are there any problems with this way of doing it, and if so, is there another way I should be doing this?

2

Well i'm not super familiar with UniswapV2 contracts, so this is just my 2 cents but it seems that router02 calculates that price and checks if it matches what you entered (uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB);), and it indeed seems that uniswapV2Library's quote function is what you're looking for

    // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
    function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
        require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
        require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
        amountB = amountA.mul(reserveB) / reserveA;
    }

so i would either call it or copy it in my contract (it doesnt make any external calls,you'd just need to call getReserves to get reserveA and reserveB beforehand) to compute this number before calling addLiquidity

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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