4

I'm trying to create a helper in a contract that lets the user deposit a single token and have it internally swap to the other token and add it as liquidity.

Lets say there is an LP with ETH and BTC and a user supplies only ETH, then how much of that ETH should be swapped to BTC to maximize the liquidity returned?

You could swap 50% percent but I'm looking for the exact answer that takes into account the 0.3% fee and the change in ratio because of the swap.

Zapper calculates as follows:

    function calculateSwapInAmount(uint256 reserveIn, uint256 userIn)
        internal
        pure
        returns (uint256)
    {
        return
            Babylonian
                .sqrt(
                reserveIn.mul(userIn.mul(3988000) + reserveIn.mul(3988009))
            )
                .sub(reserveIn.mul(1997)) / 1994;
    }

Zapper uniswap add contract (https://etherscan.io/address/0x5ACedBA6C402e2682D312a7b4982eda0Ccf2d2E3#code)

How is this formula derived and is it correct?

roelio
  • 141
  • 2

2 Answers2

1

I have the math to this exactly worked out via my python package UniswapPy; the step-by-step walkthrough is in the jupyter notebook

Here are a few image clippings from it:

enter image description here

enter image description here

Then solve the quadratic for alpha; but you really have to read the notebook to get the full description

Ian Moore
  • 71
  • 5
0

Got an answer via Zapper discord which lead me to https://blog.alphafinance.io/onesideduniswap/

roelio
  • 141
  • 2