I'm in the process of developing a smart contract that allows users to purchase tokens. However, I'm encountering an issue with the price calculation:
- The token I'm selling (let's call it "SellToken") has 18 decimals.
- The token being used for purchase (e.g., USDC) has 6 decimals.
Here's the relevant function from my smart contract:
function purchaseTokens(address inputToken, uint256 lockDuration, uint256 amount, uint256 price) external { require(acceptedTokens[inputToken], "Token not accepted"); require(price == priceByLockDuration[lockDuration], "Invalid price"); IERC20 paymentToken = IERC20(inputToken); uint256 totalPrice = price.mul(amount); console.log('totalPrice', totalPrice); console.log('amount', amount); require(paymentToken.balanceOf(msg.sender) >= totalPrice, "Insufficient balance"); require(totalTokensForSale.sub(totalTokensSold) >= amount, "Insufficient sale tokens for sale"); require(paymentToken.transferFrom(msg.sender, address(this), totalPrice), "Payment transfer failed"); Purchase memory newPurchase; newPurchase.amount = amount; newPurchase.unlockTime = block.timestamp.add(lockDuration); newPurchase.claimed = false; purchases[msg.sender].push(newPurchase); purchaseCount[msg.sender] = purchaseCount[msg.sender].add(1); totalTokensSold = totalTokensSold.add(amount); } When I set the price as follows:
const price = ethers.parseUnits('0.1', USDCdecimals) const amount = 1 tokenDistribution.purchaseTokens( USDCtokenAddress, unlockPeriod, amount, price, ) The result is that when a user spends 0.1 USDC, they only receive 0.000000000000000001 SellToken.
How can I adjust the price calculation so that spending 0.1 USDC will give the user 1 SellToken?