JavaScript and big numbers, calculating reserve data erc20 and bep20

383 views Asked by At

I have searched all day and still no working solution. My problem is I am working with JavaScript to get EVM blockchain data and any library I use does not work exactly.

// pair
// 0 = BMON
// 1 = BUSD

// transaction
const tx0 = 2755738843649989653057n; // amount0Out BMON
const tx1 = 113747760332474227520n; // amount1In BUSD

// reserve after transaction
const x = 466822693713887341798087n; // reserve0 BMON
const y = 19334468154310748213608n; // reserve1 BUSD
const k = x * y;
console.log(k)

const newX = x + tx0;
const newY = y - tx1;
const newK = newX * newY;
console.log(newK)

in Uniswap a price is based off the reserves. and I get data from a Swap event what and how much goes in and out.

Just for a test to see if my calculations are 100% accurate I made the above small script.

I get the reserves data after the transaction, but I need to know the price before the transaction. I subtract what's going in and add what's going out to make a new reserve. the constant of the reserve has to be always the same. my code knows the reserve after the transaction and the reserve before the transaction when I did the add/subtract but somehow the constant is never the same as it should be.

I tried bigInt, BigNumber.js, normal numbers etc. Nothing is working. and I need it to work 100% accurate.

Is there someone who can help me please?

1

There are 1 answers

7
Lukas Liesis On BEST ANSWER

Call Number.MAX_SAFE_INTEGER and you will find max safe integer value. If you go out of this range, math becomes tricky and you probably won't be happy with results.

Your math must stay in the range of max safe integer to have good results.

Read more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER

You may explore BigInt but it has it's own caveats just like float point numbers.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt

Read more here: https://www.smashingmagazine.com/2019/07/essential-guide-javascript-newest-data-type-bigint/#the-problem

enter image description here

If you found it useful, please consider upvoting/accepting