0

I Wanna to create a StoreBasket in Substrate .

I Have Two Struct one for BusinessItem .

#[derive(Clone, Encode, Decode, PartialEq, RuntimeDebug, TypeInfo)]
#[scale_info(skip_type_params(T))]
#[codec(mel_bound())]
pub struct BusinessItem {
    media: Vec<u8>,
    title: Vec<u8>,
    description: Vec<u8>,
    price: u32,
    count: u32,
    itemId: [u8; 16],
}

also i Defined Storage For Item:

#[pallet::storage]
#[pallet::getter(fn items)]
pub(super) type Items<T: Config> = StorageMap<_, Twox64Concat, T::AccountId, Vec<BusinessItem>>;

I wanna to find item in item Storage with itemid , for exmaple i have itemId : X0o788dfgg and i need to find item with this id in storage .

i wrote this code bit it dose not work :

let _itemInfo: Option<&BusinessItem> = items.iter().find(|item| item.itemId == item_id);

whats the problem ? how can i solve this problem ?

1
  • Why is this not a StorageDoubleMap? Commented Oct 28, 2022 at 13:53

1 Answer 1

1

IterableStorageMap doc.

if let Some(item) = <Items<T>>::iter().find(|(_, i)| i.id == id) {
  log::info!("got {:#?}", item);
}

But I don't recommend using this. Because it will do a lot of r/w, which costs a lot of resources.

Maybe you should add another map to record the mapping ItemId -> AccountId. Or something like that.


Okay, I found you are trying to store a Vec<Item> under each AccountId key. I have to say, this has a really bad performance.

let mut matched_items = Vec::new();
<Items<T>>::iter().for_each(|(_, items)| {
  items.iter().for_each(|i| {
    if i.id == id {
      matched_items.push(i.clone());
    }
  })
});
8
  • it show me this error : ` no field itemId on type `&&frame_support::dispatch::Vec<BusinessItem>`` Commented Oct 25, 2022 at 8:15
  • Sorry, I made a mistake here. Let me update my answer.
    – AurevoirXavier
    Commented Oct 25, 2022 at 8:24
  • thanks for answer but still show me error : ` no field itemId on type `&(<T as frame_system::Config>::AccountId, frame_support::dispatch::Vec<BusinessItem>)`` Commented Oct 25, 2022 at 8:35
  • Sry, try this find(|(_, i)| i.id == id). Because the iterator returns a tuple (K, V).
    – AurevoirXavier
    Commented Oct 25, 2022 at 8:49
  • no field itemId on type &frame_support::dispatch::Vec<BusinessItem> Commented Oct 25, 2022 at 8:55

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.