1

I'm using #[pallet::getter(fn get_balance)] for my StorageMap to generate a getter function, but it returns pure u64 instead of Result type. What is the way to handle missing key cases then?

    #[pallet::storage]
    #[pallet::getter(fn get_balance)]
    pub(super) type Balances<T: Config> =
    StorageMap<_, Blake2_128Concat, T::AccountId, u64, ValueQuery>;
    #[pallet::weight(10_000)]
    pub fn transfer(
        _origin: OriginFor<T>,
        to: T::AccountId,
        value: u64,
    ) -> DispatchResultWithPostInfo {
        let sender = ensure_signed(_origin)?;
        let sender_balance = Self::get_balance(&sender);
        let receiver_balance = Self::get_balance(&to).ok_or(0 as u64);

After cargo check I receive this error:

error[E0599]: no method named `ok_or` found for type `u64` in the current scope
  --> pallets/ERC20/src/lib.rs:93:50
   |
93 |             let receiver_balance = Self::get_balance(&to).ok_or(0 as u64);
   |                                                           ^^^^^ method not found in `u64`

I'm using 4.0.0-dev version FRAME libraries and 5.0.0 version sp-* libraries.

1 Answer 1

2

There is a trait bound.

You are using ValueQuery.

The value in the storage map must be implemented Default.

If the key is missing in the storage map, then the default value will be returned.

If you don't want a default value, go for OptionQuery. If you want a result, then X::get(y).ok_or(Error)?.

Your Answer

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

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