5

I don't know how can I convert Option<BalanceOf> (subtrate specific type)to u64 (rust primitive types)?

I followed this article( How do you convert between Substrate specific types and Rust primitive types? ), it helped me while converting u64 to Option<BalanceOf using the below function.

    pub fn u64_to_balance_option(input: u8) -> Option<BalanceOf<T>> {
            input.try_into().ok()
        }

But I also need to convert some Option<BalanceOf> types inside u64 to perform some mathematical operation and then again convert u64 to Option<BalanceOf> to put back inside my storage items.

Thank you

1
  • Can you share the function signature you want, since your question makes exactly what types you are working with confusing.
    – Shawn Tabrizi
    Mar 28, 2022 at 16:48

1 Answer 1

10

You'll see that Currency::Balance is bound to AtLeast32BitUnsigned which by being bound to BaseArithmetic is bound to implement TryInto<u64>. Therefore the most obvious code is something like:

pub fn balance_to_u64_option(input: impl TryInto<u64>) -> Option<u64> {
    input.try_into().ok()
}

However, balances cannot necessarily be expressed as a u64, so this really isn't such a great plan for production code as it will restrict your pallet to being used only when someone has a small enough balance.

In general, you should aim to do all arithmetic in the native Polkadot types. Currency::Balance is required to implement all the typical arithmetic operations for this reason.

1
  • Can you please make it more simple for me, I am very new to substrate and rust, Thank you for your response. Mar 28, 2022 at 14:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.