Skip to content

Commit

Permalink
test: storing-custom-types
Browse files Browse the repository at this point in the history
  • Loading branch information
julio4 committed May 2, 2024
1 parent a32e0d3 commit cb31be2
Show file tree
Hide file tree
Showing 5 changed files with 25 additions and 35 deletions.
2 changes: 1 addition & 1 deletion listings/getting-started/bytearray/src/bytearray.cairo
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
// ANCHOR: contract
#[starknet::interface]
pub trait IMessage<TContractState> {
fn append(ref self: TContractState, str: ByteArray);
fn prepend(ref self: TContractState, str: ByteArray);
}

// ANCHOR: contract
#[starknet::contract]
pub mod MessageContract {
#[storage]
Expand Down
23 changes: 23 additions & 0 deletions listings/getting-started/storing_custom_types/src/contract.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ pub trait IStoringCustomType<TContractState> {
fn set_person(ref self: TContractState, person: Person);
}

// ANCHOR: contract
// Deriving the starknet::Store trait
// allows us to store the `Person` struct in the contract's storage.
#[derive(Drop, Serde, Copy, starknet::Store)]
Expand All @@ -27,3 +28,25 @@ pub mod StoringCustomType {
}
}
}
// ANCHOR_END: contract

#[cfg(test)]
mod tests {
use super::{
IStoringCustomType, StoringCustomType, Person,
StoringCustomType::personContractMemberStateTrait
};

#[test]
fn can_call_set_person() {
let mut state = StoringCustomType::contract_state_for_testing();

let person = Person { age: 10, name: 'Joe' };

state.set_person(person);
let read_person = state.person.read();

assert(person.age == read_person.age, 'wrong age');
assert(person.name == read_person.name, 'wrong name');
}
}
3 changes: 0 additions & 3 deletions listings/getting-started/storing_custom_types/src/lib.cairo
Original file line number Diff line number Diff line change
@@ -1,4 +1 @@
mod contract;

#[cfg(test)]
mod tests;
30 changes: 0 additions & 30 deletions listings/getting-started/storing_custom_types/src/tests.cairo

This file was deleted.

2 changes: 1 addition & 1 deletion src/ch00/basics/storing-custom-types.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@
While native types can be stored in a contract's storage without any additional work, custom types require a bit more work. This is because at compile time, the compiler does not know how to store custom types in storage. To solve this, we need to implement the `Store` trait for our custom type. Hopefully, we can just derive this trait for our custom type - unless it contains arrays or dictionaries.

```rust
{{#include ../../../listings/getting-started/storing_custom_types/src/contract.cairo}}
{{#rustdoc_include ../../../listings/getting-started/storing_custom_types/src/contract.cairo:contract}}
```

0 comments on commit cb31be2

Please sign in to comment.