prb-math icon indicating copy to clipboard operation
prb-math copied to clipboard

Feature Request: Add token decimal conversion utilities to PRB Math

Open darryl-eth opened this issue 10 months ago • 3 comments

Describe the feature you would like

It is common for ERC20 tokens to use decimals other than 18 when representing token amounts. For example, USDT has 6 decimals, meaning 10_000_000 represents 10 USDT. When working with these tokens, we often need to convert between the token's native decimals and UD60x18. I'd like to suggest adding utility functions similar to the following.

function toUD60x18(uint256 raw_amount, uint8 decimals) internal pure returns (UD60x18) {
    if (decimals < 18) {
        return ud(raw_amount * 10 ** (18 - decimals));
    } else if (decimals > 18) {
        return ud(raw_amount / (10 ** (decimals - 18)));
    }
    return ud(raw_amount);
}

function fromUD60x18(UD60x18 ud_amount, uint8 decimals) internal pure returns (uint256) {
    if (decimals < 18) {
        return ud_amount.unwrap() / (10 ** (18 - decimals));
    } else if (decimals > 18) {
        return ud_amount.unwrap() * 10 ** (decimals - 18);
    }
    return ud_amount.unwrap();
}

Additional context

No response

darryl-eth avatar Apr 03 '25 03:04 darryl-eth

Thanks for your feature request!

Am I right that you basically want the ERC20Normalizer logic ported to PRBMath?

PaulRBerg avatar Apr 03 '25 09:04 PaulRBerg

Thanks for your feature request!

Am I right that you basically want the ERC20Normalizer logic ported to PRBMath?

yes I think so. The use case would be more general than just ERC20 balance. For example, we might be dealing with a uint that is upscaled to 10^10. and we would like to easily convert it to a UD60x18, to do some math operation, then convert it back to 10dp.

(btw, i edited the original description to fix some error)

darryl-eth avatar Apr 03 '25 09:04 darryl-eth

Yeah, it's a good idea and feature request. Thanks for sharing.

PaulRBerg avatar Apr 03 '25 10:04 PaulRBerg