Skip to content

Commit

Permalink
fix: #87 (#89)
Browse files Browse the repository at this point in the history
  • Loading branch information
julio4 authored Oct 5, 2023
1 parent a8d000b commit d9a3cac
Show file tree
Hide file tree
Showing 3 changed files with 6 additions and 13 deletions.
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
#[starknet::contract]
mod PetRegistry {
use poseidon::poseidon_hash_span;
use hash::{HashStateTrait, Hash};

#[storage]
struct Storage {
registration_time: LegacyMap::<felt252, u64>,
registration_time: LegacyMap::<Pet, u64>,
}

#[derive(Copy, Drop, Serde)]
#[derive(Copy, Drop, Serde, Hash)]
struct Pet {
name: felt252,
age: u8,
Expand All @@ -18,17 +18,11 @@ mod PetRegistry {
#[generate_trait]
impl PetRegistry of PetRegistryTrait {
fn register_pet(ref self: ContractState, key: Pet, timestamp: u64) {
let mut serialized: Array<felt252> = ArrayTrait::new();
Serde::<Pet>::serialize(@key, ref serialized);
let hashed_key = poseidon_hash_span(serialized.span());
self.registration_time.write(hashed_key, timestamp);
self.registration_time.write(key, timestamp);
}

fn get_registration_date(self: @ContractState, key: Pet) -> u64 {
let mut serialized: Array<felt252> = ArrayTrait::new();
Serde::<Pet>::serialize(@key, ref serialized);
let hashed_key = poseidon_hash_span(serialized.span());
self.registration_time.read(hashed_key)
self.registration_time.read(key)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ mod tests {
let pet = Pet { name: 'Cute Labrador', age: 5, owner: 'Louis' };

// Store a pet.

contract.register_pet(pet, 1234);

// Read the array.
Expand Down
2 changes: 1 addition & 1 deletion src/ch01-03-struct-mapping-key.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Structs as mapping keys

It is currently impossible to use structs as mapping keys. However, a workaround consists in hashing the values of all the struct's fields, and use this hash as a key in the `LegacyMap` type.
In order to use structs as mapping keys, you can use `#[derive(Hash)]` on the struct definition. This will automatically generate a hash function for the struct that can be used to represent the struct as a key in a `LegacyMap`.

Consider the following example in which we would like to use an object of
type `Pet` as a key in a `LegacyMap`. The `Pet` struct has three fields: `name`, `age` and `owner`. We consider that the combination of these three fields uniquely identifies a pet.
Expand Down

0 comments on commit d9a3cac

Please sign in to comment.