I am a bit confused with how to do operations with the Balances in the Substrate runtime. More concrete the division.
The example I want to implement is similar to the Lottery pallet but with shared prizes distribution:
Person A buys 10 UNITS of ticket 1.
Person B buys 10 UNITS of ticket 2.
Person C buys 30 UNITS of ticket 1.
The total Pot is 50 UNITS.
If ticket 1 is the winner, with weighted distribution the person A have to receive the 25% of the pot and the person C the 75%. The maths for this weighted distribution are simple:
the amount that one deposit / the total amount of the winners deposit in the case of Person A = 10/40 = 0.25
The normal division shows a 0 when try for example 10/40:
let weighted = amount_deposit_winner / total_amount_deposit_winners; let amount_to_receive = weighted * total_pot;
This is because you can not use floating point maths in the runtime, and you got the rounded result.
You can check this 2 answers from SE for more info:
So what I did was convert the Substrate type Balance into u128 (How do you convert between Substrate specific types and Rust primitive types?) and do the division using Perquintill as suggested here and here.
let amount_winner_in_u128 = amount_deposit_winner.saturated_into::<u128>(); let total_winners_in_u128 = total_amount_deposit_winners.saturated_into::<u128>(); let weighted = Perquintill::from_rational(amount_winner_in_u128, total_winners_in_u128); let amount_to_receive = weighted.mul_floor(total_pot.saturated_into::<u128>());
And then transform it into Balance again in order to perform the transfer:
Is this a correct way to calculate these weights for Balances in Substrate?, or is there a better way to do it?