0

I'm kinda struggling here to find a solution.

I have a code where user can deposit token like USDC, DAI etc...

For example USDC had 6 decimals and DAI has 18 decimals.

How can I have a generic fee calculation in my function so it handle all different case when decimals are differents and also avoid rounding by 0 ?

I have something like this for the calculation :

uint256 feeToCollect = (amount * feeBps * 10**18) / BPS; 

uint256 amountWithFee = amount + fee; 

IERC20(token).transferFrom(msg.sender, address(this), amountWithFee;

amount = amount that the user deposit

feeBps = 10 so it's 0.1%

BPS = 10000

10**18 is a scale to avoid rounding by 0.

Thank you for your help !

2
  • Don't hardcode the decimal value, get it dynamically from IERC20(token).decimals(); Commented Feb 29 at 16:48
  • Correct thanks but I have the following issue when I increment the deposited amount and the fees : Let say I deposit 100 tokens and have 2 mapping that keep track of the deposit and fees : mapping(address => uint256) public totalDeposited; mapping(address => uint256) public feeCollected; uint256 feeToCollect = (amount * feeBps * 10**18) / BPS; uint256 amountWithFee = amount + fee; IERC20(token).transferFrom(msg.sender, address(this), amountWithFee; totalDeposited += amount; feeCollected += fee; Mappings return : 100 -> totalDeposit 100000000000000000 -> feeCollected
    – 0xAurora
    Commented Feb 29 at 22:15

1 Answer 1

0

If I understand the math problem correctly, the code should look something like that:

uint decimalFactor = IERC20(token).decimals(); //should return 18 or 6 in your case.

uint256 feeToCollect = (amount * feeBps * 10**decimalFactor) / BPS;

2
  • Correct thanks but I have the following issue when I increment the deposited amount and the fees : Let say I deposit 100 tokens and have 2 mapping that keep track of the deposit and fees : mapping(address => uint256) public totalDeposited; mapping(address => uint256) public feeCollected; uint256 feeToCollect = (amount * feeBps * 10**18) / BPS; uint256 amountWithFee = amount + fee; IERC20(token).transferFrom(msg.sender, address(this), amountWithFee; totalDeposited += amount; feeCollected += fee; Mappings return : 100 -> totalDeposit 100000000000000000 -> feeCollected
    – 0xAurora
    Commented Feb 29 at 22:20
  • Add explanation for readers on how calculation works.
    – DevCrypto
    Commented Mar 5 at 12:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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