0

In my stylus contract, I have the following sol_storage:

sol_storage! {
    #[entrypoint]
    pub struct SimpleStorage {
        mapping(string => string) name_to_favorite_number;
    }
}

And, I have a public function I'd like to use to update the mapping:

    pub fn add_person(&mut self, name: String, favorite_number: U256) -> Result<(), Vec<u8>> {
        // add a person to the mapping of people
        // ?????
        Ok(())
    }

How do I add the value into the mapping?

1 Answer 1

1

When you add mapping(string => string) name_to_favorite_number; into your contract SimpleStorage, you behind-the-scenes add a StorageMap<String, StorageUint<256, 4>> object to self as name_to_favorite_number.

So, you can access it by:

let name_to_number: StorageMap<String, StorageUint<256, 4>> = self.name_to_favorite_number;

Note, you can't actually run the above line because you can't copy out this, but you have to use a function to interact with it... see more below.

This StorageMap object then acts similar to a solidity mapping, and you can get a StorageGuardMut<'_, V> object which acts as a sort of mapping "setter".

Where passing the name as the key will allow you to set the value.

let name_to_number_setter = name_to_number.setter(name)

Then, you can set the value:

name_to_number_setter.set(favorite_number)

The whole function would look like:

    pub fn add_person(&mut self, name: String, favorite_number: U256) -> Result<(), Vec<u8>> {
        let mut name_to_favorite_number_setter = self.name_to_favorite_number.setter(name);
        name_to_favorite_number_setter.set(favorite_number);
        Ok(())
    }

Or, minimized:

    pub fn add_person(&mut self, name: String, favorite_number: U256) -> Result<(), Vec<u8>> {
        self.name_to_favorite_number
            .setter(name)
            .set(favorite_number);
        Ok(())
    }

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.