Reputation: 1
I've tested this function on a few different examples and it seems to return proper numbers but I'm not sure if this is correct and will work for all cases (different decimals of A and B, different values of amountOfB and priceForA etc).
Is this the right way to compute price of token A that have fixed price in amount of B tokens?
function calculatePrice(uint8 decimalsA, uint256 priceForA, uint256 amountOfB) public {
return amountOfB * 10 ** decimalsA / priceForA;
}
Decimals for both tokens A and B can be equal or one can be higher or lower than the other. For example
decimalsA = 6;
decimalsB = 18;
// priceForA is price for 1 (human readable) A token which is 0.01 (human readable) B tokens
// so in other words for 1000000 A you need to pay 10000000000000000 B
priceForA = 10000000000000000;
// this is the amount of B tokens that will be used to buy A tokens
amountOfB = 50000000000000000;
In this example we should get 5000000 as return value so 5A (human readable) tokens.
Upvotes: 0
Views: 543