I am trying to learn Solidity and write a contract that accepts USDC for my token which has 18 decimals.

I'm getting confused as how to treat the amount being sent when I buy my ERC20.


function buyToken(IERC20 token, uint256 amount) public payable

Where token is the address of USDC and amount is the total USDC I will pay/exchange for my ERC20 Token. Should I convert the amount provided (6 decimals) to 18 decimals? How? What is the best practice for this?

2 Answers 2


Since in your case, the token is of 18 decimals, suppose you want to buy 10 tokens so the amount that you would enter is 10 multiplied by 10^18 which means 10000000000000000000. Alternatively you can code your function so that the user enters the actual amount which is 10 and inside the function the amount is multiplied by 10^18 so that no body has to count the number of zeros to append to.

so the above function would become

function buyToken(IERC20 token, uint256 amount) public payable {
uint _amount = amount * (10**18)

****rest of the logic****
  • thanks for this. is it best practice to enter the number of tokens you want to buy? as opposed to entering the amount of money (in this case USDC) you want to spend in the buy function? I always thought that the amount is the amount of money I want to spend.
    – momoja
    Commented Apr 26, 2022 at 9:11
  • This approach does get the job done. Using the parameter to take amount of tokens one would like to buy. Hoping others can share an approach where the amount is used as the amount of money to be spent to purchase tokens. Or whether or not that is a proper approach. :)
    – momoja
    Commented Apr 28, 2022 at 8:01

I solved it as follows

function getLastestPrice() public view returns (uint) {
    (, int256 price, , , ) = priceFeed.latestRoundData();

    uint adjustmentPrice = uint(price) / 10**8;
    return adjustmentPrice;

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.