Skip to content
This repository has been archived by the owner on Apr 25, 2024. It is now read-only.

getOutputAmount returns wrong calculation result #70

Open
maximsen opened this issue May 29, 2021 · 2 comments
Open

getOutputAmount returns wrong calculation result #70

maximsen opened this issue May 29, 2021 · 2 comments

Comments

@maximsen
Copy link

I create pair with ratio 1200/400 and try to simulate swap.
Input amount is 3 USDC. I add fee for input and expect to get output amount, which should be 1 WETH, but get different value

const USDC = new Token(1, '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', 18, 'USDC', 'USD Coin')
const WETH = new Token(1, '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', 18, 'WETH9', 'Wrapped Ether')
const pair = new Pair(
    CurrencyAmount.fromRawAmount(USDC, 1200 * (10 ** USDC.decimals)),
    CurrencyAmount.fromRawAmount(WETH, 400 * (10 ** WETH.decimals))
);

const imputAmount = CurrencyAmount.fromRawAmount(USDC, 3 * (10 ** USDC.decimals));
const inputAmountWithFee = imputAmount.multiply(new Fraction(1000, 997));
const [outputAmount] = pair.getOutputAmount(inputAmountWithFee);
consoel.log(outputAmount.toSignificant()) // 0.997506

outputAmount should equal to 1, but I get 0.99750
It seems like fee isn't counted correctly

@maximsen
Copy link
Author

https://github.com/Uniswap/uniswap-v2-sdk/blob/021336d10535f15adc92f464d8b7c8033e2d596e/src/entities/pair.ts#L118
Why inputAmountWithFee added to denominator? Doesn't that change the fee from 0.3%?

@Florian-S-A-W
Copy link

Hi @maximsen

The calculation done by the SDK is correct. If you look at the code of a swap in a V2 Pair, in line 180-181 you can see that the fee is subtracted before calculating that K is still correct after the transaction.

Looking at your transaction, the way the constant product formula works is by calculating a product of the reserves k which needs to stay the same after a trade.
In your example that means k before the calculation:
1200 * 400 = 480.000

needs to be the same after the calculation:

1203 * wethReservesAfter = 480.000
wethReservesAfter = 399.00249...

And the output is:
400 - wethReservesAfter = 0.99750...

If we compare the calculation provided by the SDK and on chain results of swaps, it is also correct. Just keep in mind that the result is rounded to the minimum unit of the currency on-chain and cut off by the formatting function you use in the SDK. The fractional result by the SDK is 100% correct but any representation might be a bit off.

royalaid pushed a commit to royalaid/qidao-sdk that referenced this issue Apr 12, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants