I am recreating a UNISWAP-like AMM and have encountered problems anytime I want to divide the balances of tokens in my pool. For example: I want to require()
that tokens are deposited in the correct ratio (Total number of token 1/Total number of token 2). If I do this I can encounter 2 problems:
- either the result is 0<x<1 and I get 0 which stops all further calculations
- or the result is rounded down to an integer which is a significant calculation error
I hoped using larger numbers (18 decimals) would solve this problem but it hasn't, I also don't want to use external libraries, other than safeMath. What can I do to solve these problems? Thanks!
function deposit(uint256 _amountRED, uint256 _amountYELLOW) payable external returns(uint256){ require((_amountYELLOW * (10 ** 18)) * balance_RED / balance_YELLOW == _amountRED * (10 ** 18), "Ratio not correct!");
Where _amountRED &_amountYELLOW are human readable token values you want to deposit, balance_RED & balance_YELLOW are the 18 decimal values of total number of tokens in the pool already. – nora goba Mar 2 at 19:12_amountYELLOW * balance_RED == _amountRED * balance_YELLOW
, but it will limit the possible values of_amountYELLOW
and_amountRED
to certain divisors of the other side. Perhaps_amountYELLOW * K / _amountRED == balance_YELLOW * K / balance_RED
for some constant K will give better results (you can start withK = 10**18
and ajust how many decimals you care about). – Ismael Mar 3 at 2:36