Skip to content

Commit c60b659

Browse files
ptisserandArcticae
andauthored
Add example using storage_address_from_base for store cheatcode (#2175)
## Introduced changes <!-- A brief description of the changes --> - Add an example using `storage_address_from_base` for `store` cheatcode ## Checklist <!-- Make sure all of these are complete --> - [ ] Linked relevant issue - [x] Updated relevant documentation - [ ] Added relevant tests - [ ] Performed self-review of the code - [ ] Added changes to `CHANGELOG.md` --------- Co-authored-by: Tomasz Rejowski <[email protected]>
1 parent c3437be commit c60b659

File tree

1 file changed

+41
-1
lines changed

1 file changed

+41
-1
lines changed

docs/src/snforge-advanced-features/storage-cheatcodes.md

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@ which allow manipulating the storage directly (reading and writing).
77
In order to obtain the variable address that you'd like to write to, or read from, you need to use either:
88
- `selector!` macro - if the variable is not a mapping
99
- `map_entry_address` function in tandem with `selector!` - for key-value pair of a map variable
10-
10+
- `starknet::storage_access::storage_address_from_base`
11+
1112
## Example: Felt-only storage
1213
This example uses only felts for simplicity
1314

@@ -160,4 +161,43 @@ fn store_in_complex_mapping() {
160161
> The `load` cheatcode will return zeros for memory you haven't written into yet (it is a default storage value for Starknet contracts' storage).
161162
162163
164+
## Example with `storage_address_from_base`
165+
166+
This example uses `storage_address_from_base` with `address` function of the [storage variable](https://book.cairo-lang.org/ch14-01-contract-storage.html#addresses-of-storage-variables).
167+
168+
To retrieve storage address of a given `field`, you need to import `{field_name}ContractMemberStateTrait` from the contract.
169+
170+
```rust
171+
#[starknet::contract]
172+
mod Contract {
173+
#[storage]
174+
struct Storage {
175+
map: LegacyMap::<(u8, u32), u32>,
176+
}
177+
}
178+
179+
// ...
180+
use starknet::storage_access::storage_address_from_base;
181+
use snforge_std::{ store, load };
182+
use Contract::mapContractMemberStateTrait;
183+
184+
#[test]
185+
fn update_mapping() {
186+
let key = (1_u8, 10_u32);
187+
let data = 42_u32;
188+
189+
// ...
190+
let mut state = Contract::contract_state_for_testing();
191+
let storage_address: felt252 = storage_address_from_base(
192+
state.map.address(key)
193+
)
194+
.into();
195+
let storage_value: Span<felt252> = array![data.into()].span();
196+
store(contract_address, storage_address, storage_value);
197+
198+
let read_data: u32 = load(contract_address, storage_address, 1).at(0).try_into().unwrap():
199+
assert_eq!(read_data, data, "Storage update failed")
200+
}
201+
202+
```
163203

0 commit comments

Comments
 (0)