Skip to content

Commit

Permalink
implemented scrub for Store trait
Browse files Browse the repository at this point in the history
  • Loading branch information
dean-starkware committed Jan 27, 2025
1 parent 42c370c commit 7ca7bbe
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 2 deletions.
31 changes: 31 additions & 0 deletions corelib/src/starknet/storage_access.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,37 @@ pub trait Store<T> {
/// This is bounded to 255, as the offset is a u8. As such, a single type can only take up to
/// 255 slots in storage.
fn size() -> u8;

/// Clears the storage area by writing zeroes to it.
///
/// # Arguments
///
/// * `address_domain` - The storage domain
/// * `base` - The base storage address to start clearing
/// * `offset` - The offset from the base address where clearing should start
///
/// The operation writes zeroes to storage starting from the specified base address and offset,
/// and continues for the size of the type as determined by the `size()` function.
#[inline]
fn scrub(
address_domain: u32, base: StorageBaseAddress, offset: u8,
) -> SyscallResult<
(),
> {
let mut result = Result::Ok(());
let mut offset = offset;
for _ in 0..Self::size() {
if let Result::Err(err) =
storage_write_syscall(
address_domain, storage_address_from_base_and_offset(base, offset), 0,
) {
result = Result::Err(err);
break;
}
offset += 1;
};
result
}
}

/// Trait for efficient packing of values into optimized storage representations.
Expand Down
39 changes: 37 additions & 2 deletions crates/cairo-lang-starknet/cairo_level_tests/storage_access.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,8 @@ mod test_contract {
};

#[storage]
struct Storage {
data: AbcEtc,
pub struct Storage {
pub data: AbcEtc,
byte_arrays: ByteArrays,
non_zeros: NonZeros,
vecs: Vecs,
Expand Down Expand Up @@ -402,3 +402,38 @@ fn test_enum_sub_pointers() {
deserialized(test_contract::__external::get_queryable_enum_low(serialized(()))), 789,
);
}

#[test]
fn test_scrub_clears_memory() {
let base_address = starknet::storage_access::storage_base_address_from_felt252(
selector!("data"),
);
for i in 0..=255_u8 {
starknet::Store::<u8>::write_at_offset(0, base_address, i, 1).unwrap();
};
starknet::Store::<
(
felt252,
felt252,
felt252,
felt252,
felt252,
felt252,
felt252,
felt252,
felt252,
felt252,
felt252,
),
>::scrub(0, base_address, 7)
.unwrap();
for i in 0..7_u8 {
assert_eq!(starknet::Store::<u8>::read_at_offset(0, base_address, i).unwrap(), 1);
};
for i in 7..18_u8 {
assert_eq!(starknet::Store::<u8>::read_at_offset(0, base_address, i).unwrap(), 0);
};
for i in 18..=255_u8 {
assert_eq!(starknet::Store::<u8>::read_at_offset(0, base_address, i).unwrap(), 1);
};
}

0 comments on commit 7ca7bbe

Please sign in to comment.