Created
April 28, 2021 21:13
-
-
Save TomiOhl/1c5ac6126210a89ae632f9e8fd6e3e4c to your computer and use it in GitHub Desktop.
Converting an amount from one token's decimals to another in Solidity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity 0.8.4; | |
interface IERC20 { | |
function decimals() external view returns (uint8); | |
} | |
contract DecimalsTest { | |
function changeDecimals(address _fromToken, address _desToken, uint _amount) external view returns (uint) { | |
return convertDecimals(_amount, getDecimals(_fromToken), getDecimals(_desToken)); | |
} | |
function getDecimals(address _token) internal view returns (uint8) { | |
return IERC20(_token).decimals(); | |
} | |
// Convert from the decimals of token1 to the decimals of token2 | |
// Slight inaccuracy when converting to fewer decimals (approx. a quarter of a usd cent on an ether -> usdc swap) | |
function convertDecimals(uint _tokenAmount, uint8 _token1decimals, uint8 _token2decimals) internal pure returns (uint) { | |
if (_token1decimals > _token2decimals) | |
return _tokenAmount / (10**(_token1decimals - _token2decimals)); | |
else | |
return _tokenAmount * (10**(_token2decimals - _token1decimals)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment