Skip to content

Instantly share code, notes, and snippets.

@DavideSilva
Created May 30, 2023 14:02
Show Gist options
  • Save DavideSilva/2c3f604bca6df00551c711eecfaf687f to your computer and use it in GitHub Desktop.
Save DavideSilva/2c3f604bca6df00551c711eecfaf687f to your computer and use it in GitHub Desktop.
Implementation of StorageAccess trait for CustomStruct in Cairo 1
#[contract]
mod HelloStarknet {
use starknet::StorageAccess;
use starknet::StorageBaseAddress;
use starknet::SyscallResult;
use starknet::storage_read_syscall;
use starknet::storage_write_syscall;
use starknet::storage_address_from_base_and_offset;
use traits::{Into, TryInto};
use option::OptionTrait;
struct Storage {
map: LegacyMap<felt252, CustomStruct>,
}
#[derive(Drop, Serde)]
struct CustomStruct {
value_a: u64,
value_b: u64,
value_c: u64,
}
impl CustomStructStorageAccess of StorageAccess::<CustomStruct> {
fn write(address_domain: u32, base: StorageBaseAddress, value: CustomStruct) -> SyscallResult::<()> {
storage_write_syscall(
address_domain,
storage_address_from_base_and_offset(base, 0_u8),
value.value_a.into()
);
storage_write_syscall(
address_domain,
storage_address_from_base_and_offset(base, 1_u8),
value.value_b.into()
);
storage_write_syscall(
address_domain,
storage_address_from_base_and_offset(base, 2_u8),
value.value_c.into()
)
}
fn read(address_domain: u32, base: StorageBaseAddress) -> SyscallResult::<CustomStruct> {
Result::Ok(
CustomStruct {
value_a: storage_read_syscall(
address_domain,
storage_address_from_base_and_offset(base, 0_u8)
)?.try_into().expect('not u64'),
value_b: storage_read_syscall(
address_domain,
storage_address_from_base_and_offset(base, 1_u8)
)?.try_into().expect('not u64'),
value_c: storage_read_syscall(
address_domain,
storage_address_from_base_and_offset(base, 2_u8)
)?.try_into().expect('not u64'),
}
)
}
}
#[constructor]
fn constructor() {
let my_struct: CustomStruct = CustomStruct {
value_a: 1_u64,
value_b: 2_u64,
value_c: 3_u64,
};
map::write(1, my_struct);
let stored_struct = map::read(1);
assert(stored_struct.value_a == 1_u64, 'not u64');
assert(stored_struct.value_b == 2_u64, 'not u64');
assert(stored_struct.value_c == 3_u64, 'not u64');
}
#[external]
fn update_struct(key: felt252, new_struct: CustomStruct) {
map::write(key, new_struct);
}
// Returns the current balance.
#[view]
fn get_struct(key: felt252) -> CustomStruct {
map::read(key)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment