Joystream / joystream

Joystream Monorepo
http://www.joystream.org
GNU General Public License v3.0
1.42k stars 115 forks source link

Floating point values rounding #298

Open gleb-urvanov opened 4 years ago

gleb-urvanov commented 4 years ago

The following code is used in runtime for stake calculation:

let required_stake = Perbill::from_rational_approximation(numerator, denominator) * total_issuance;
let balance: BalanceOf<T> = required_stake.saturated_into();

required_stake is a floating point, and with usage of saturated_into is rounded to the nearest integer. While in the typesript code

new BN((issuance * numerator) / denominator)

If sent using API, the value will be rounded down. This caused the issue when transaction gets rejected because of incorrect stake value provided, eg 101516 vs 101517. With limited information about tx failure reason, such issue can cost time to find and solve. Also, it is important to display the required stake correctly rounded in UI.

The solution used is to use explicit rounding function in typescript:

const stake = (issuance * numerator) / denominator;
const stakeBN = new BN(stake.toFixed(0));
traumschule commented 2 years ago

relevant commits: cb80ece0d7c66ece64dc5dba7529e6a1815f5998 ed0e2cd279f1baa637f04cc20c845e2a4fe0db39