From 5cc9f1fb11645af9d7adf5c2824284c24684eb99 Mon Sep 17 00:00:00 2001 From: benesjan Date: Mon, 26 Feb 2024 10:26:40 +0000 Subject: [PATCH] feat: PublicImmutable impl --- .../aztec/src/state_vars/public_immutable.nr | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 noir-projects/aztec-nr/aztec/src/state_vars/public_immutable.nr diff --git a/noir-projects/aztec-nr/aztec/src/state_vars/public_immutable.nr b/noir-projects/aztec-nr/aztec/src/state_vars/public_immutable.nr new file mode 100644 index 00000000000..bbda1e0f509 --- /dev/null +++ b/noir-projects/aztec-nr/aztec/src/state_vars/public_immutable.nr @@ -0,0 +1,46 @@ +use crate::context::{Context}; +use crate::oracle::storage::storage_read; +use crate::oracle::storage::storage_write; +use dep::std::option::Option; +use dep::protocol_types::traits::{Deserialize, Serialize}; +use crate::state_vars::storage::Storage; + +// docs:start:public_immutable_struct +struct PublicImmutable { + context: Context, + storage_slot: Field, +} +// docs:end:public_immutable_struct + +impl Storage for PublicImmutable {} + +impl PublicImmutable { + // docs:start:public_immutable_struct_new + pub fn new( + // Note: Passing the contexts to new(...) just to have an interface compatible with a Map. + context: Context, + storage_slot: Field + ) -> Self { + assert(storage_slot != 0, "Storage slot 0 not allowed. Storage slots must start from 1."); + PublicImmutable { context, storage_slot } + } + // docs:end:public_immutable_struct_new + + // docs:start:public_immutable_struct_write + pub fn initialize(self, value: T) where T: Serialize { + assert( + self.context.private.is_none(), "PublicImmutable initialization only supported in public functions" + ); + let fields = T::serialize(value); + storage_write(self.storage_slot, fields); + } + // docs:end:public_immutable_struct_write + + // docs:start:public_immutable_struct_read + pub fn read(self) -> T where T: Deserialize { + assert(self.context.private.is_none(), "PublicImmutable reads only supported in public functions"); + let fields = storage_read(self.storage_slot); + T::deserialize(fields) + } + // docs:end:public_immutable_struct_read +}