Skip to content

Feature Request: Add token decimal conversion utilities to PRB Math #252

Description

@darryl-eth

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions