Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support Fixed Size Solidity Arrays in the SDK #20

Merged
merged 12 commits into from
Sep 6, 2023
16 changes: 13 additions & 3 deletions stylus-proc/src/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// For licensing, see https://github.com/OffchainLabs/stylus-sdk-rs/blob/stylus/licenses/COPYRIGHT.md

use lazy_static::lazy_static;
use proc_macro2::Ident;
use proc_macro2::{Ident, Literal};
use quote::quote;
use regex::Regex;
use syn::{
Expand Down Expand Up @@ -110,8 +110,18 @@ impl Parse for SolidityTy {
};

while input.peek(Bracket) {
let _content;
let _ = bracketed!(_content in input); // TODO: fixed arrays
let content;
let _ = bracketed!(content in input);
if let Ok(bracket_contents) = content.parse::<Literal>() {
let size = bracket_contents.to_string().parse::<usize>().map_err(|_| {
Error::new_spanned(&bracket_contents, "Array size must be a positive integer")
})?;
let outer = sdk!("StorageArray");
let inner = quote! { #path };
path = syn::parse_str(&format!("{outer}<{inner}, {size}>"))?;
return Ok(SolidityTy(path));
};

let outer = sdk!("StorageVec");
let inner = quote! { #path };
path = syn::parse_str(&format!("{outer}<{inner}>"))?;
Expand Down
124 changes: 124 additions & 0 deletions stylus-sdk/src/storage/array.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
// Copyright 2023, Offchain Labs, Inc.
// For licensing, see https://github.com/OffchainLabs/stylus-sdk-rs/blob/stylus/licenses/COPYRIGHT.md

use super::{Erase, StorageGuard, StorageGuardMut, StorageType};
use crate::crypto;
use alloy_primitives::U256;
use std::{cell::OnceCell, marker::PhantomData};

/// Accessor for a storage-backed array.
pub struct StorageArray<S: StorageType, const N: usize> {
slot: U256,
base: OnceCell<U256>,
rauljordan marked this conversation as resolved.
Show resolved Hide resolved
marker: PhantomData<S>,
}

impl<S: StorageType, const N: usize> StorageType for StorageArray<S, N> {
type Wraps<'a> = StorageGuard<'a, StorageArray<S, N>> where Self: 'a;
type WrapsMut<'a> = StorageGuardMut<'a, StorageArray<S, N>> where Self: 'a;

const REQUIRED_SLOTS: usize = N * S::REQUIRED_SLOTS;
rauljordan marked this conversation as resolved.
Show resolved Hide resolved

unsafe fn new(slot: U256, offset: u8) -> Self {
debug_assert!(offset == 0);
debug_assert!(N > 0);
rauljordan marked this conversation as resolved.
Show resolved Hide resolved
Self {
slot,
base: OnceCell::new(),
marker: PhantomData,
}
}

fn load<'s>(self) -> Self::Wraps<'s> {
StorageGuard::new(self)
}

fn load_mut<'s>(self) -> Self::WrapsMut<'s> {
StorageGuardMut::new(self)
}
}

impl<S: StorageType, const N: usize> StorageArray<S, N> {
/// Gets an accessor to the element at a given index, if it exists.
/// Note: the accessor is protected by a [`StorageGuard`], which restricts
/// its lifetime to that of `&self`.
pub fn getter(&self, index: impl TryInto<usize>) -> Option<StorageGuard<S>> {
let store = unsafe { self.accessor(index)? };
Some(StorageGuard::new(store))
}

/// Gets a mutable accessor to the element at a given index, if it exists.
/// Note: the accessor is protected by a [`StorageGuardMut`], which restricts
/// its lifetime to that of `&mut self`.
pub fn setter(&mut self, index: impl TryInto<usize>) -> Option<StorageGuardMut<S>> {
let store = unsafe { self.accessor(index)? };
Some(StorageGuardMut::new(store))
}

/// Gets the underlying accessor to the element at a given index, if it exists.
///
/// # Safety
///
/// Enables aliasing.
unsafe fn accessor(&self, index: impl TryInto<usize>) -> Option<S> {
let index = index.try_into().ok()?;
if index >= N {
return None;
}
let (slot, offset) = self.index_slot(index);
Some(S::new(slot, offset))
}

/// Gets the underlying accessor to the element at a given index, even if out of bounds.
///
/// # Safety
///
/// Enables aliasing. UB if out of bounds.
unsafe fn accessor_unchecked(&self, index: usize) -> S {
let (slot, offset) = self.index_slot(index);
S::new(slot, offset)
}

/// Gets the element at the given index, if it exists.
pub fn get(&self, index: impl TryInto<usize>) -> Option<S::Wraps<'_>> {
let store = unsafe { self.accessor(index)? };
Some(store.load())
}

/// Gets a mutable accessor to the element at a given index, if it exists.
pub fn get_mut(&mut self, index: impl TryInto<usize>) -> Option<S::WrapsMut<'_>> {
let store = unsafe { self.accessor(index)? };
Some(store.load_mut())
}

/// Determines the slot and offset for the element at an index.
fn index_slot(&self, index: usize) -> (U256, u8) {
let width = S::SLOT_BYTES;
let words = S::REQUIRED_SLOTS.max(1);
let density = self.density();

let slot = self.base() + U256::from(words * index / density);
rauljordan marked this conversation as resolved.
Show resolved Hide resolved
let offset = 32 - (width * (1 + index % density)) as u8;
(slot, offset)
}

/// Number of elements per slot.
const fn density(&self) -> usize {
32 / S::SLOT_BYTES
}

/// Determines where in storage indices start. Could be made const in the future.
fn base(&self) -> &U256 {
self.base
.get_or_init(|| crypto::keccak(self.slot.to_be_bytes::<32>()).into())
}
}

impl<S: Erase, const N: usize> Erase for StorageArray<S, N> {
fn erase(&mut self) {
for i in 0..N {
let mut store = unsafe { self.accessor_unchecked(i) };
store.erase()
}
}
}
2 changes: 2 additions & 0 deletions stylus-sdk/src/storage/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@
use alloy_primitives::{Address, BlockHash, BlockNumber, FixedBytes, Signed, Uint, U256};
use std::{cell::OnceCell, ops::Deref};

pub use array::StorageArray;
pub use bytes::{StorageBytes, StorageString};
pub use cache::{
Erase, SimpleStorageType, StorageCache, StorageGuard, StorageGuardMut, StorageType,
};
pub use map::StorageMap;
pub use vec::StorageVec;

mod array;
mod bytes;
mod cache;
mod map;
Expand Down