0

I am iterating on all the elements so that I have a complexity O(n).

fn has_item(&self, item: &Item<Self::Api>) -> bool {
    return self.map_items_tokens().iter().any(|i| &i.0 == item);
}

How can I save gas fees?

Fargerik
  • 210
  • 2
  • 6

1 Answers1

0

A pull request is pending https://github.com/ElrondNetwork/elrond-wasm-rs/pull/844

For the moment, you can add this utility to your smart contract.

use elrond_wasm::{
    api::StorageMapperApi,
    elrond_codec::{NestedDecode, NestedEncode, TopDecode, TopEncode},
    storage::{mappers::BiDiMapper, StorageKey},
    storage_get_len,
    types::ManagedType,
};

pub trait ContainsUtils<SA, K, V> {
    fn contains_id(&self, id: &K, base_key: &[u8]) -> bool;
    fn contains_value(&self, value: &V, base_key: &[u8]) -> bool;
}

impl<SA, K, V> ContainsUtils<SA, K, V> for BiDiMapper<SA, K, V>
where
    SA: StorageMapperApi,
    K: TopEncode + TopDecode + NestedEncode + NestedDecode + 'static + Default + PartialEq,
    V: TopEncode + TopDecode + NestedEncode + NestedDecode + 'static + Default + PartialEq,
{
    fn contains_id(&self, id: &K, base_key: &[u8]) -> bool {
        let mut key = StorageKey::<SA>::new(base_key);
        key.append_bytes(b"_id_to_value");
        key.append_item(id);

        return storage_get_len(key.as_ref()) > 0;
    }

    fn contains_value(&self, value: &V, base_key: &[u8]) -> bool {
        let mut key = StorageKey::<SA>::new(base_key);
        key.append_bytes(b"_value_to_id");
        key.append_item(value);

        return storage_get_len(key.as_ref()) > 0;
    }
}

You use it this way,
where mapper_items_token is the same value as your storage key specified in the attribute #[storage_mapper(your key)]

fn has_item(&self, item: &Item<Self::Api>) -> bool {
    return self.map_items_tokens().contains_id(item, b"mapper_items_token");
}
Fargerik
  • 210
  • 2
  • 6
  • The pull request has been accepted, and this feature will be added to the future elrond-wasm-rs version ! – Fargerik Nov 22 '22 at 10:29