aztec-nr - noir_aztec::capsules

Struct CapsuleArray

pub struct CapsuleArray<T>
{ /* private fields */ }

A dynamically sized array backed by PXE's non-volatile database (called capsules). Values are persisted until deleted, so they can be e.g. stored during simulation of a transaction and later retrieved during witness generation. All values are scoped per contract address, so external contracts cannot access them.

Implementations

impl<T> CapsuleArray<T>

pub unconstrained fn at(contract_address: AztecAddress, base_slot: Field) -> Self

Returns a CapsuleArray connected to a contract's capsules at a base slot. Array elements are stored in contiguous slots following the base slot, so there should be sufficient space between array base slots to accommodate elements. A reasonable strategy is to make the base slot a hash of a unique value.

pub unconstrained fn len(self) -> u32

Returns the number of elements stored in the array.

pub unconstrained fn push(self, value: T)
where T: Serialize

Stores a value at the end of the array.

pub unconstrained fn get(self, index: u32) -> T
where T: Deserialize

Retrieves the value stored in the array at index. Throws if the index is out of bounds.

pub unconstrained fn remove(self, index: u32)

Deletes the value stored in the array at index. Throws if the index is out of bounds.

pub unconstrained fn for_each<Env>(self, f: unconstrained fn[Env](u32, T))
where T: Deserialize

Calls a function on each element of the array.

The function f is called once with each array value and its corresponding index. The order in which values are processed is arbitrary.

Array Mutation

It is safe to delete the current element (and only the current element) from inside the callback via remove:

array.for_each(|index, value| {
  if some_condition(value) {
    array.remove(index); // safe only for this index
  }
}

If all elements in the array need to iterated over and then removed, then using for_each results in optimal efficiency.

It is not safe to push new elements into the array from inside the callback.