pub fn convert(
amount: impl Into<Uint256>,
rate: impl Into<Uint256>,
input_decimals: u8,
output_decimals: u8
) -> StdResult<Uint256>
Expand description
Convert between tokens with different decimals.
Arguments
amount
- the amount of input token to convertrate
- corresponds to the output token decimals. E.g: If we want 1:1 rate and the output token has 6 decimals, then rate = 1_000_000input_decimals
- the number of decimals of the input tokenoutput_decimals
- the number of decimals of the output token
Examples
Assuming the user friendly (in the UI) exchange rate has been set to 1 output_token (9 decimals) == 1.5 input_token (6 decimals): the rate would be 1 / 1.5 = 0.(6) or 666666666 (0.(6) ** 10 * 9) meaning the price for 1 output_token is 1500000000 (1.5 * 10 ** 9 decimals) of input_token.
If we want to get 2 of output_token, we need to send 3 input_token i.e. amount = 3000000000 (3 * 10 ** 9 decimals)
use fadroma::tokens::convert;
use fadroma::cosmwasm_std::Uint256;
let rate = 666_666_666u32;
let amount = 3_000_000u32;
let result = convert(amount, rate, 6, 9).unwrap();
assert_eq!(result, Uint256::from(1_999_999_998u32));