4

Wanted to get some clarity on repeated reads.

Assuming this is the contract storage, two values both under the default 0x00000000 key in the storage.

#[ink(storage)]
pub struct MyContract {
  pub field_1: u32,
  pub field_2: bool,
}

Now are the repeated calls to the storage within one message cached?
Basically, will this incur two reads:

```rust
#[ink(message)]
pub fn get_values(&self) -> (u32, bool) {
    (self.state.field_1, self.state.field_2)
}

Is there any difference if the storage is non-eager? E.g. with a contract like that:

#[derive(Default, Debug)]
#[ink::storage_item]
pub struct State {
    pub field_1: u32,
    pub field_2: bool,
}

#[ink(storage)]
pub struct MyContract {
  pub state: Lazy<State, ManualKey<123>>,  
}

will the 123 cell be read twice, or is it cached on the first read?

#[ink(message)]
pub fn get_values(&self) -> (u32, bool) {
    (self.state.get_or_default().field_1, self.state.get_or_default().field_2)
}

1 Answer 1

5

will the 123 cell be read twice, or is it cached on the first read?

It will be read twice. At the moment the Lazy type is just a thin wrapper around ink::get_contract_storage. So arguably Lazy here is a misleading name since it could imply some form of caching/lazy loading.

If not wrapped in either Lazy or Mapping, storage item data types which are part of the contract storage struct are stored in the same storage cell and thus loaded up on contract invocation. So repeated accesses to fields in that case are "in memory".

In ink! 3 we originally had sophisticated caching data structures but those were removed in order to massively reduce contract binary sizes.

1
  • thanks, that's all very clear - and actually in line with how we've been approaching Lazy thus far - more like a way to arrange storage (with upgrades in mind) than anything else.
    – fbielejec
    Apr 17, 2023 at 11:06

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.