0

i want to make crypto to crypto smart contract where i need to sell erc20 token and on buyer side i need to calculate the price which i have to send to seller and i have a price of token can you please describe the calculation.below is my function.

function buyToken(uint256 _tradeId, address token, uint256 _quantity, uint256 _tokenPrice) external {

   uint256 quantity = _quantity * (10 ** ERC20Interface(token).decimals);
   uint256 amount = quantity * _tokenPrice;

}
  • Comments are not for extended discussion; this conversation has been moved to chat. – eth Jan 25 at 12:15
1

Since the resolution of ether is 18 decimals, but the resolution of an ERC20-token is not necessarily the same, you can use this:

uint256 amount;
uint8 decimals = ERC20Interface(token).decimals;
if (decimals > 18)
    amount = _quantity * _tokenPrice / 10 ** (decimals - 18);
else
    amount = _quantity * _tokenPrice * 10 ** (18 - decimals);

Be sure to replace the * operations with SafeMath.mul.

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.