Modules
core
Main entrypoint for the Cairo core library.
Fully qualified path: core
Modules
Free functions
Enums
Type aliases
Extern types
Extern functions
traits
Core traits for various operations.This module provides a collection of essential traits that define common behavior patterns for Cairo types. # Main Categories ## Memory Management - Copy
: Enables value semantics for types - Drop
: Allows values to be safely discarded - Destruct
: Provides custom cleanup behavior for non-droppable types - PanicDestruct
: Handles destruction during panic scenarios ## Arithmetic Operations - Add
, Sub
, Mul
, Div
, Rem
: Standard arithmetic operators (+
, -
, *
, /
, %
) - DivRem
: Combined division and remainder operation - Neg
: Unary negation (-
) ## Bitwise Operations - BitAnd
, BitOr
, BitXor
: Binary bitwise operations (&
, |
, ^
) - BitNot
: Unary bitwise complement (~
) ## Comparison - PartialEq
: Equality comparison (==
, !=
) - PartialOrd
: Ordering comparison (<
, <=
, >
, >=
) ## Type Conversion - Into
: Infallible type conversion - TryInto
: Fallible type conversion ## Utility Traits - Default
: Creation of default values - Felt252DictValue
: Support for dictionary value types
Fully qualified path: core::traits
Traits
boolean
Boolean operations.The bool
type is a primitive type in Cairo representing a boolean value that can be either true
or false
. This module provides trait implementations for boolean operations. # ExamplesBasic boolean operations:
let value = true;
assert!(value == true);
assert!(!value == false);
Converting to optional values with BoolTrait::then_some
:
use core::boolean::BoolTrait;
let bool_value = true;
let result = bool_value.then_some(42_u8);
assert!(result == Some(42));
let bool_value = false;
let result = bool_value.then_some(42_u8);
assert!(result == None);
Fully qualified path: core::boolean
Traits
circuit
Efficient modular arithmetic computations using arithmetic circuits.This module provides a type-safe way to perform modular arithmetic operations using arithmetic circuits. It is particularly useful for implementing cryptographic algorithms and other computations that require efficient modular arithmetic with large numbers. # Core FeaturesModular arithmetic operations (add, subtract, multiply, inverse) - Support for numbers up to 384 bits - Type-safe circuit construction - Efficient evaluation of complex expressions # Examples ## Basic ArithmeticHere's an example showing basic modular arithmetic operations:
use core::circuit::{
CircuitElement, EvalCircuitTrait, CircuitOutputsTrait, CircuitInput, CircuitModulus,
AddInputResultTrait, CircuitInputs, circuit_add, circuit_mul,
};
// Compute (a + b) * c mod p
let a = CircuitElement::<CircuitInput<0>> {};
let b = CircuitElement::<CircuitInput<1>> {};
let c = CircuitElement::<CircuitInput<2>> {};
let sum = circuit_add(a, b);
let result = circuit_mul(sum, c);
// Evaluate with inputs [3, 6, 2] modulo 7
let modulus = TryInto::<_, CircuitModulus>::try_into([7, 0, 0, 0]).unwrap();
let outputs = (result,)
.new_inputs()
.next([3, 0, 0, 0])
.next([6, 0, 0, 0])
.next([2, 0, 0, 0])
.done()
.eval(modulus)
.unwrap();
// Result: (3 + 6) * 2 mod 7 = 4
assert!(outputs.get_output(result) == 4.into());
How It WorksThe module uses a type-based approach to construct and evaluate arithmetic circuits:Circuit elements are created using CircuitElement<T>
where T defines their role (input or gate) 2. Basic operations combine elements into more complex expressions (chaining gates to create a circuit) 3. The final circuit is evaluated with specific input values and a modulusOperations are performed using a multi-limb representation for large numbers, with each number represented as four 96-bit limbs allowing for values up to 384 bits. # Performance ConsiderationsCircuit evaluation is optimized for large modular arithmetic operations - The multi-limb representation allows efficient handling of large numbers - Circuit construction has zero runtime overhead due to type-based approach # ErrorsCircuit evaluation can fail in certain cases: - When computing multiplicative inverses of non-invertible elements - When the modulus is 0 or 1 In that case the evaluation will return an Error.
Fully qualified path: core::circuit
Free functions
Structs
Enums
Type aliases
Traits
Impls
Extern types
blake
Fully qualified path: core::blake
Extern functions
box
Box<T>
is a smart pointer that allows for:Storing values of arbitrary size while maintaining a fixed-size pointer * Enabling recursive types that would otherwise have infinite size * Moving large data structures efficiently by passing pointers instead of copying values # ExamplesCreating a new box with BoxTrait::new
:
let boxed = BoxTrait::new(42);
let unboxed = boxed.unbox();
Working with larger structures:
let large_array = array![1, 2, 3, 4, 5];
let boxed_array = BoxTrait::new(large_array);
Creating a recursive data structure:
[derive(Copy, Drop, Debug)]
enum BinaryTree {
Leaf: u32,
Node: (u32, Box<BinaryTree>, Box<BinaryTree>)
}
let leaf = BinaryTree::Leaf(1);
let node = BinaryTree::Node((2, BoxTrait::new(leaf), BoxTrait::new(leaf)));
println!("{:?}", node);
NOTE: A Box<T>
is a smart pointer type that provides a way to store a value of type T
in Cairo VM's boxed segment, leaving only a pointer in the execution segment.
Fully qualified path: core::box
Traits
Extern types
nullable
A wrapper type for handling optional values.Nullable<T>
is a wrapper type that can either contain a value stored in a Box<T>
or be null. It provides a safe way to handle optional values without the risk of dereferencing null pointers.This makes it particularly useful in dictionaries that store complex data structures that don't implement the Felt252DictValue
trait; instead, they can be wrapped inside a Nullable
. # ExamplesBasic usage:
let value: Nullable<u32> = NullableTrait::new(10);
let unwrapped_value = value.deref();
Handling null values:
let null_value: Nullable<u32> = Default::default();
let unwrapped_value = null_value.deref_or(1);
Checking if the value is null:
let value: Nullable<u32> = NullableTrait::new(10);
let is_null = if value.is_null() {
// Handle null case
} else {
// Handle non-null case
};
Fully qualified path: core::nullable
Enums
Traits
Extern types
Extern functions
array
A contiguous collection of elements of the same type in memory, written Array<T>
.Arrays have O(1) indexing, O(1) push and O(1) pop (from the front).Arrays can only be mutated by appending to the end or popping from the front. # ExamplesYou can explicitly create an Array
with ArrayTrait::new
:
let arr: Array<usize> = ArrayTrait::new();
...or by using the array!
macro:
let arr: Array<usize> = array![];
let arr: Array<usize> = array![1, 2, 3, 4, 5];
You can append
values onto the end of an array:
let mut arr = array![1, 2];
arr.append(3);
Popping values from the front works like this:
let mut arr = array![1, 2];
let one = arr.pop_front(); // Returns Some(1)
Arrays support indexing (through the IndexView
trait):
let arr = array![1, 2, 3];
let three = arr[2]; // Returns a snapshot (@T)
Arrays can be converted to Span
s for read-only access:
let arr = array![1, 2, 3];
let span = arr.span();
A span can be manipulated without affecting the original array:
let mut arr = array![1, 2, 3];
let mut span = arr.span();
span.pop_back();
assert!(arr == array![1, 2, 3]);
Fully qualified path: core::array
Structs
Traits
Impls
Extern types
dict
A dictionary-like data structure that maps felt252
keys to values of any type.The Felt252Dict
provides efficient key-value storage with operations for inserting, retrieving, and updating values. Each operation creates a new entry that can be validated through a process called squashing. # ExamplesOne can create a new dictionary using the Default::default
method:
use core::dict::Felt252Dict;
let mut dict: Felt252Dict<u8> = Default::default();
... then insert new values corresponding to a given key with the Felt252DictTrait::insert
method, and retrieve any value given a key with the Felt252DictTrait::get
method.
dict.insert(0, 10);
dict.insert(1, 20);
assert!(dict.get(0) == 10);
assert!(dict.get(1) == 20);
dict.insert(0, 20);
assert!(dict.get(0) == 20);
It is also possible to use the Felt252DictTrait::entry
method to retrieve the last entry given a certain key. In this case, the method takes ownership of the dictionary and returns the entry to update. After that, using the Felt252DictEntryTrait::finalize
allows to create a new entry in the dictionary. Using entry
and finalize
methods can be very useful given that it does not require the type in the dictionary to be copyable, meaning that we can use non-copyable types like arrays as dictionary values.
use core::dict::Felt252Dict;
let mut dict: Felt252Dict<u8> = Default::default();
dict.insert(0, 10);
let (entry, prev_value) = dict.entry(0);
let new_value: u8 = 20;
dict = entry.finalize(new_value);
Fully qualified path: core::dict
Traits
Extern types
result
Error handling with the Result
type.Result
is the type used for returning and propagating errors. It is an enum with the variants, Ok(T)
, representing success and containing a value, and Err(E)
, representing error and containing an error value.
enum Result<T, E> {
Ok: T,
Err: E,
}
Functions return Result
whenever errors are expected and recoverable.A simple function returning Result
might be defined and used like so:
fn parse_version(header: felt252) -> Result<felt252, felt252> {
match header {
0 => Ok(0),
1 => Ok(1),
_ => Err('invalid version'),
}
}
let version = parse_version(1);
match version {
Ok(v) => println!("working with version {}", v),
Err(e) => println!("error parsing version: {:?}", e)
}
Results must be usedA common problem with using return values to indicate errors is that it is easy to ignore the return value, thus failing to handle the error. Result
is annotated with the #[must_use]
attribute, which will cause the compiler to issue a warning when a Result value is ignored. # Method overviewIn addition to working with pattern matching, Result
provides a wide variety of different methods. ## Querying the variantThe is_ok
and is_err
methods return true
if the Result
is Ok
or Err
, respectively. ## Extracting contained valuesThese methods extract the contained value in a [Result<T, E>
](Result<T, E>
) when it is the Ok
variant. If the Result
is Err
:expect
panics with a provided felt252 error message * unwrap
panics with a generic message * unwrap_or
returns the provided default value * unwrap_or_default
returns the default value of the type T
(which must implement the Default
trait) * unwrap_or_else
returns the result of evaluating the provided functionexpect
: ResultTrait::expect unwrap
: ResultTrait::unwrap unwrap_or
: ResultTrait::unwrap_or unwrap_or_default
: ResultTrait::unwrap_or_default unwrap_or_else
: ResultTrait::unwrap_or_elseThese methods extract the contained value in a [Result<T, E>
](Result<T, E>
) when it is the Err
variant. If the Result
is Ok
:expect_err
panics with a provided felt252 error message * unwrap_err
panics with a generic messageexpect_err
: ResultTrait::expect_err unwrap_err
: ResultTrait::unwrap_err ## Transforming contained valuesThese methods transform Result
to Option
:ok
transforms [Result<T, E>
](Result<T, E>
) into Option<T>
, mapping Ok(v)
to Some(v)
and Err(e)
to None
* err
transforms [Result<T, E>
](Result<T, E>
) into Option<E>
, mapping Ok(v)
to None
and Err(e)
to Some(e)
This method transforms the contained value of the Ok
variant:map
transforms [Result<T, E>
](Result<T, E>
) into [Result<U, E>
](Result<U, E>
) by applying the provided function to the contained value of Ok
and leaving Err
values unchangedThis method transforms the contained value of the Err
variant:map_err
transforms [Result<T, E>
](Result<T, E>
) into [Result<T, F>
](Result<T, F>
) by applying the provided function to the contained value of Err
and leaving Ok
values unchangedThese methods transform a [Result<T, E>
](Result<T, E>
) into a value of a possibly different type U
:map_or
applies the provided function to the contained value of Ok
, or returns the provided default value if the Result
is Err
* map_or_else
applies the provided function to the contained value of Ok
, or applies the provided default fallback function to the contained value of Err
map_or
: ResultTrait::map_or map_or_else
: ResultTrait::map_or_else ## Boolean operatorsThese methods treat the Result
as a boolean value, where Ok
acts like true
and Err
acts like false
. There are two categories of these methods: ones that take a Result
as input, and ones that take a function as input.The and
and or
methods take another Result
as input, and produce a Result
as output. The and
method can produce a [Result<U, E>
](Result<U, E>
) value having a different inner type U
than [Result<T, E>
](Result<T, E>
). The or
method can produce a [Result<T, F>
](Result<T, F>
) value having a different error type F
than [Result<T, E>
](Result<T, E>
).| method | self | input | output | |---------|----------|-----------|----------| | and
| Err(e)
| (ignored) | Err(e)
| | and
| Ok(x)
| Err(d)
| Err(d)
| | and
| Ok(x)
| Ok(y)
| Ok(y)
| | or
| Err(e)
| Err(d)
| Err(d)
| | or
| Err(e)
| Ok(y)
| Ok(y)
| | or
| Ok(x)
| (ignored) | Ok(x)
|and
: ResultTrait::and or
: ResultTrait::orThe and_then
and or_else
methods take a function as input, and only evaluate the function when they need to produce a new value. The and_then
method can produce a [Result<U, E>
](Result<U, E>
) value having a different inner type U
than [Result<T, E>
](Result<T, E>
). The or_else
method can produce a [Result<T, F>
](Result<T, F>
) value having a different error type F
than [Result<T, E>
](Result<T, E>
).| method | self | function input | function result | output | |--------------|----------|----------------|-----------------|----------| | and_then
| Err(e)
| (not provided) | (not evaluated) | Err(e)
| | and_then
| Ok(x)
| x
| Err(d)
| Err(d)
| | and_then
| Ok(x)
| x
| Ok(y)
| Ok(y)
| | or_else
| Err(e)
| e
| Err(d)
| Err(d)
| | or_else
| Err(e)
| e
| Ok(y)
| Ok(y)
| | or_else
| Ok(x)
| (not provided) | (not evaluated) | Ok(x)
|and_then
: ResultTrait::and_then or_else
: ResultTrait::or_else # The question mark operator, ?
When writing code that calls many functions that return the Result
type, handling Ok
/Err
can be tedious. The question mark operator, ?
, hides some of the boilerplate of propagating errors up the call stack.It replaces this:
use core::integer::u8_overflowing_add;
fn add_three_numbers(a: u8, b: u8, c: u8) -> Result<u8, u8> {
match u8_overflowing_add(a, b) {
Ok(sum_ab) => {
match u8_overflowing_add(sum_ab, c) {
Ok(total) => Ok(total),
Err(e) => Err(e),
}
},
Err(e) => Err(e),
}
}
With this:
use core::integer::u8_overflowing_add;
fn add_three_numbers_2(a: u8, b: u8, c: u8) -> Result<u8, u8> {
let total = u8_overflowing_add(u8_overflowing_add(a, b)?, c)?;
Ok(total)
}
It's much nicer: Ok
Err
: Err ## Iterating over Result
A Result
can be iterated over. This can be helpful if you need an iterator that is conditionally empty. The iterator will either produce a single value (when the Result
is Ok
), or produce no values (when the Result
is Err
). For example, into_iter
contains Some(v)
if the Result
is Ok(v)
, and None
if the Result
is Err
.
Fully qualified path: core::result
Enums
Traits
option
Optional values.The Option
type represents an optional value: every Option
is either Some
and contains a value, or None
, and does not. Option
types are very common in Cairo code, as they have a number of uses:Initial values * Return values for functions that are not defined over their entire input range (partial functions) * Return value for otherwise reporting simple errors, where None
is returned on error * Optional struct fields * Optional function argumentsOptions are commonly paired with pattern matching to query the presence of a value and take action, always accounting for the None
case.
fn divide(numerator: u64, denominator: u64) -> Option<u64> {
if denominator == 0 {
None
} else {
Some(numerator / denominator)
}
}
// The return value of the function is an option
let result = divide(2, 3);
// Pattern match to retrieve the value
match result {
// The division was valid
Some(x) => println!("Result: {x}"),
// The division was invalid
None => println!("Cannot divide by 0"),
}
The question mark operator, ?
Similar to the Result
type, when writing code that calls many functions that return the Option
type, handling Some
/None
can be tedious. The question mark operator, ?
, hides some of the boilerplate of propagating values up the call stack.It replaces this:
fn add_last_numbers(mut array: Array<u32>) -> Option<u32> {
let a = array.pop_front();
let b = array.pop_front();
match (a, b) {
(Some(x), Some(y)) => Some(x + y),
_ => None,
}
}
With this:
fn add_last_numbers(mut array: Array<u32>) -> Option<u32> {
Some(array.pop_front()? + array.pop_front()?)
}
It's much nicer!Ending the expression with ?
will result in the Some
's unwrapped value, unless the result is None
, in which case None
is returned early from the enclosing function. ?
can be used in functions that return Option
because of the early return of None
that it provides.Some
: Some None
: None # Method overviewIn addition to working with pattern matching, Option
provides a wide variety of different methods. ## Querying the variantThe is_some
and is_none
methods return true
if the Option
is Some
or None
, respectively.is_none
: OptionTrait::is_none is_none_or
: OptionTrait::is_none_or is_some
: OptionTrait::is_some is_some_and
: OptionTrait::is_some_and ## Extracting the contained valueThese methods extract the contained value in an Option<T>
when it is the Some
variant. If the Option
is None
:expect
panics with a provided custom message * unwrap
panics with a generic message * unwrap_or
returns the provided default value * unwrap_or_default
returns the default value of the type T
(which must implement the Default
trait) * unwrap_or_else
returns the result of evaluating the provided functionexpect
: OptionTrait::expect unwrap
: OptionTrait::unwrap unwrap_or
: OptionTrait::unwrap_or unwrap_or_default
: OptionTrait::unwrap_or_default unwrap_or_else
: OptionTrait::unwrap_or_else ## Transforming contained valuesThese methods transform Option
to Result
:ok_or
transforms Some(v)
to Ok(v)
, and None
to Err(err)
using the provided default err
value. * ok_or_else
transforms Some(v)
to Ok(v)
, and None
to a value of Err
using the provided functionErr(err)
: Err Ok(v)
: Ok Some(v)
: Some ok_or
: OptionTrait::ok_or ok_or_else
: OptionTrait::ok_or_elseThese methods transform the Some
variant:map
transforms Option<T>
to Option<U>
by applying the provided function to the contained value of Some
and leaving None
values unchangedThese methods transform Option<T>
to a value of a possibly different type U
:map_or
applies the provided function to the contained value of Some
, or returns the provided default value if the Option
is None
* map_or_else
applies the provided function to the contained value of Some
, or returns the result of evaluating the provided fallback function if the Option
is None
map_or
: OptionTrait::map_or map_or_else
: OptionTrait::map_or_else ## Boolean operatorsThese methods treat the Option
as a boolean value, where Some
acts like true
and None
acts like false
. There are two categories of these methods: ones that take an Option
as input, and ones that take a function as input (to be lazily evaluated).The and
, or
, and xor
methods take another Option
as input, and produce an Option
as output. Only the and
method can produce an Option<U>
value having a different inner type U
than Option<T>
.| method | self | input | output | |---------|-----------|-----------|-----------| | and
| None
| (ignored) | None
| | and
| Some(x)
| None
| None
| | and
| Some(x)
| Some(y)
| Some(y)
| | or
| None
| None
| None
| | or
| None
| Some(y)
| Some(y)
| | or
| Some(x)
| (ignored) | Some(x)
| | xor
| None
| None
| None
| | xor
| None
| Some(y)
| Some(y)
| | xor
| Some(x)
| None
| Some(x)
| | xor
| Some(x)
| Some(y)
| None
|and
: OptionTrait::and or
: OptionTrait::or xor
: OptionTrait::xorThe and_then
and or_else
methods take a function as input, and only evaluate the function when they need to produce a new value. Only the and_then
method can produce an Option<U>
value having a different inner type U
than Option<T>
.| method | self | function input | function result | output | |--------------|-----------|----------------|-----------------|-----------| | and_then
| None
| (not provided) | (not evaluated) | None
| | and_then
| Some(x)
| x
| None
| None
| | and_then
| Some(x)
| x
| Some(y)
| Some(y)
| | or_else
| None
| (not provided) | None
| None
| | or_else
| None
| (not provided) | Some(y)
| Some(y)
| | or_else
| Some(x)
| (not provided) | (not evaluated) | Some(x)
|and_then
: OptionTrait::and_then or_else
: OptionTrait::or_else ## Iterating over Option
An Option
can be iterated over. This can be helpful if you need an iterator that is conditionally empty. The iterator will either produce a single value (when the Option
is Some
), or produce no values (when the Option
is None
). For example, into_iter
contains Some(v)
if the Option
is Some(v)
, and None
if the Option
is None
.
Fully qualified path: core::option
Structs
Enums
Traits
Impls
clone
The Clone
trait provides the ability to duplicate instances of types that cannot be 'implicitly copied'.In Cairo, some simple types are "implicitly copyable": when you assign them or pass them as arguments, the receiver will get a copy, leaving the original value in place. These types do not require allocation to copy, and are not at risk of accessing un-allocated memory, so the compiler considers them cheap and safe to copy. For other types, copies must be made explicitly, by convention implementing the Clone
trait and calling the Clone::clone
method. # Examples
let arr = array![1, 2, 3];
let cloned_arr = arr.clone();
assert!(arr == cloned_arr);
You can use the #[derive(Clone)]
attribute to automatically generate the implementation for your type:
[derive(Clone, Drop)]
struct Sheep {
name: ByteArray,
age: u8,
}
fn main() {
let dolly = Sheep {
name: "Dolly",
age: 6,
};
let cloned_sheep = dolly.clone(); // Famous cloned sheep!
}
Fully qualified path: core::clone
Traits
ec
Functions and constructs related to elliptic curve operations on the STARK curve.This module provides implementations for various elliptic curve operations tailored for the STARK curve.Curve information: * Curve equation: y² ≡ x³ + α·x + β (mod p) * α = 1 * β = 0x6f21413efbe40de150e596d72f7a8c5609ad26c15c915c1f4cdfcb99cee9e89 * p = 0x0800000000000011000000000000000000000000000000000000000000000001 = 2^251 + 17 * 2^192 + 1 Generator point: * x = 0x1ef15c18599971b7beced415a40f0c7deacfd9b0d1819e03d723d8bc943cfca * y = 0x5668060aa49730b7be4801df46ec62de53ecd11abe43a32873000c36e8dc1f # ExamplesCreating points and basic operations:
// Create a point from coordinates
let point = EcPointTrait::new(
x: 336742005567258698661916498343089167447076063081786685068305785816009957563,
y: 1706004133033694959518200210163451614294041810778629639790706933324248611779,
).unwrap();
// Perform scalar multiplication
let result = point.mul(2);
// Add points
let sum = point + result;
// Subtract points
let diff = result - point;
Using EC state for batch operations:
let p = EcPointTrait::new_from_x(1).unwrap();
let p_nz = p.try_into().unwrap();
// Initialize state
let mut state = EcStateTrait::init();
// Add points and scalar multiplications
state.add(p_nz);
state.add_mul(1, p_nz);
// Get the final result
let _result = state.finalize();
Fully qualified path: core::ec
Modules
Type aliases
Traits
Impls
Extern types
Extern functions
ecdsa
Elliptic Curve Digital Signature Algorithm (ECDSA) for the STARK curve.This module provides implementations for ECDSA signature verification and public key recovery specifically tailored for the STARK curve.Curve information: * Curve equation: y² ≡ x³ + α·x + β (mod p) * α = 1 * β = 0x6f21413efbe40de150e596d72f7a8c5609ad26c15c915c1f4cdfcb99cee9e89 * p = 0x0800000000000011000000000000000000000000000000000000000000000001 = 2^251 + 17 * 2^192 + 1 Generator point: * x = 0x1ef15c18599971b7beced415a40f0c7deacfd9b0d1819e03d723d8bc943cfca * y = 0x5668060aa49730b7be4801df46ec62de53ecd11abe43a32873000c36e8dc1f
Fully qualified path: core::ecdsa
Free functions
integer
Integer types and operations.This module provides the built-in integer types and their associated operations. # Integer TypesThe following integer types are available:Unsigned integers: u8
, u16
, u32
, u64
, u128
, u256
* Signed integers: i8
, i16
, i32
, i64
, i128
# OperationsInteger types implement various traits that enable common operations:Basic arithmetic via Add
, Sub
, Mul
, Div
, Rem
and DivRem
* Bitwise operations via BitAnd
, BitOr
, BitXor
, and BitNot
* Comparison via PartialEq
and PartialOrd
* Safe arithmetic via CheckedAdd
, CheckedSub
, CheckedMul
* Wrapping arithmetic via WrappingAdd
, WrappingSub
, WrappingMul
* Overflow handling via OverflowingAdd
, OverflowingSub
, OverflowingMul
Add
: crate::traits::Add Sub
: crate::traits::Sub Mul
: crate::traits::Mul Div
: crate::traits::Div Rem
: crate::traits::Rem DivRem
: crate::traits::DivRem CheckedAdd
: crate::num::traits::ops::checked::CheckedAdd CheckedSub
: crate::num::traits::ops::checked::CheckedSub CheckedMul
: crate::num::traits::ops::checked::CheckedMul WrappingAdd
: crate::num::traits::ops::wrapping::WrappingAdd WrappingSub
: crate::num::traits::ops::wrapping::WrappingSub WrappingMul
: crate::num::traits::ops::wrapping::WrappingMul OverflowingAdd
: crate::num::traits::ops::overflowing::OverflowingAdd OverflowingSub
: crate::num::traits::ops::overflowing::OverflowingSub OverflowingMul
: crate::num::traits::ops::overflowing::OverflowingMul # ExamplesBasic operators:
let a: u8 = 5;
let b: u8 = 10;
assert_eq!(a + b, 15);
assert_eq!(a * b, 50);
assert_eq!(a & b, 0);
assert!(a < b);
Checked operations:
use core::num::traits::{CheckedAdd, Bounded};
let max: u8 = Bounded::MAX;
assert!(max.checked_add(1_u8).is_none());
ConversionsIntegers can be converted between different types using:TryInto
for potentially fallible conversions * Into
for infallible conversions to wider types
Fully qualified path: core::integer
Free functions
Structs
Traits
Extern types
Extern functions
cmp
Utilities for comparing and ordering values. This module contains functions that rely on the PartialOrd
trait for comparing values. # Examples
use core::cmp::{min, max, minmax};
assert!(min(10, 20) == 10);
assert!(max(10, 20) == 20);
assert!(minmax(20, 10) == (10, 20));
assert!(minmax(10, 20) == (10, 20));
Fully qualified path: core::cmp
Free functions
gas
Utilities for handling gas in Cairo code.
Fully qualified path: core::gas
Extern types
Extern functions
math
Mathematical operations and utilities.Provides extended GCD, modular inverse, and modular arithmetic operations.
Fully qualified path: core::math
Free functions
num
Fully qualified path: core::num
Modules
ops
Overloadable operators.Implementing these traits allows you to overload certain operators.Note: Other overloadable operators are also defined in the core::traits
module.Only operators backed by traits can be overloaded. For example, the addition assignment operator (+=
) can be overloaded through the AddAssign
trait, but since the assignment operator (=
) has no backing trait, there is no way of overloading its semantics. Additionally, this module does not provide any mechanism to create new operators.Implementations of operator traits should be unsurprising in their respective contexts, keeping in mind their usual meanings and operator precedence. For example, when implementing MulAssign
, the operation should have some resemblance to multiplication assignment. # ExamplesThis example creates a Point
struct that implements AddAssign
and SubAssign
, and then demonstrates adding and subtracting two Point
s to themselves.
use core::ops::{AddAssign, SubAssign};
[derive(Debug, Drop, Copy, PartialEq)]
struct Point {
x: i32,
y: i32,
}
impl AddAssignImpl of AddAssign<Point, Point> {
fn add_assign(ref self: Point, rhs: Point) {
self = Point { x: self.x + rhs.x, y: self.y + rhs.y }
}
}
impl SubAssignImpl of SubAssign<Point, Point> {
fn sub_assign(ref self: Point, rhs: Point) {
self = Point { x: self.x - rhs.x, y: self.y - rhs.y }
}
}
fn main() {
let mut point = Point {x : 3, y: 4};
point += point;
assert!(point == Point {x: 6, y: 8});
point -= point;
assert!(point == Point {x: 0, y: 0});
}
See the documentation for each trait for an example implementation.
Fully qualified path: core::ops
Modules
Structs
Traits
panics
Core panic mechanism.This module provides the core panic functionality used for error handling in Cairo. It defines the basic types and functions used to trigger and manage panics, which are Cairo's mechanism for handling unrecoverable errors.Panics can be triggered in several ways:Using the panic
function:
use core::panics::panic;
panic(array!['An error occurred']);
Or using the panic!
macro:
panic!("Panic message");
This macro internally converts the message into a ByteArray
and uses panic_with_byte_array
.
Fully qualified path: core::panics
Free functions
Structs
Enums
Extern functions
hash
Generic hashing support.This module provides a hash state abstraction that can be updated with values and finalized to produce a hash. This allows for flexible and efficient hashing of any type with different hash functions.The simplest way to make a type hashable is to use #[derive(Hash)]
. Hashing a value is done by initiating a HashState
corresponding to a hash function, updating it with the value, and then finalizing it to get the hash result. # ExamplesBasic usage with Pedersen and Poseidon hash:
use core::pedersen::PedersenTrait;
use core::poseidon::PoseidonTrait;
[derive(Copy, Drop, Hash)]
struct Person {
id: u32,
phone: u64,
}
fn main() {
let person1 = Person { id: 1, phone: 555_666_7777 };
let person2 = Person { id: 2, phone: 555_666_7778 };
assert!(
PedersenTrait::new(0)
.update_with(person1)
.finalize() != PedersenTrait::new(0)
.update_with(person2)
.finalize(),
);
assert!(
PoseidonTrait::new()
.update_with(person1)
.finalize() != PoseidonTrait::new()
.update_with(person2)
.finalize(),
);
}
Fully qualified path: core::hash
Modules
Traits
keccak
Keccak-256 cryptographic hash function implementation. # Main Functionskeccak_u256s_le_inputs
- Hash multiple u256
values in little-endian format - keccak_u256s_be_inputs
- Hash multiple u256
values in big-endian format - cairo_keccak
- Hash u64 words with a final partial word. Closest to the syscall input. - compute_keccak_byte_array
- Hash a ByteArray
directly # Examples
use core::keccak::*;
// Hash u256 values
let input = array![1_u256, 2_u256].span();
assert!(keccak_u256s_le_inputs(input) ==
0x234a9e12e9b063b60f7e3289ee9b86a731de8e7e41bd4987f10982d6a753444d);
assert!(keccak_u256s_be_inputs(input) ==
0xe0c2a7d2cc99d544061ac0ccbb083ac8976e54eed878fb1854dfe7b6ce7b0be9);
// Hash a `Bytearray`
let text: ByteArray = "Hello, Keccak!";
assert!(compute_keccak_byte_array(@text) ==
0x85c9aab73219c1e95c5b5966a4ecc8db4418c3500072a830cfb5a2d13d2c2249);
Fully qualified path: core::keccak
Free functions
pedersen
Pedersen hash related traits implementations.This module provides an implementation of the Pedersen hash function, which is a collision-resistant cryptographic hash function.The HashState
struct represents the state of a Pedersen hash computation. It contains a single felt252
field state
that holds the current hash value.The PedersenTrait
provides a new
method to create a new HashState
from a base value.The HashStateTrait
defined in the Hash module provides the update
and finalize
methods to update the hash state and obtain the final hash value, respectively. # Examples
use core::hash::HashStateTrait;
use core::pedersen::PedersenTrait;
let mut state = PedersenTrait::new(0);
state = state.update(1);
state = state.update(2);
let hash = state.finalize();
assert!(hash == 0x07546be9ecb576c12cd00962356afd90b615d8ef50605bc13badfd1fd218c0d5);
Fully qualified path: core::pedersen
Structs
Traits
Impls
Extern types
Extern functions
serde
Serialization and deserialization of data structures.This module provides traits and implementations for converting Cairo types into a sequence of felt252
values (serialization) and back (deserialization).When passing values between Cairo and an external environment, serialization and deserialization are necessary to convert Cairo's data types into a sequence of felt252
values, as felt252
is the fundamental type of the language. # The Serde
TraitAll types that need to be serialized must implement the Serde
trait. This includes both simple types that serialize to a single felt252
and compound types (like u256
) that require multiple felt252
values.
Fully qualified path: core::serde
Modules
Traits
sha256
Implementation of the SHA-256 cryptographic hash function.This module provides functions to compute SHA-256 hashes of data. The input data can be an array of 32-bit words, or a ByteArray
. # Examples
use core::sha256::compute_sha256_byte_array;
let data = "Hello";
let hash = compute_sha256_byte_array(@data);
assert!(hash == [0x185f8db3, 0x2271fe25, 0xf561a6fc, 0x938b2e26, 0x4306ec30, 0x4eda5180,
0x7d17648, 0x26381969]);
Fully qualified path: core::sha256
Free functions
poseidon
Poseidon hash related traits implementations and functions.This module provides cryptographic hash functions based on the Poseidon permutation.The Poseidon hash function is an arithmetic-friendly hash function optimized for use in zero-knowledge proof systems. This module implements the Poseidon hash using a sponge construction for arbitrary-length inputs. # Examples
use core::hash::HashStateTrait;
use core::poseidon::PoseidonTrait;
// Create a new hash state
let mut state = PoseidonTrait::new();
// Update with values
state = state.update(1);
state = state.update(2);
// Finalize to get the hash
let hash = state.finalize();
Fully qualified path: core::poseidon
Free functions
Structs
Traits
Impls
Extern types
Extern functions
debug
Utilities related to printing of values at runtime. The recommended way of printing values is by using the Display
and Debug
traits available in the fmt
module. The items in this module are not public, and are not recommended for use.
Fully qualified path: core::debug
Free functions
fmt
Functionality for formatting values.The main components of this module are:Error
: A type representing formatting errors. - Formatter
: A struct that holds the configuration and buffer for formatting. - Display
: A trait for standard formatting using the empty format ("{}"). - Debug
: A trait for debug formatting using the empty format ("{:?}"). - LowerHex
: A trait for hex formatting in lower case.The module includes implementations of the Display
, Debug
and LowerHex
traits for various types.
Fully qualified path: core::fmt
Modules
Structs
Traits
starknet
Functionalities for interacting with the Starknet network. # Core ComponentsStorage: The storage
module defines abstractions on how to interact with Starknet contract storage. - Syscalls: The syscalls
module contains the extern declarations for all the system calls available in Starknet. - Contract Addresses: The contract_address
and eth_address
modules provide types and utilities for working with Starknet contract addresses and Ethereum addresses. - Cryptography: The secp256k1
, secp256r1
, secp256_trait
, and eth_signature
modules handle various elliptic curve operations. - Execution Info: The info
module exposes functions for accessing information about the current contract execution, such as the caller address, contract address, block info, and transaction info.
Fully qualified path: core::starknet
Modules
Constants
Free functions
Structs
Type aliases
Traits
Extern types
Extern functions
internal
Fully qualified path: core::internal
Structs
Enums
Extern functions
zeroable
Types and traits for handling non-zero values and zero checking operations.This module provides the NonZero
wrapper type which guarantees that a value is never zero. The Zeroable
trait is meant for internal use only. The public-facing equivalent is the Zero
trait.
Fully qualified path: core::zeroable
Extern types
bytes_31
Definitions and utilities for the bytes31
type.The bytes31
type is a compact, indexable 31-byte type. # ExamplesCreating a bytes31
from a felt252
:
let value: bytes31 = 0xaabb.try_into().unwrap();
Accessing a byte by index:
assert!(value[0] == 0xbb);
Fully qualified path: core::bytes_31
Traits
Impls
Extern types
byte_array
ByteArray
is designed to handle large sequences of bytes with operations like appending, concatenation, and accessing individual bytes. It uses a structure that combines an Array
of bytes31
for full words and a felt252
for handling partial words, optimizing for both space and performance. # ExamplesThere are multiple ways to create a new ByteArray
: - From a string literal:
let s = "Hello";
Using the format!
macro:
let max_tps:u16 = 850;
let s = format!("Starknet's max TPS is: {}", max_tps);
You can append bytes to an existing ByteArray
with ByteArrayTrait::append_byte
:
let mut ba: ByteArray = "";
ba.append_byte(0x41); // Appending a single byte 'A'
You can create a new ByteArray
from an existing one by concatenating with +
:
let s = "Hello";
let message = s + " world!";
Indexing operations are available on the ByteArray
type as well:
let mut ba: ByteArray = "ABC";
let first_byte = ba[0]
assert!(first_byte == 0x41);
Fully qualified path: core::byte_array
Constants
Structs
Traits
Impls
string
Fully qualified path: core::string
Traits
iter
Composable external iteration.If you've found yourself with a collection of some kind, and needed to perform an operation on the elements of said collection, you'll quickly run into 'iterators'. Iterators are heavily used in idiomatic code, so it's worth becoming familiar with them.Before explaining more, let's talk about how this module is structured: # OrganizationThis module is largely organized by type:Traits are the core portion: these traits define what kind of iterators exist and what you can do with them. The methods of these traits are worth putting some extra study time into. * Functions provide some helpful ways to create some basic iterators. * Structs are often the return types of the various methods on this module's traits. You'll usually want to look at the method that creates the struct
, rather than the struct
itself. For more detail about why, see 'Implementing Iterator'.Traits: #traits Functions: #functions Structs: #structsThat's it! Let's dig into iterators. # IteratorThe heart and soul of this module is the Iterator
trait. The core of Iterator
looks like this:
trait Iterator {
type Item;
fn next(ref self) -> Option<Self::Item>;
}
An iterator has a method, next
, which when called, returns an Optionnext
will return Some(Item)
as long as there are elements, and once they've all been exhausted, will return None
to indicate that iteration is finished.Iterator
's full definition includes a number of other methods as well, but they are default methods, built on top of next
, and so you get them for free.Iterators are also composable, and it's common to chain them together to do more complex forms of processing. See the Adapters section below for more details.Some(Item)
: Some next
: Iterator::next # Forms of iterationThere is currently only one common method which can create iterators from a collection:into_iter()
, which iterates over T
. # Implementing IteratorCreating an iterator of your own involves two steps: creating a struct
to hold the iterator's state, and then implementing Iterator
for that struct
. This is why there are so many struct
s in this module: there is one for each iterator and iterator adapter.Let's make an iterator named Counter
which counts from 1
to 5
:
// First, the struct:
/// An iterator which counts from one to five
[derive(Drop)]
struct Counter {
count: usize,
}
// we want our count to start at one, so let's add a new() method to help.
// This isn't strictly necessary, but is convenient. Note that we start
// `count` at zero, we'll see why in `next()`'s implementation below.
[generate_trait]
impl CounterImpl of CounterTrait {
fn new() -> Counter {
Counter { count: 0 }
}
}
// Then, we implement `Iterator` for our `Counter`:
impl CounterIter of core::iter::Iterator<Counter> {
// we will be counting with usize
type Item = usize;
// next() is the only required method
fn next(ref self: Counter) -> Option<Self::Item> {
// Increment our count. This is why we started at zero.
self.count += 1;
// Check to see if we've finished counting or not.
if self.count < 6 {
Some(self.count)
} else {
None
}
}
}
// And now we can use it!
let mut counter = CounterTrait::new();
assert!(counter.next() == Some(1));
assert!(counter.next() == Some(2));
assert!(counter.next() == Some(3));
assert!(counter.next() == Some(4));
assert!(counter.next() == Some(5));
assert!(counter.next() == None);
Calling next
this way gets repetitive. Cairo has a construct which can call next
on your iterator, until it reaches None
. Let's go over that next. # for
loops and IntoIterator
Cairo's for
loop syntax is actually sugar for iterators. Here's a basic example of for
:
let values = array![1, 2, 3, 4, 5];
for x in values {
println!("{x}");
}
This will print the numbers one through five, each on their own line. But you'll notice something here: we never called anything on our array to produce an iterator. What gives?There's a trait in the core library for converting something into an iterator: IntoIterator
. This trait has one method, into_iter
, which converts the thing implementing IntoIterator
into an iterator. Let's take a look at that for
loop again, and what the compiler converts it into:
let values = array![1, 2, 3, 4, 5];
for x in values {
println!("{x}");
}
Cairo de-sugars this into:
let values = array![1, 2, 3, 4, 5];
{
let mut iter = IntoIterator::into_iter(values);
let result = loop {
let mut next = 0;
match iter.next() {
Some(val) => next = val,
None => {
break;
},
};
let x = next;
let () = { println!("{x}"); };
};
result
}
First, we call into_iter()
on the value. Then, we match on the iterator that returns, calling next
over and over until we see a None
. At that point, we break
out of the loop, and we're done iterating.There's one more subtle bit here: the core library contains an interesting implementation of IntoIterator
:
impl IteratorIntoIterator<T, +Iterator<T>> of IntoIterator<T>
In other words, all Iterator
s implement IntoIterator
, by just returning themselves. This means two things:If you're writing an Iterator
, you can use it with a for
loop. 2. If you're creating a collection, implementing IntoIterator
for it will allow your collection to be used with the for
loop. # AdaptersFunctions which take an Iterator
and return another Iterator
are often called 'iterator adapters', as they're a form of the 'adapter pattern'.Common iterators adapters include map
, enumerate
and zip
.map
: Iterator::map enumerate
: Iterator::enumerate zip
: Iterator::zip # LazinessIterators (and iterator adapters) are lazy. This means that just creating an iterator doesn't do a whole lot. Nothing really happens until you call next
. This is sometimes a source of confusion when creating an iterator solely for its side effects. For example, the map
method calls a closure on each element it iterates over:
let v = array![1, 2, 3, 4, 5];
let _ = v.into_iter().map(|x| println!("{x}"));
This will not print any values, as we only created an iterator, rather than using it. The compiler will warn us about this kind of behavior:
Unhandled `#[must_use]` type
Fully qualified path: core::iter
Traits
metaprogramming
Metaprogramming utilities.
Fully qualified path: core::metaprogramming
Traits
testing
Measurement of gas consumption for testing purpose.This module provides the get_available_gas
function, useful for asserting the amount of gas consumed by a particular operation or function call. By calling get_available_gas
before and after the operation, you can calculate the exact amount of gas used.
Fully qualified path: core::testing
Extern functions
to_byte_array
ASCII representation of numeric types for ByteArray
manipulation.This module enables conversion of numeric values into their ASCII string representation, with support for different numeric bases and efficient appending to existing ByteArray
. # ExamplesBasic decimal formatting:
use core::to_byte_array::{FormatAsByteArray, AppendFormattedToByteArray};
let value: u32 = 42;
let base: NonZero<u32> = 10;
// Create a new formatted `ByteArray`
let formatted = value.format_as_byte_array(base);
assert!(formatted == "42");
// Append to an existing `ByteArray`
let mut buffer = "Value: ";
value.append_formatted_to_byte_array(ref buffer, base);
assert!(buffer == "Value: 42");
Custom base formatting:
use core::to_byte_array::FormatAsByteArray;
let value: u32 = 255;
// Hexadecimal representation
let hex = value.format_as_byte_array(16);
assert!(hex == "ff");
// Binary representation
let bin = value.format_as_byte_array(2);
assert!(bin == "11111111");
Fully qualified path: core::to_byte_array
Traits
stark_curve
Fully qualified path: core::ec::stark_curve
Constants
traits
Fully qualified path: core::num::traits
Modules
Traits
zero
Traits for types with an additive identity element.
Fully qualified path: core::num::traits::zero
Traits
one
Traits for types with a multiplicative identity element.
Fully qualified path: core::num::traits::one
Traits
bit_size
Utilities for determining the bit size of types.
Fully qualified path: core::num::traits::bit_size
Traits
ops
Fully qualified path: core::num::traits::ops
Modules
checked
Safe arithmetic operations with overflow/underflow checking.This module provides traits for performing arithmetic operations with explicit overflow and underflow protection. These operations return None
when an overflow or underflow occurs, allowing you to handle these cases gracefully without panicking. # Examples
use core::num::traits::{CheckedAdd, CheckedSub, CheckedMul};
// Checked addition
let a: u8 = 1;
assert!(a.checked_add(2) == Some(3));
assert!(a.checked_add(255) == None); // Overflow
// Checked subtraction
let b: u8 = 1;
assert!(b.checked_sub(1) == Some(0));
assert!(b.checked_sub(2) == None); // Underflow
// Checked multiplication
let c: u8 = 10;
assert!(c.checked_mul(20) == Some(200));
assert!(c.checked_mul(30) == None); // Overflow
Fully qualified path: core::num::traits::ops::checked
Traits
overflowing
Arithmetic operations with overflow detection.This module provides traits for performing arithmetic operations that explicitly track potential numeric overflow conditions.
Fully qualified path: core::num::traits::ops::overflowing
Traits
pow
Trait and implementations for raising a value to a power.This module provides efficient exponentiation operations for numeric types using the square-and-multiply algorithm, which achieves logarithmic time complexity O(log n).
Fully qualified path: core::num::traits::ops::pow
Traits
saturating
Saturating arithmetic operations for numeric types.This module provides traits and implementations for arithmetic operations that saturate at the numeric type's boundaries instead of overflowing.
Fully qualified path: core::num::traits::ops::saturating
Traits
wrapping
Arithmetic operations with overflow and underflow wrapping.This module provides traits for performing arithmetic operations that wrap around at the boundary of the type in case of overflow or underflow. This is particularly useful when you want to: - Perform arithmetic operations without panicking on overflow/underflow - Implement modular arithmetic - Handle cases where overflow is expected and desired # Examples
use core::num::traits::{WrappingAdd, WrappingSub, WrappingMul};
// Addition wrapping
let a: u8 = 255;
assert!(a.wrapping_add(1) == 0);
// Subtraction wrapping
let b: u8 = 0;
assert!(b.wrapping_sub(1) == 255);
// Multiplication wrapping
let c: u8 = 200;
assert!(c.wrapping_mul(2) == 144); // (200 * 2) % 256 = 144
Fully qualified path: core::num::traits::ops::wrapping
Traits
index
Indexing traits for indexing operations on collections.This module provides traits for implementing the indexing operator []
, offering two distinct approaches to access elements in collections:IndexView
- For snapshot-based access * Index
- For reference-based access # When to use which traitUse IndexView
when the collection can be accessed in a read-only context and is not mutated by a read access. This is the most common case in Cairo. - Use Index
when the input type needs to be passed as ref
. This is mainly useful for types depending on a Felt252Dict
, where dictionary accesses are modifying the data structure itself.Only one of these traits should be implemented for any given type, not both.
Fully qualified path: core::ops::index
Traits
into_felt252_based
Implementation for Hash
for types that can be converted into felt252
using the Into
trait. # Examples
impl MyTypeHash<S, +HashStateTrait<S>, +Drop<S>> =
core::hash::into_felt252_based::HashImpl<MyType, S>;`
Fully qualified path: core::hash::into_felt252_based
into_felt252_based
Fully qualified path: core::serde::into_felt252_based
into_felt252_based
Implementations for Debug
and LowerHex
for types that can be converted into felt252
using the Into
trait. # Examples
impl MyTypeDebug = crate::fmt::into_felt252_based::DebugImpl<MyType>;`
impl MyTypeLowerHex = crate::fmt::into_felt252_based::LowerHexImpl<MyType>;
Fully qualified path: core::fmt::into_felt252_based
storage_access
Storage access primitives for Starknet contract storage.This module provides abstractions over the system calls for reading from and writing to Starknet contract storage. It includes traits and implementations for storing various data types efficiently. # Storage ArchitectureStorage addresses range from [0, 2^251)
* Base addresses can be combined with offsets, allowing storage of up to 255 values sequentially * Multiple storage domains can be supported, each with its own set of storage space. Currently, only the domain 0
is supported. Values stored in domain 0
are committed to Ethereum as part of the state diffs. # Core ComponentsStorageAddress
: Represents a specific storage location * StorageBaseAddress
: Base address that can be combined with offsets * Store<T>
: Core trait for types that can be stored in contract storage * StorePacking<T,P>
: Trait for efficient packing/unpacking of valuesGenerally, you don't need to implement the Store
trait yourself. Most types of the core library, at the exception of collection types, implement the Store
trait - and thus, you can derive the Store
trait for your own types, as long as they don't contain any collections.
Fully qualified path: core::starknet::storage_access
Traits
Extern types
Extern functions
syscalls
Utilities for interacting with the Starknet OS.Writing smart contracts requires various associated operations, such as calling another contract or accessing the contract’s storage, that standalone programs do not require. Cairo supports these operations by using system calls.System calls enable a contract to require services from the Starknet OS. You can use system calls in a function to get information that depends on the broader state of Starknet, such as the current timestamp of the address of the caller, but also to modify the state of Starknet by, for example, storing values in a contract's storage or deploying new contracts.
Fully qualified path: core::starknet::syscalls
Extern functions
contract_address
The ContractAddress
type represents a Starknet contract address, with a value range of [0, 2**251)
.A variable of type ContractAddress
can be created from a felt252
value using the contract_address_const
function, or using the TryInto
trait. # Examples
use starknet::contract_address::contract_address_const;
let contract_address = contract_address_const::<0x0>();
Fully qualified path: core::starknet::contract_address
Extern types
Extern functions
secp256_trait
Elliptic Curve Digital Signature Algorithm (ECDSA) for Secp256k1 and Secp256r1 curves.This module provides traits and functions for working with ECDSA signatures on the Secp256k1 and the Secp256r1 curves. It includes utilities for creating and validating signatures, as well as recovering public keys from signatures. # Examples
use starknet::SyscallResultTrait;
Fully qualified path: core::starknet::secp256_trait
Free functions
Structs
Traits
secp256k1
Functions and constructs related to elliptic curve operations on the secp256k1 curve.This module provides functionality for performing operations on the secp256k1 elliptic curve, commonly used in cryptographic applications such as Bitcoin and Ethereum. It implements the traits defined in the secp256_trait
module to ensure consistent behavior across different secp256 curve implementations.Curve information: * Base field: q = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f * Scalar field: r = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141 * Curve equation: y^2 = x^3 + 7
Fully qualified path: core::starknet::secp256k1
Extern types
secp256r1
Functions and constructs related to elliptic curve operations on the secp256r1 curve.This module provides functionality for performing operations on the NIST P-256 (also known as secp256r1) elliptic curve. It implements the traits defined in the secp256_trait
module to ensure consistent behavior across different secp256 curve implementations.Curve information: * Base field: q = 0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff * Scalar field: r = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551 * a = -3 * b = 0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b * Curve equation: y^2 = x^3 + ax + b
Fully qualified path: core::starknet::secp256r1
Extern types
eth_address
Ethereum address type for working with Ethereum primitives.This module provides the EthAddress
type, which is used when interacting with Ethereum primitives, such as signatures and L1 <-> L2 messages.
Fully qualified path: core::starknet::eth_address
Structs
eth_signature
Utilities for Ethereum signature verification and address recovery.This module provides functionality for working with Ethereum signatures. It implements verification of Ethereum signatures against addresses and conversion of public keys to Ethereum addresses.
Fully qualified path: core::starknet::eth_signature
Free functions
class_hash
The ClassHash
type represents a Starknet contract class hash, with a value range of [0, 2**251)
.A variable of type ClassHash
can be created from a felt252
value using the class_hash_const
function, or using the TryInto
trait. # Examples
use starknet::class_hash::class_hash_const;
let hash = class_hash_const::<0x123>();
let hash = 0x123.try_into().unwrap();
Fully qualified path: core::starknet::class_hash
Extern types
Extern functions
event
Event handling traits for Starknet smart contracts.This module provides traits for serializing, deserializing and emitting events on Starknet. The Event
trait handles the serialization of event types, while the EventEmitter
trait provides the capability to emit events from Starknet contracts.
Fully qualified path: core::starknet::event
Traits
account
Account module defining the Call
struct and the AccountContract
trait.The Call
struct represents a call to a contract, with the following fields: - to
: The address of the contract to call. - selector
: The entry point selector in the called contract. - calldata
: The calldata to pass to the entry point.The AccountContract
trait defines the standard interface for account contracts. It assumes that the calldata for invoke transactions is an Array<Call>
, following the SNIP6 standard.Implementing this trait allows contracts to function as account contracts in the Starknet network, supporting class declarations and batched call execution.
Fully qualified path: core::starknet::account
Structs
Traits
storage
Storage-related types and traits for Cairo contracts.This module implements the storage system for Starknet contracts, providing high-level abstractions for persistent data storage. It offers a type-safe interface for reading and writing to Starknet storage through the StoragePointerReadAccess
and StoragePointerWriteAccess
traits, along with useful storage-only collection types like Vec
and Map
.Vec
: starknet::storage::vec::Vec Map
: starknet::storage::map::Map # OverviewThe storage system in Starknet contracts is built on a key-value store where each storage slot is identified by a 251-bit address. The storage system allows interactions with storage using state variables, which are declared inside a Storage
struct annotated with the #[storage]
attribute. This ensures type-safe storage access and simplifies the process of reading and writing to storage. # Using the Storage SystemStorage is typically declared using the #[storage]
attribute on a struct:
[storage]
struct Storage {
balance: u256,
users: Map<ContractAddress, User>,
nested_data: Map<ContractAddress, Map<ContractAddress, u8>>,
collection: Vec<u8>,
}
Any type that implements the Store
trait (or it's optimized StorePacked
variant) can be used in storage. This type can simply be derived using #[derive(Store)]
- provided that all of the members of the type also implement Store
.
[derive(Copy, Default, Drop, Store)]
struct User {
name: felt252,
age: u8,
}
Interaction with storage is made through a set of traits, depending on the type interacted with:StoragePointerReadAccess
and StoragePointerWriteAccess
allow for reading and writing storable types. - StorageMapReadAccess
and StorageMapWriteAccess
allow for reading and writing to storage Map
s. - StoragePathEntry
allows for accessing a specific entry in a Map
, and can be combined with the StoragePointer
traits to read and write in these entries. - VecTrait
and MutableVecTrait
allow for interacting with storage Vec
s.VecTrait
: starknet::storage::vec::VecTrait MutableVecTrait
: starknet::storage::vec::MutableVecTrait StorageMapReadAccess
: starknet::storage::map::StorageMapReadAccess StorageMapWriteAccess
: starknet::storage::map::StorageMapWriteAccess StoragePathEntry
: starknet::storage::map::StoragePathEntry ## Examples
fn use_storage(self: @ContractState) {
let address = 'address'.try_into().unwrap();
// Reading values
let balance = self.balance.read();
// For a `Map`, use the `entry` method to access values at specific keys:
let user = self.users.entry(address).read();
// Accessing nested `Map`s requires chaining `entry` calls:
let nested = self.nested_data.entry(address).entry(address).read();
// Accessing a specific index in a `Vec` requires using the `index` method:
let element = self.collection[index];
// Writing values
self.balance.write(100);
self.users.entry(address).write(Default::default());
self.nested_data.entry(address).entry(address).write(10);
self.collection[index].write(20);
}
Storage LifecycleWhen you access a storage variable, it goes through several transformations:FlattenedStorage: The starting point is your contract's storage struct. Each member is represented either as a StorageBase
or another FlattenedStorage
(for #[substorage(v0)]
or #[flat]
members).StorageBase: For simple variables, this holds the sn_keccak
hash of the variable name, which becomes the storage address. For example:
#[storage]
struct Storage {
balance: u128, // Stored at sn_keccak('balance')
}
StoragePath: For complex types, a StoragePath
represents an un-finalized path to aspecific entry in storage. For example, a StoragePath
for a Map
can be updated withspecific keys to point to a specific entry in the map.StoragePointer: The final form, pointing to the actual storage location. For multi-slotvalues (like structs), values are stored sequentially from this address. # Storage CollectionsCairo's memory collection types, like Felt252Dict
and Array
, can not be used in storage.Consequently, any type that contains these types can not be used in storage either.Instead, Cairo has two storage-only collection types: Map
and Vec
.Instead of storing these memory collections directly, you will need to reflect them intostorage using the Map
and Vec
types. # Address CalculationStorage addresses are calculated deterministically:For a single value variable, the address is the sn_keccak
hash of the variable name's ASCIIencoding. sn_keccak
is Starknet's version of the Keccak-256 hash function, with its outputtruncated to 250 bits.For variables composed of multiple values (tuples, structs, or enums), the base storageaddress is also the sn_keccak
hash of the variable name's ASCII encoding. The storage layoutthen varies depending on the specific type. A struct will store its members as a sequence ofprimitive types, while an enum will store its variant index, followed by the members of thevariant.For variables within a storage node, the address is calculated using a chain of hashes thatrepresents the node structure. Given a member m
within a storage variable variable_name
,the path is computed as h(sn_keccak(variable_name), sn_keccak(m))
, where h
is the Pedersenhash. For nested storage nodes, this process repeats, creating a hash chain representing thepath to each leaf node. At the leaf node, the storage calculation follows the standard rules forthat variable type.For Map
or Vec
variables, the address is calculated relative to the storage baseaddress (the sn_keccak
hash of the variable name) combined with the mapping keys or vectorindices.See their respective module documentation for more details.
Fully qualified path: core::starknet::storage
Structs
Traits
Impls
testing
Testing utilities for Starknet contracts.This module provides functions for testing Starknet contracts. The functions allow manipulation of blockchain state and storage variables during tests, as well as inspection of emitted events and messages.Note: The functions in this module can only be used with the cairo-test
testing framework. If you are using Starknet Foundry, refer to its documentation.
Fully qualified path: core::starknet::testing
Free functions
Extern functions
Constants
ALPHA
The STARK Curve is defined by the equation y² ≡ x³ + α·x + β (mod p).
Fully qualified path: core::ec::stark_curve::ALPHA
pub const ALPHA: felt252 = 1;
BETA
The STARK Curve is defined by the equation y² ≡ x³ + α·x + β (mod p).
Fully qualified path: core::ec::stark_curve::BETA
pub const BETA: felt252 = 0x6f21413efbe40de150e596d72f7a8c5609ad26c15c915c1f4cdfcb99cee9e89;
ORDER
The order (number of points) of the STARK Curve.
Fully qualified path: core::ec::stark_curve::ORDER
pub const ORDER: felt252 = 0x800000000000010ffffffffffffffffb781126dcae7b2321e66a241adc64d2f;
GEN_X
The x coordinate of the generator point used in the ECDSA signature.
Fully qualified path: core::ec::stark_curve::GEN_X
pub const GEN_X: felt252 = 0x1ef15c18599971b7beced415a40f0c7deacfd9b0d1819e03d723d8bc943cfca;
GEN_Y
The y coordinate of the generator point used in the ECDSA signature.
Fully qualified path: core::ec::stark_curve::GEN_Y
pub const GEN_Y: felt252 = 0x5668060aa49730b7be4801df46ec62de53ecd11abe43a32873000c36e8dc1f;
VALIDATED
The expected return value of the __validate__
function in account contracts.This constant is used to indicate that a transaction validation was successful. Account contracts must return this value from their __validate__
function to signal that the transaction should proceed.
Fully qualified path: core::starknet::VALIDATED
pub const VALIDATED: felt252 = 'VALID';
BYTE_ARRAY_MAGIC
A magic constant for identifying serialization of ByteArray
variables. An array of felt252
with this magic value as one of the felt252
indicates that you should expect right after it a serialized ByteArray
. This is currently used mainly for prints and panics.
Fully qualified path: core::byte_array::BYTE_ARRAY_MAGIC
pub const BYTE_ARRAY_MAGIC: felt252 =
0x46a6158a16a947e5916b2a2ca68501a45e93d7110e81aa2d6438b1c57c879a3;
Free functions
panic_with_felt252
Panics with the given felt252
as error message. # Examples
use core::panic_with_felt252;
panic_with_felt252('error message');
Fully qualified path: core::panic_with_felt252
pub fn panic_with_felt252(err_code: felt252) -> never
panic_with_const_felt252
Panics with the given const argument felt252
as error message. # Examples
use core::panic_with_const_felt252;
panic_with_const_felt252::<'error message'>();
Fully qualified path: core::panic_with_const_felt252
pub fn panic_with_const_felt252<const ERR_CODE: felt252>() -> never
assert
Panics if cond
is false with the given felt252
as error message. # Examples
assert(false, 'error message');
Fully qualified path: core::assert
pub const fn assert(cond: bool, err_code: felt252)
circuit_add
Creates a new circuit element representing addition modulo p of two input circuits.This function combines two circuit elements using modular addition, creating a new circuit element that represents their sum modulo the circuit's modulus. # Argumentslhs
- Left-hand side circuit element * rhs
- Right-hand side circuit element # ReturnsA new circuit element representing (lhs + rhs) mod p
# Examples
let a = CircuitElement::<CircuitInput<0>> {};
let b = CircuitElement::<CircuitInput<1>> {};
let sum = circuit_add(a, b);
Fully qualified path: core::circuit::circuit_add
pub fn circuit_add<Lhs, Rhs, +CircuitElementTrait<Lhs>, +CircuitElementTrait<Rhs>>(
lhs: CircuitElement<Lhs>, rhs: CircuitElement<Rhs>,
) -> CircuitElement<AddModGate<Lhs, Rhs>>
circuit_sub
Creates a new circuit element representing subtraction modulo p of two input circuits.This function combines two circuit elements using modular subtraction, creating a new circuit element that represents their difference modulo the circuit's modulus. # Argumentslhs
- Left-hand side circuit element (minuend) * rhs
- Right-hand side circuit element (subtrahend) # ReturnsA new circuit element representing (lhs - rhs) mod p
# Examples
let a = CircuitElement::<CircuitInput<0>> {};
let b = CircuitElement::<CircuitInput<1>> {};
let diff = circuit_sub(a, b);
Fully qualified path: core::circuit::circuit_sub
pub fn circuit_sub<Lhs, Rhs, +CircuitElementTrait<Lhs>, +CircuitElementTrait<Rhs>>(
lhs: CircuitElement<Lhs>, rhs: CircuitElement<Rhs>,
) -> CircuitElement<SubModGate<Lhs, Rhs>>
circuit_inverse
Creates a new circuit element representing the multiplicative inverse modulo p of an input circuit.This function creates a new circuit element representing the multiplicative inverse of the input element modulo the circuit's modulus. The operation will fail during evaluation if the input is not invertible (not coprime with the modulus). # Argumentsinput
- Circuit element to compute the inverse of # ReturnsA new circuit element representing input^(-1) mod p
# Examples
let a = CircuitElement::<CircuitInput<0>> {};
let inv_a = circuit_inverse(a);
Fully qualified path: core::circuit::circuit_inverse
pub fn circuit_inverse<Input, +CircuitElementTrait<Input>>(
input: CircuitElement<Input>,
) -> CircuitElement<InverseGate<Input>>
circuit_mul
Creates a new circuit element representing multiplication modulo p of two input circuits.This function combines two circuit elements using modular multiplication, creating a new circuit element that represents their product modulo the circuit's modulus. # Argumentslhs
- Left-hand side circuit element * rhs
- Right-hand side circuit element # ReturnsA new circuit element representing (lhs * rhs) mod p
# Examples
let a = CircuitElement::<CircuitInput<0>> {};
let b = CircuitElement::<CircuitInput<1>> {};
let product = circuit_mul(a, b);
Fully qualified path: core::circuit::circuit_mul
pub fn circuit_mul<Lhs, Rhs, +CircuitElementTrait<Lhs>, +CircuitElementTrait<Rhs>>(
lhs: CircuitElement<Lhs>, rhs: CircuitElement<Rhs>,
) -> CircuitElement<MulModGate<Lhs, Rhs>>
check_ecdsa_signature
Verifies an ECDSA signature against a message hash and public key.Note: the verification algorithm implemented by this function slightly deviates from the standard ECDSA. While this does not allow to create valid signatures if one does not possess the private key, it means that the signature algorithm used should be modified accordingly. This function validates that s
and r
are not 0 or equal to the curve order, but does not check that r, s < stark_curve::ORDER
, which should be checked by the caller. # Arguments * message_hash
- The hash of the signed message * public_key
- The x-coordinate of the signer's public key point on the STARK curve * signature_r
- The r component of the ECDSA signature (x-coordinate of point R) * signature_s
- The s component of the ECDSA signature # Returns Returns true
if the signature is valid, false
otherwise. # Examples
use core::ecdsa::check_ecdsa_signature;
let message_hash = 0x2d6479c0758efbb5aa07d35ed5454d728637fceab7ba544d3ea95403a5630a8;
let pubkey = 0x1ef15c18599971b7beced415a40f0c7deacfd9b0d1819e03d723d8bc943cfca;
let r = 0x6ff7b413a8457ef90f326b5280600a4473fef49b5b1dcdfcd7f42ca7aa59c69;
let s = 0x23a9747ed71abc5cb956c0df44ee8638b65b3e9407deade65de62247b8fd77;
assert!(check_ecdsa_signature(message_hash, pubkey, r, s));
Fully qualified path: core::ecdsa::check_ecdsa_signature
pub fn check_ecdsa_signature(
message_hash: felt252, public_key: felt252, signature_r: felt252, signature_s: felt252,
) -> bool
recover_public_key
Recovers the public key from an ECDSA signature and message hash.Given a valid ECDSA signature, the original message hash, and the y-coordinate parity of point R, this function recovers the signer's public key. This is useful in scenarios where you need to verify a message has been signed by a specific public key. # Arguments * message_hash
- The hash of the signed message * signature_r
- The r component of the ECDSA signature (x-coordinate of point R) * signature_s
- The s component of the ECDSA signature * y_parity
- The parity of the y-coordinate of point R (true
for odd, false
for even) # Returns Returns Some(public_key)
containing the x-coordinate of the recovered public key point if the signature is valid, None
otherwise. # Examples
use core::ecdsa::recover_public_key;
let message_hash = 0x503f4bea29baee10b22a7f10bdc82dda071c977c1f25b8f3973d34e6b03b2c;
let signature_r = 0xbe96d72eb4f94078192c2e84d5230cde2a70f4b45c8797e2c907acff5060bb;
let signature_s = 0x677ae6bba6daf00d2631fab14c8acf24be6579f9d9e98f67aa7f2770e57a1f5;
assert!(
recover_public_key(:message_hash, :signature_r, :signature_s, y_parity: false)
.unwrap() == 0x7b7454acbe7845da996377f85eb0892044d75ae95d04d3325a391951f35d2ec,
)
Fully qualified path: core::ecdsa::recover_public_key
pub fn recover_public_key(
message_hash: felt252, signature_r: felt252, signature_s: felt252, y_parity: bool,
) -> Option<felt252>
u128_wrapping_add
Fully qualified path: core::integer::u128_wrapping_add
pub fn u128_wrapping_add(lhs: u128, rhs: u128) -> u128 implicits(RangeCheck) nopanic
u128_wrapping_sub
Fully qualified path: core::integer::u128_wrapping_sub
pub fn u128_wrapping_sub(a: u128, b: u128) -> u128 implicits(RangeCheck) nopanic
u128_wide_mul
Multiplies two u128s and returns (high, low)
- the 128-bit parts of the result.
Fully qualified path: core::integer::u128_wide_mul
pub fn u128_wide_mul(a: u128, b: u128) -> (u128, u128) nopanic
u128_overflowing_mul
Fully qualified path: core::integer::u128_overflowing_mul
pub fn u128_overflowing_mul(lhs: u128, rhs: u128) -> (u128, bool) implicits(RangeCheck) nopanic
u8_wrapping_add
Fully qualified path: core::integer::u8_wrapping_add
pub fn u8_wrapping_add(lhs: u8, rhs: u8) -> u8 implicits(RangeCheck) nopanic
u8_wrapping_sub
Fully qualified path: core::integer::u8_wrapping_sub
pub fn u8_wrapping_sub(lhs: u8, rhs: u8) -> u8 implicits(RangeCheck) nopanic
u16_wrapping_add
Fully qualified path: core::integer::u16_wrapping_add
pub fn u16_wrapping_add(lhs: u16, rhs: u16) -> u16 implicits(RangeCheck) nopanic
u16_wrapping_sub
Fully qualified path: core::integer::u16_wrapping_sub
pub fn u16_wrapping_sub(lhs: u16, rhs: u16) -> u16 implicits(RangeCheck) nopanic
u32_wrapping_add
Fully qualified path: core::integer::u32_wrapping_add
pub fn u32_wrapping_add(lhs: u32, rhs: u32) -> u32 implicits(RangeCheck) nopanic
u32_wrapping_sub
Fully qualified path: core::integer::u32_wrapping_sub
pub fn u32_wrapping_sub(lhs: u32, rhs: u32) -> u32 implicits(RangeCheck) nopanic
u64_wrapping_add
Fully qualified path: core::integer::u64_wrapping_add
pub fn u64_wrapping_add(lhs: u64, rhs: u64) -> u64 implicits(RangeCheck) nopanic
u64_wrapping_sub
Fully qualified path: core::integer::u64_wrapping_sub
pub fn u64_wrapping_sub(lhs: u64, rhs: u64) -> u64 implicits(RangeCheck) nopanic
u256_overflowing_add
Fully qualified path: core::integer::u256_overflowing_add
pub fn u256_overflowing_add(lhs: u256, rhs: u256) -> (u256, bool) implicits(RangeCheck) nopanic
u256_overflowing_sub
Fully qualified path: core::integer::u256_overflowing_sub
pub fn u256_overflowing_sub(lhs: u256, rhs: u256) -> (u256, bool) implicits(RangeCheck) nopanic
u256_overflow_sub
Fully qualified path: core::integer::u256_overflow_sub
pub fn u256_overflow_sub(lhs: u256, rhs: u256) -> (u256, bool) implicits(RangeCheck) nopanic
u256_overflowing_mul
Fully qualified path: core::integer::u256_overflowing_mul
pub fn u256_overflowing_mul(lhs: u256, rhs: u256) -> (u256, bool)
u256_overflow_mul
Fully qualified path: core::integer::u256_overflow_mul
pub fn u256_overflow_mul(lhs: u256, rhs: u256) -> (u256, bool)
u256_wide_mul
Fully qualified path: core::integer::u256_wide_mul
pub fn u256_wide_mul(a: u256, b: u256) -> u512 nopanic
u512_safe_div_rem_by_u256
Calculates division with remainder of a u512 by a non-zero u256.
Fully qualified path: core::integer::u512_safe_div_rem_by_u256
pub fn u512_safe_div_rem_by_u256(
lhs: u512, rhs: NonZero<u256>,
) -> (u512, u256) implicits(RangeCheck) nopanic
min
Takes two comparable values a
and b
and returns the smaller of the two values. # Examples
use core::cmp::min;
assert!(min(0, 1) == 0);
Fully qualified path: core::cmp::min
pub fn min<T, +PartialOrd<T>, +Drop<T>, +Copy<T>>(a: T, b: T) -> T
max
Takes two comparable values a
and b
and returns the greater of the two values. # Examples
use core::cmp::max;
assert!(max(0, 1) == 1);
Fully qualified path: core::cmp::max
pub fn max<T, +PartialOrd<T>, +Drop<T>, +Copy<T>>(a: T, b: T) -> T
minmax
Takes two comparable values a
and b
and returns a tuple with the smaller value and the greater value. # Examples
use core::cmp::minmax;
assert!(minmax(0, 1) == (0, 1));
assert!(minmax(1, 0) == (0, 1));
Fully qualified path: core::cmp::minmax
pub fn minmax<T, +PartialOrd<T>, +Drop<T>, +Copy<T>>(a: T, b: T) -> (T, T)
egcd
Computes the extended GCD and Bezout coefficients for two numbers.Uses the Extended Euclidean algorithm to find (g, s, t, sub_direction) where g = gcd(a, b)
. The relationship between inputs and outputs is: * If sub_direction
is true: g = s * a - t * b
* If sub_direction
is false: g = t * b - s * a
Returns a tuple (g, s, t, sub_direction) where g is the GCD and (s, -t)
or (-s, t)
are the Bezout coefficients (according to sub_direction
). # Examples
use core::math::egcd;
let (g, s, t, dir) = egcd::<u32>(12, 8);
assert!(g == 4);
Fully qualified path: core::math::egcd
pub fn egcd<
T,
+Copy<T>,
+Drop<T>,
+Add<T>,
+Mul<T>,
+DivRem<T>,
+core::num::traits::Zero<T>,
+core::num::traits::One<T>,
+TryInto<T, NonZero<T>>,
>(
a: NonZero<T>, b: NonZero<T>,
) -> (T, T, T, bool)
inv_mod
Computes the modular multiplicative inverse of a
modulo n
.Returns s
such that a*s ≡ 1 (mod n)
where s
is between 1
and n-1
inclusive, or None
if gcd(a,n) > 1
(inverse doesn't exist). # Examples
use core::math::inv_mod;
let inv = inv_mod::<u32>(3, 7);
assert!(inv == Some(5));
Fully qualified path: core::math::inv_mod
pub fn inv_mod<
T,
+Copy<T>,
+Drop<T>,
+Add<T>,
+Sub<T>,
+Mul<T>,
+DivRem<T>,
+core::num::traits::Zero<T>,
+core::num::traits::One<T>,
+TryInto<T, NonZero<T>>,
>(
a: NonZero<T>, n: NonZero<T>,
) -> Option<T>
u256_inv_mod
Returns the inverse of a
modulo n
, or None
if a
is not invertible modulo n
.All a
s will be considered not invertible for n == 1
. # Examples
use core::math::u256_inv_mod;
let inv = u256_inv_mod(3, 17);
assert!(inv == Some(6));
Fully qualified path: core::math::u256_inv_mod
pub fn u256_inv_mod(a: u256, n: NonZero<u256>) -> Option<NonZero<u256>>
u256_div_mod_n
Returns a / b (mod n)
, or None
if b
is not invertible modulo n
. # Examples
use core::math::u256_inv_mod;
let result = u256_div_mod_n(17, 7, 29);
assert!(result == Some(19));
Fully qualified path: core::math::u256_div_mod_n
pub fn u256_div_mod_n(a: u256, b: u256, n: NonZero<u256>) -> Option<u256>
u256_mul_mod_n
Returns a * b (mod n)
. # Examples
use core::math::u256_mul_mod_n;
let result = u256_mul_mod_n(17, 23, 29);
assert!(result == 14);
Fully qualified path: core::math::u256_mul_mod_n
pub fn u256_mul_mod_n(a: u256, b: u256, n: NonZero<u256>) -> u256
panic_with_byte_array
Panics with a ByteArray
message.Constructs a panic message by prepending the BYTE_ARRAY_MAGIC
value and serializing the provided ByteArray
into the panic data. # Examples
use core::panics::panic_with_byte_array;
let error_msg = "An error occurred";
panic_with_byte_array(@error_msg);
Fully qualified path: core::panics::panic_with_byte_array
pub fn panic_with_byte_array(err: @ByteArray) -> crate::never
keccak_u256s_le_inputs
Computes the Keccak-256 hash of multiple u256
values in little-endian format. # Argumentsinput
- A span of little-endian u256
values to be hashed # ReturnsThe 32-byte Keccak-256 hash as a little-endian u256
# Examples
use core::keccak::keccak_u256s_le_inputs;
let input: Span<u256> = array![0, 1, 2].span();
assert!(keccak_u256s_le_inputs(input) ==
0xf005473605efc7d8ff67d9f23fe2e4a4f23454c12b49b38822ed362e0a92a0a6);
Fully qualified path: core::keccak::keccak_u256s_le_inputs
pub fn keccak_u256s_le_inputs(mut input: Span<u256>) -> u256
keccak_u256s_be_inputs
Computes the Keccak-256 hash of multiple u256
values in big-endian format. # Argumentsinput
- A span of big-endian u256
values to be hashed # ReturnsThe 32-byte Keccak-256 hash as a little-endian u256
# Examples
use core::keccak::keccak_u256s_be_inputs;
let input = array![0x1234_u256, 0x5678_u256].span();
let hash = assert!(keccak_u256s_be_inputs(input) ==
0xfa31cb2326ed629f79d2da5beb78e2bd8ac7a1b8b86cae09eeb6a89a908b12a);
Fully qualified path: core::keccak::keccak_u256s_be_inputs
pub fn keccak_u256s_be_inputs(mut input: Span<u256>) -> u256
cairo_keccak
Computes the Keccak-256 hash of a byte sequence with custom padding.This function allows hashing arbitrary byte sequences by providing the input as 64-bit words in little-endian format and a final partial word. # Argumentsinput
- Array of complete 64-bit words in little-endian format * last_input_word
- Final partial word (if any) * last_input_num_bytes
- Number of valid bytes in the final word (0-7) # ReturnsThe 32-byte Keccak-256 hash as a little-endian u256
# PanicsPanics if last_input_num_bytes
is greater than 7. # Examples
use core::keccak::cairo_keccak;
// Hash "Hello world!" by splitting into 64-bit words in little-endian
let mut input = array![0x6f77206f6c6c6548]; // a full 8-byte word
let hash = cairo_keccak(ref input, 0x21646c72, 4); // 4 bytes of the last word
assert!(hash == 0xabea1f2503529a21734e2077c8b584d7bee3f45550c2d2f12a198ea908e1d0ec);
Fully qualified path: core::keccak::cairo_keccak
pub fn cairo_keccak(
ref input: Array<u64>, last_input_word: u64, last_input_num_bytes: usize,
) -> u256
compute_keccak_byte_array
Computes the Keccak-256 hash of a ByteArray
. # Argumentsarr
- The input bytes to hash # ReturnsThe 32-byte Keccak-256 hash as a little-endian u256
# Examples
use core::keccak::compute_keccak_byte_array;
let text: ByteArray = "Hello world!";
let hash = compute_keccak_byte_array(@text);
assert!(hash == 0xabea1f2503529a21734e2077c8b584d7bee3f45550c2d2f12a198ea908e1d0ec);
Fully qualified path: core::keccak::compute_keccak_byte_array
pub fn compute_keccak_byte_array(arr: @ByteArray) -> u256
compute_sha256_u32_array
Computes the SHA-256 hash of an array of 32-bit words. # Argumentsinput
- An array of u32
values to hash * last_input_word
- The final word when input is not word-aligned * last_input_num_bytes
- Number of bytes in the last input word (must be less than 4) # ReturnsThe SHA-256 hash of the input array
+ last_input_word
as big endian # Examples
use core::sha256::compute_sha256_u32_array;
let hash = compute_sha256_u32_array(array![0x68656c6c], 0x6f, 1);
assert!(hash == [0x2cf24dba, 0x5fb0a30e, 0x26e83b2a, 0xc5b9e29e, 0x1b161e5c, 0x1fa7425e,
0x73043362, 0x938b9824]);
Fully qualified path: core::sha256::compute_sha256_u32_array
pub fn compute_sha256_u32_array(
mut input: Array<u32>, last_input_word: u32, last_input_num_bytes: u32,
) -> [u32; 8]
compute_sha256_byte_array
Computes the SHA-256 hash of the input ByteArray
. # Examples
use core::sha256::compute_sha256_byte_array;
Fully qualified path: core::sha256::compute_sha256_byte_array
pub fn compute_sha256_byte_array(arr: @ByteArray) -> [u32; 8]
poseidon_hash_span
Computes the Poseidon hash on the given span input. Applies the sponge construction to digest many elements. To distinguish between use cases, the capacity element is initialized to 0. To distinguish between different input sizes always pads with 1, and possibly with another 0 to complete to an even-sized input. # Examples
let span = [1, 2].span();
let hash = poseidon_hash_span(span);
assert!(hash == 0x0371cb6995ea5e7effcd2e174de264b5b407027a75a231a70c2c8d196107f0e7);
Fully qualified path: core::poseidon::poseidon_hash_span
pub fn poseidon_hash_span(mut span: Span<felt252>) -> felt252
print_byte_array_as_string
Prints a ByteArray
as a string. # Examples
let ba: ByteArray = "123";
print_byte_array_as_string(@ba);
Fully qualified path: core::debug::print_byte_array_as_string
pub fn print_byte_array_as_string(self: @ByteArray)
get_block_info
Returns the block information for the current block. # Examples
use starknet::get_block_info;
let block_info = get_block_info().unbox();
let block_number = block_info.block_number;
let block_timestamp = block_info.block_timestamp;
let sequencer = block_info.sequencer_address;
Fully qualified path: core::starknet::info::get_block_info
pub fn get_block_info() -> Box<BlockInfo>
get_block_number
Returns the number of the current block. # Examples
use starknet::get_block_number;
let block_number = get_block_number();
Fully qualified path: core::starknet::info::get_block_number
pub fn get_block_number() -> u64
get_block_timestamp
Returns the timestamp of the current block. # Examples
use starknet::get_block_timestamp;
let block_timestamp = get_block_timestamp();
Fully qualified path: core::starknet::info::get_block_timestamp
pub fn get_block_timestamp() -> u64
get_caller_address
Returns the address of the caller contract. # Examples
use starknet::get_caller_address;
let caller = get_caller_address();
Fully qualified path: core::starknet::info::get_caller_address
pub fn get_caller_address() -> ContractAddress
get_contract_address
Returns the address of the contract being executed. # Examples
use starknet::get_contract_address;
let contract_address = get_contract_address();
Fully qualified path: core::starknet::info::get_contract_address
pub fn get_contract_address() -> ContractAddress
get_execution_info
Returns the execution info for the current execution. # Examples
use starknet::get_execution_info;
let execution_info = get_execution_info().unbox();
// Access various execution context information
let caller = execution_info.caller_address;
let contract = execution_info.contract_address;
let selector = execution_info.entry_point_selector;
Fully qualified path: core::starknet::info::get_execution_info
pub fn get_execution_info() -> Box<v2::ExecutionInfo>
get_tx_info
Returns the transaction information for the current transaction. # Examples
use starknet::get_tx_info;
let tx_info = get_tx_info().unbox();
let account_contract_address = tx_info.account_contract_address;
let chain_id = tx_info.chain_id;
let nonce = tx_info.nonce;
let max_fee = tx_info.max_fee;
let tx_hash = tx_info.transaction_hash;
let signature = tx_info.signature;
let version = tx_info.version;
Fully qualified path: core::starknet::info::get_tx_info
pub fn get_tx_info() -> Box<v2::TxInfo>
signature_from_vrs
Creates an ECDSA signature from the v
, r
, and s
values.v
is the sum of an odd number and the parity of the y coordinate of the ec point whose x coordinate is r
.See https://eips.ethereum.org/EIPS/eip-155 for more details. # Examples
use starknet::secp256_trait::signature_from_vrs;
let signature = signature_from_vrs(0,
0xa73bd4903f0ce3b639bbbf6e8e80d16931ff4bcf5993d58468e8fb19086e8cac,
0x36dbcd03009df8c59286b162af3bd7fcc0450c9aa81be5d10d312af6c66b1d60);
Fully qualified path: core::starknet::secp256_trait::signature_from_vrs
pub fn signature_from_vrs(v: u32, r: u256, s: u256) -> Signature
is_signature_entry_valid
Checks whether the given value
is in the range [1, N), where N is the size of the curve.For ECDSA signatures to be secure, both r
and s
components must be in the range [1, N), where N is the order of the curve. Enforcing this range prevents signature malleability attacks where an attacker could create multiple valid signatures for the same message by adding multiples of N. This function validates that a given value meets this requirement. # ReturnsReturns true
if the value is in the valid range [1, N), false
otherwise. # Examples
use starknet::secp256r1::Secp256r1Point;
use starknet::secp256_trait::is_signature_entry_valid;
assert!(!is_signature_entry_valid::<Secp256r1Point>(0));
Fully qualified path: core::starknet::secp256_trait::is_signature_entry_valid
pub fn is_signature_entry_valid<
Secp256Point, +Drop<Secp256Point>, impl Secp256Impl: Secp256Trait<Secp256Point>,
>(
value: u256,
) -> bool
is_valid_signature
Checks whether a signature is valid given a public key point and a message hash. # Examples
use starknet::SyscallResultTrait;
use starknet::secp256r1::Secp256r1Point;
use starknet::secp256_trait::{Secp256Trait, is_valid_signature};
let msg_hash = 0x4cee90eb86eaa050036147a12d49004b6b9c72bd725d39d4785011fe190f0b4d;
let r = 0xa73bd4903f0ce3b639bbbf6e8e80d16931ff4bcf5993d58468e8fb19086e8cac;
let s = 0x36dbcd03009df8c59286b162af3bd7fcc0450c9aa81be5d10d312af6c66b1d60;
let public_key = Secp256Trait::secp256_ec_new_syscall(
0x4aebd3099c618202fcfe16ae7770b0c49ab5eadf74b754204a3bb6060e44eff3,
0x7618b065f9832de4ca6ca971a7a1adc826d0f7c00181a5fb2ddf79ae00b4e10e,
)
.unwrap_syscall()
.unwrap();
assert!(is_valid_signature::<Secp256r1Point>(msg_hash, r, s, public_key));
Fully qualified path: core::starknet::secp256_trait::is_valid_signature
pub fn is_valid_signature<
Secp256Point,
+Drop<Secp256Point>,
impl Secp256Impl: Secp256Trait<Secp256Point>,
+Secp256PointTrait<Secp256Point>,
>(
msg_hash: u256, r: u256, s: u256, public_key: Secp256Point,
) -> bool
recover_public_key
Recovers the public key associated with a given signature and message hash.Returns the public key as a point on the curve. # Examples
use starknet::secp256r1::Secp256r1Point;
use starknet::secp256_trait::{Signature, recover_public_key};
let msg_hash = 0x4cee90eb86eaa050036147a12d49004b6b9c72bd725d39d4785011fe190f0b4d;
let signature = Signature {
r: 0xa73bd4903f0ce3b639bbbf6e8e80d16931ff4bcf5993d58468e8fb19086e8cac,
s: 0x36dbcd03009df8c59286b162af3bd7fcc0450c9aa81be5d10d312af6c66b1d60,
y_parity: true,
};
let public_key = recover_public_key::<Secp256r1Point>(msg_hash, signature);
Fully qualified path: core::starknet::secp256_trait::recover_public_key
pub fn recover_public_key<
Secp256Point,
+Drop<Secp256Point>,
impl Secp256Impl: Secp256Trait<Secp256Point>,
+Secp256PointTrait<Secp256Point>,
>(
msg_hash: u256, signature: Signature,
) -> Option<Secp256Point>
verify_eth_signature
Asserts that an Ethereum signature is valid for a given message hash and Ethereum address. Also verifies that the r
and s
components of the signature are in the range [1, N)
, where N is the size of the curve. # Argumentsmsg_hash
- The 32-byte hash of the message that was signed * signature
- The Ethereum signature containing r
, s
components and y_parity
* eth_address
- The expected Ethereum address of the signer # PanicsPanics if: * The signature components are out of range (not in [1, N) where N is the curve order) * The recovered address doesn't match the provided address # Examples
use starknet::eth_address::EthAddress;
use starknet::eth_signature::verify_eth_signature;
use starknet::secp256_trait::Signature;
let msg_hash = 0xe888fbb4cf9ae6254f19ba12e6d9af54788f195a6f509ca3e934f78d7a71dd85;
let r = 0x4c8e4fbc1fbb1dece52185e532812c4f7a5f81cf3ee10044320a0d03b62d3e9a;
let s = 0x4ac5e5c0c0e8a4871583cc131f35fb49c2b7f60e6a8b84965830658f08f7410c;
let y_parity = true;
let eth_address: EthAddress = 0x767410c1bb448978bd42b984d7de5970bcaf5c43_u256
.try_into()
.unwrap();
verify_eth_signature(msg_hash, Signature { r, s, y_parity }, eth_address);
Fully qualified path: core::starknet::eth_signature::verify_eth_signature
pub fn verify_eth_signature(msg_hash: u256, signature: Signature, eth_address: EthAddress)
is_eth_signature_valid
Validates an Ethereum signature against a message hash and Ethereum address. Similar to verify_eth_signature
but returns a Result
instead of panicking. Also verifies that r
and s
components of the signature are in the range [1, N)
, where N is the size of the curve. # Argumentsmsg_hash
- The 32-byte hash of the message that was signed * signature
- The Ethereum signature containing r
, s
components and y_parity
* eth_address
- The expected Ethereum address of the signer # ReturnsReturns Ok(())
if the signature is valid, or Err(felt252)
containing an error message if invalid. # Examples
use starknet::eth_address::EthAddress;
use starknet::eth_signature::is_eth_signature_valid;
use starknet::secp256_trait::Signature;
let msg_hash = 0xe888fbb4cf9ae6254f19ba12e6d9af54788f195a6f509ca3e934f78d7a71dd85;
let r = 0x4c8e4fbc1fbb1dece52185e532812c4f7a5f81cf3ee10044320a0d03b62d3e9a;
let s = 0x4ac5e5c0c0e8a4871583cc131f35fb49c2b7f60e6a8b84965830658f08f7410c;
let y_parity = true;
let eth_address: EthAddress = 0x767410c1bb448978bd42b984d7de5970bcaf5c43_u256
.try_into()
.unwrap();
assert!(is_eth_signature_valid(msg_hash, Signature { r, s, y_parity }, eth_address).is_ok());
Fully qualified path: core::starknet::eth_signature::is_eth_signature_valid
pub fn is_eth_signature_valid(
msg_hash: u256, signature: Signature, eth_address: EthAddress,
) -> Result<(), felt252>
public_key_point_to_eth_address
Converts a public key point to its corresponding Ethereum address.The Ethereum address is calculated by taking the Keccak-256 hash of the public key coordinates and taking the last 20 big-endian bytes. # Argumentspublic_key_point
- A point on a secp256 curve representing a public key # ReturnsThe 20-byte Ethereum address derived from the public key # Examples
use starknet::eth_signature::public_key_point_to_eth_address;
use starknet::secp256k1::Secp256k1Point;
use starknet::secp256_trait::Secp256Trait;
let public_key: Secp256k1Point = Secp256Trait::secp256_ec_get_point_from_x_syscall(
0xa9a02d48081294b9bb0d8740d70d3607feb20876964d432846d9b9100b91eefd, false,
)
.unwrap()
.unwrap();
let eth_address = public_key_point_to_eth_address(public_key);
assert!(eth_address == 0x767410c1bb448978bd42b984d7de5970bcaf5c43.try_into().unwrap());
Fully qualified path: core::starknet::eth_signature::public_key_point_to_eth_address
pub fn public_key_point_to_eth_address<
Secp256Point,
+Drop<Secp256Point>,
+Secp256Trait<Secp256Point>,
+Secp256PointTrait<Secp256Point>,
>(
public_key_point: Secp256Point,
) -> EthAddress
set_block_number
Sets the block number to the provided value. # Argumentsblock_number
- The block number to set.After a call to set_block_number
, starknet::get_execution_info().block_info.block_number
will return the set value.
Fully qualified path: core::starknet::testing::set_block_number
pub fn set_block_number(block_number: u64)
set_caller_address
Sets the caller address to the provided value. # Argumentsaddress
- The caller address to set.After a call to set_caller_address
, starknet::get_execution_info().caller_address
will return the set value.
Fully qualified path: core::starknet::testing::set_caller_address
pub fn set_caller_address(address: ContractAddress)
set_contract_address
Sets the contract address to the provided value. # Argumentsaddress
- The contract address to set.After a call to set_contract_address
, starknet::get_execution_info().contract_address
will return the set value.
Fully qualified path: core::starknet::testing::set_contract_address
pub fn set_contract_address(address: ContractAddress)
set_sequencer_address
Sets the sequencer address to the provided value. # Argumentsaddress
- The sequencer address to set.After a call to set_sequencer_address
, starknet::get_execution_info().block_info.sequencer_address
will return the set value.
Fully qualified path: core::starknet::testing::set_sequencer_address
pub fn set_sequencer_address(address: ContractAddress)
set_block_timestamp
Sets the block timestamp to the provided value. # Argumentsblock_timestamp
- The block timestamp to set.After a call to set_block_timestamp
, starknet::get_execution_info().block_info.block_timestamp
will return the set value.
Fully qualified path: core::starknet::testing::set_block_timestamp
pub fn set_block_timestamp(block_timestamp: u64)
set_version
Sets the version to the provided value. # Argumentsversion
- The version to set.After a call to set_version
, starknet::get_execution_info().tx_info.version
will return the set value.
Fully qualified path: core::starknet::testing::set_version
pub fn set_version(version: felt252)
set_account_contract_address
Sets the account contract address. # Argumentsaddress
- The account contract to set.After a call to set_account_contract_address
, starknet::get_execution_info().tx_info.account_contract_address
will return the set value.
Fully qualified path: core::starknet::testing::set_account_contract_address
pub fn set_account_contract_address(address: ContractAddress)
set_max_fee
Sets the transaction max fee. # Argumentsfee
- The max fee to set.After a call to set_max_fee
, starknet::get_execution_info().tx_info.max_fee
will return the set value.
Fully qualified path: core::starknet::testing::set_max_fee
pub fn set_max_fee(fee: u128)
set_transaction_hash
Sets the transaction hash. # Argumentshash
- The transaction hash to set.After a call to set_transaction_hash
, starknet::get_execution_info().tx_info.transaction_hash
will return the set value.
Fully qualified path: core::starknet::testing::set_transaction_hash
pub fn set_transaction_hash(hash: felt252)
set_chain_id
Set the transaction chain id. # Argumentschain_id
- The chain id to set.After a call to set_chain_id
, starknet::get_execution_info().tx_info.chain_id
will return the set value.
Fully qualified path: core::starknet::testing::set_chain_id
pub fn set_chain_id(chain_id: felt252)
set_nonce
Set the transaction nonce. # Argumentsnon
- The nonce to set.After a call to set_nonce
, starknet::get_execution_info().tx_info.nonce
will return the set value.
Fully qualified path: core::starknet::testing::set_nonce
pub fn set_nonce(nonce: felt252)
set_signature
Set the transaction signature. # Argumentssignature
- The signature to set.After a call to set_signature
, starknet::get_execution_info().tx_info.signature
will return the set value.
Fully qualified path: core::starknet::testing::set_signature
pub fn set_signature(signature: Span<felt252>)
set_block_hash
Set the hash for a block. # Argumentsblock_number
- The targeted block number. value
- The block hash to set.After a call to set_block_hash
, starknet::syscalls::get_block_hash_syscall
for the block_number will return the set value. Unset blocks values call would fail.
Fully qualified path: core::starknet::testing::set_block_hash
pub fn set_block_hash(block_number: u64, value: felt252)
pop_log_raw
Pop the earliest unpopped logged event for the contract. # Argumentsaddress
- The contract address from which to pop an event.The value is returned as a tuple of two spans, the first for the keys and the second for the data. May be called multiple times to pop multiple events. If called until None
is returned, all events have been popped.
Fully qualified path: core::starknet::testing::pop_log_raw
pub fn pop_log_raw(address: ContractAddress) -> Option<(Span<felt252>, Span<felt252>)>
pop_log
Pop the earliest unpopped logged event for the contract as the requested type. # Argumentsaddress
- The contract address from which to pop an event.Should be used when the type of the event is known. Type of the event should be the event defined within the contract. Useful for testing the contract's event emission. May be called multiple times to pop multiple events. If called until None
is returned, all events have been popped. # Examples
[starknet::contract]
mod contract {
[event]
[derive(Copy, Drop, Debug, PartialEq, starknet::Event)]
pub enum Event {
Event1: felt252,
Event2: u128,
}
...
}
[test]
fn test_event() {
let contract_address = somehow_get_contract_address();
call_code_causing_events(contract_address);
assert_eq!(
starknet::testing::pop_log(contract_address), Some(contract::Event::Event1(42))
);
assert_eq!(
starknet::testing::pop_log(contract_address), Some(contract::Event::Event2(41))
);
assert_eq!(
starknet::testing::pop_log(contract_address), Some(contract::Event::Event1(40))
);
assert_eq!(starknet::testing::pop_log_raw(contract_address), None);
}
Fully qualified path: core::starknet::testing::pop_log
pub fn pop_log<T, +starknet::Event<T>>(address: ContractAddress) -> Option<T>
pop_l2_to_l1_message
Pop the earliest unpopped l2 to l1 message for the contract. # Argumentsaddress
- The contract address from which to pop a l2-L1 message.The returned value is a tuple of the l1 address the message was sent to as a felt252
, and the message data as a span. May be called multiple times to pop multiple messages. Useful for testing the contract's l2 to l1 message emission.
Fully qualified path: core::starknet::testing::pop_l2_to_l1_message
pub fn pop_l2_to_l1_message(address: ContractAddress) -> Option<(felt252, Span<felt252>)>
Structs
u384
A 384-bit unsigned integer, used for circuit values.
Fully qualified path: core::circuit::u384
#[derive(Copy, Drop, Debug, PartialEq)]
pub struct u384 {
pub limb0: u96,
pub limb1: u96,
pub limb2: u96,
pub limb3: u96,
}
Members
limb0
The least significant 96 bits
Fully qualified path: core::circuit::u384::limb0
pub limb0: u96
limb1
Bits 96-191
Fully qualified path: core::circuit::u384::limb1
pub limb1: u96
limb2
Bits 192-287
Fully qualified path: core::circuit::u384::limb2
pub limb2: u96
limb3
The most significant 96 bits
Fully qualified path: core::circuit::u384::limb3
pub limb3: u96
CircuitElement
A wrapper for circuit elements, used to construct circuits.This type provides a generic wrapper around different circuit components (inputs, gates) and enables composition of circuit elements through arithmetic operations. The type parameter T
defines the specific role of the element in the circuit.
Fully qualified path: core::circuit::CircuitElement
pub struct CircuitElement<T> {}
Span
A span is a view into a contiguous collection of the same type - such as Array
. It is a structure with a single field that holds a snapshot of an array. Span
implements the Copy
and the Drop
traits.
Fully qualified path: core::array::Span
pub struct Span<T> {
pub(crate) snapshot: @Array<T>,
}
SpanIter
An iterator struct over a span collection.
Fully qualified path: core::array::SpanIter
pub struct SpanIter<T> {
span: Span<T>,
}
ArrayIter
An iterator struct over an array collection.
Fully qualified path: core::array::ArrayIter
#[derive(Drop)]
pub struct ArrayIter<T> {
array: Array<T>,
}
OptionIter
An iterator over the value in the Some
variant of an Option
.The iterator yields one value if the Option
is a Some
, otherwise none.This struct is created by the into_iter
method on Option
(provided by the IntoIterator
trait).
Fully qualified path: core::option::OptionIter
#[derive(Drop)]
pub struct OptionIter<T> {
inner: Option<T>,
}
u256
The 256-bit unsigned integer type.The u256
type is composed of two 128-bit parts: the low part [0, 128) and the high part [128, 256).
Fully qualified path: core::integer::u256
#[derive(Copy, Drop, Hash, PartialEq, Serde)]
pub struct u256 {
pub low: u128,
pub high: u128,
}
Members
low
Fully qualified path: core::integer::u256::low
pub low: u128
high
Fully qualified path: core::integer::u256::high
pub high: u128
u512
Fully qualified path: core::integer::u512
#[derive(Copy, Drop, Hash, PartialEq, Serde)]
pub struct u512 {
pub limb0: u128,
pub limb1: u128,
pub limb2: u128,
pub limb3: u128,
}
Members
limb0
Fully qualified path: core::integer::u512::limb0
pub limb0: u128
limb1
Fully qualified path: core::integer::u512::limb1
pub limb1: u128
limb2
Fully qualified path: core::integer::u512::limb2
pub limb2: u128
limb3
Fully qualified path: core::integer::u512::limb3
pub limb3: u128
Range
A (half-open) range bounded inclusively below and exclusively above (start..end
).The range start..end
contains all values with start <= x < end
. It is empty if start >= end
. # ExamplesThe start..end
syntax is a Range
:
assert!((3..5) == core::ops::Range { start: 3, end: 5 });
let mut sum = 0;
for i in 3..6 {
sum += i;
}
assert!(sum == 3 + 4 + 5);
Fully qualified path: core::ops::range::Range
#[derive(Clone, Drop, PartialEq)]
pub struct Range<T> {
pub start: T,
pub end: T,
}
Members
start
The lower bound of the range (inclusive).
Fully qualified path: core::ops::range::Range::start
pub start: T
end
The upper bound of the range (exclusive).
Fully qualified path: core::ops::range::Range::end
pub end: T
RangeInclusive
Represents the range [start, end](start, end).
Fully qualified path: core::ops::range::RangeInclusive
#[derive(Clone, Drop, PartialEq)]
pub struct RangeInclusive<T> {
pub start: T,
pub end: T,
}
Members
start
The lower bound of the range (inclusive).
Fully qualified path: core::ops::range::RangeInclusive::start
pub start: T
end
The upper bound of the range (inclusive).
Fully qualified path: core::ops::range::RangeInclusive::end
pub end: T
RangeInclusiveIterator
Fully qualified path: core::ops::range::RangeInclusiveIterator
#[derive(Clone, Drop)]
pub struct RangeInclusiveIterator<T> {
pub(crate) cur: T,
pub(crate) end: T,
pub(crate) exhausted: bool,
}
RangeIterator
Represents an iterator located at cur
, whose end is end
(cur <= end
).
Fully qualified path: core::ops::range::RangeIterator
#[derive(Clone, Drop, PartialEq)]
pub struct RangeIterator<T> {
cur: T,
end: T,
}
Panic
Represents a panic condition in Cairo.A Panic
is created when the program encounters an unrecoverable error condition and needs to terminate execution.
Fully qualified path: core::panics::Panic
pub struct Panic {}
HashState
Represents the current state of a Pedersen hash computation.The state is maintained as a single felt252
value, which is updated through the HashStateTrait::finalize
method.
Fully qualified path: core::pedersen::HashState
#[derive(Copy, Drop, Debug)]
pub struct HashState {
pub state: felt252,
}
Members
state
The current hash state
Fully qualified path: core::pedersen::HashState::state
pub state: felt252
HashState
State for Poseidon hash.
Fully qualified path: core::poseidon::HashState
#[derive(Copy, Drop, Debug)]
pub struct HashState {
pub s0: felt252,
pub s1: felt252,
pub s2: felt252,
pub odd: bool,
}
Members
s0
Fully qualified path: core::poseidon::HashState::s0
pub s0: felt252
s1
Fully qualified path: core::poseidon::HashState::s1
pub s1: felt252
s2
Fully qualified path: core::poseidon::HashState::s2
pub s2: felt252
odd
Fully qualified path: core::poseidon::HashState::odd
pub odd: bool
Error
Dedicated type for representing formatting errors.
Fully qualified path: core::fmt::Error
#[derive(Drop)]
pub struct Error {}
Formatter
Configuration for formatting.
Fully qualified path: core::fmt::Formatter
#[derive(Default, Drop)]
pub struct Formatter {
pub buffer: ByteArray,
}
Members
buffer
The pending result of formatting.
Fully qualified path: core::fmt::Formatter::buffer
pub buffer: ByteArray
EthAddress
An Ethereum address, 20 bytes in length.
Fully qualified path: core::starknet::eth_address::EthAddress
#[derive(Copy, Drop, Hash, PartialEq)]
pub struct EthAddress {
address: felt252,
}
ExecutionInfo
The same as ExecutionInfo
, but with the TxInfo
field replaced with v2::TxInfo
.
Fully qualified path: core::starknet::info::v2::ExecutionInfo
#[derive(Copy, Drop, Debug)]
pub struct ExecutionInfo {
pub block_info: Box<BlockInfo>,
pub tx_info: Box<TxInfo>,
pub caller_address: ContractAddress,
pub contract_address: ContractAddress,
pub entry_point_selector: felt252,
}
Members
block_info
Fully qualified path: core::starknet::info::v2::ExecutionInfo::block_info
pub block_info: Box<BlockInfo>
tx_info
Fully qualified path: core::starknet::info::v2::ExecutionInfo::tx_info
pub tx_info: Box<TxInfo>
caller_address
Fully qualified path: core::starknet::info::v2::ExecutionInfo::caller_address
pub caller_address: ContractAddress
contract_address
Fully qualified path: core::starknet::info::v2::ExecutionInfo::contract_address
pub contract_address: ContractAddress
entry_point_selector
Fully qualified path: core::starknet::info::v2::ExecutionInfo::entry_point_selector
pub entry_point_selector: felt252
ResourceBounds
V3 transactions resources used for enabling the fee market.
Fully qualified path: core::starknet::info::v2::ResourceBounds
#[derive(Copy, Drop, Debug, Serde)]
pub struct ResourceBounds {
pub resource: felt252,
pub max_amount: u64,
pub max_price_per_unit: u128,
}
Members
resource
The name of the resource.
Fully qualified path: core::starknet::info::v2::ResourceBounds::resource
pub resource: felt252
max_amount
The maximum amount of the resource allowed for usage during the execution.
Fully qualified path: core::starknet::info::v2::ResourceBounds::max_amount
pub max_amount: u64
max_price_per_unit
The maximum price the user is willing to pay for the resource unit.
Fully qualified path: core::starknet::info::v2::ResourceBounds::max_price_per_unit
pub max_price_per_unit: u128
TxInfo
Extended information about the current transaction.
Fully qualified path: core::starknet::info::v2::TxInfo
#[derive(Copy, Drop, Debug, Serde)]
pub struct TxInfo {
pub version: felt252,
pub account_contract_address: ContractAddress,
pub max_fee: u128,
pub signature: Span<felt252>,
pub transaction_hash: felt252,
pub chain_id: felt252,
pub nonce: felt252,
pub resource_bounds: Span<ResourceBounds>,
pub tip: u128,
pub paymaster_data: Span<felt252>,
pub nonce_data_availability_mode: u32,
pub fee_data_availability_mode: u32,
pub account_deployment_data: Span<felt252>,
}
Members
version
The version of the transaction. It is fixed (currently, 1) in the OS, and should be signed by the account contract. This field allows invalidating old transactions, whenever the meaning of the other transaction fields is changed (in the OS).
Fully qualified path: core::starknet::info::v2::TxInfo::version
pub version: felt252
account_contract_address
The account contract from which this transaction originates.
Fully qualified path: core::starknet::info::v2::TxInfo::account_contract_address
pub account_contract_address: ContractAddress
max_fee
The max_fee
field of the transaction.
Fully qualified path: core::starknet::info::v2::TxInfo::max_fee
pub max_fee: u128
signature
The signature of the transaction.
Fully qualified path: core::starknet::info::v2::TxInfo::signature
pub signature: Span<felt252>
transaction_hash
The hash of the transaction.
Fully qualified path: core::starknet::info::v2::TxInfo::transaction_hash
pub transaction_hash: felt252
chain_id
The identifier of the chain. This field can be used to prevent replay of testnet transactions on mainnet.
Fully qualified path: core::starknet::info::v2::TxInfo::chain_id
pub chain_id: felt252
nonce
The transaction's nonce.
Fully qualified path: core::starknet::info::v2::TxInfo::nonce
pub nonce: felt252
resource_bounds
A span of ResourceBounds
structs used for V3 transactions.
Fully qualified path: core::starknet::info::v2::TxInfo::resource_bounds
pub resource_bounds: Span<ResourceBounds>
tip
The tip of the transaction.
Fully qualified path: core::starknet::info::v2::TxInfo::tip
pub tip: u128
paymaster_data
If specified, the paymaster should pay for the execution of the transaction. The data includes the address of the paymaster sponsoring the transaction, followed by extra data to send to the paymaster. Used for V3 transactions.
Fully qualified path: core::starknet::info::v2::TxInfo::paymaster_data
pub paymaster_data: Span<felt252>
nonce_data_availability_mode
The data availability mode for the nonce. Used for V3 transactions.
Fully qualified path: core::starknet::info::v2::TxInfo::nonce_data_availability_mode
pub nonce_data_availability_mode: u32
fee_data_availability_mode
The data availability mode for the account balance from which fee will be taken. Used for V3 transactions.
Fully qualified path: core::starknet::info::v2::TxInfo::fee_data_availability_mode
pub fee_data_availability_mode: u32
account_deployment_data
If nonempty, will contain the required data for deploying and initializing an account contract: its class hash, address salt and constructor calldata. Used for V3 transactions.
Fully qualified path: core::starknet::info::v2::TxInfo::account_deployment_data
pub account_deployment_data: Span<felt252>
BlockInfo
Information about the current block.
Fully qualified path: core::starknet::info::BlockInfo
#[derive(Copy, Drop, Debug, Serde)]
pub struct BlockInfo {
pub block_number: u64,
pub block_timestamp: u64,
pub sequencer_address: ContractAddress,
}
Members
block_number
The number, that is, the height, of this block.
Fully qualified path: core::starknet::info::BlockInfo::block_number
pub block_number: u64
block_timestamp
The time at which the sequencer began building the block, in seconds since the Unix epoch.
Fully qualified path: core::starknet::info::BlockInfo::block_timestamp
pub block_timestamp: u64
sequencer_address
The Starknet address of the sequencer that created the block.
Fully qualified path: core::starknet::info::BlockInfo::sequencer_address
pub sequencer_address: ContractAddress
Signature
Represents a Secp256{k/r}1 ECDSA signature.This struct holds the components of an ECDSA signature: r
, s
, and y_parity
.
Fully qualified path: core::starknet::secp256_trait::Signature
#[derive(Copy, Drop, Debug, PartialEq, Serde, Hash)]
pub struct Signature {
pub r: u256,
pub s: u256,
pub y_parity: bool,
}
Members
r
Fully qualified path: core::starknet::secp256_trait::Signature::r
pub r: u256
s
Fully qualified path: core::starknet::secp256_trait::Signature::s
pub s: u256
y_parity
The parity of the y coordinate of the elliptic curve point whose x coordinate is r
. y_parity == true
means that the y coordinate is odd. Some places use non boolean v
instead of y_parity
. In that case, signature_from_vrs
should be used.
Fully qualified path: core::starknet::secp256_trait::Signature::y_parity
pub y_parity: bool
EthAddress
An Ethereum address, 20 bytes in length.
Fully qualified path: core::starknet::eth_address::EthAddress
#[derive(Copy, Drop, Hash, PartialEq)]
pub struct EthAddress {
address: felt252,
}
Call
A struct representing a call to a contract.
Fully qualified path: core::starknet::account::Call
#[derive(Drop, Copy, Serde, Debug)]
pub struct Call {
pub to: ContractAddress,
pub selector: felt252,
pub calldata: Span<felt252>,
}
Members
to
The address of the contract to call.
Fully qualified path: core::starknet::account::Call::to
pub to: ContractAddress
selector
The entry point selector in the called contract.
Fully qualified path: core::starknet::account::Call::selector
pub selector: felt252
calldata
The calldata to pass to entry point.
Fully qualified path: core::starknet::account::Call::calldata
pub calldata: Span<felt252>
AccountContractDispatcher
Fully qualified path: core::starknet::account::AccountContractDispatcher
#[derive(Copy, Drop, starknet::Store, Serde)]
pub struct AccountContractDispatcher {
pub contract_address: starknet::ContractAddress,
}
Members
contract_address
Fully qualified path: core::starknet::account::AccountContractDispatcher::contract_address
pub contract_address: starknet::ContractAddress
AccountContractLibraryDispatcher
Fully qualified path: core::starknet::account::AccountContractLibraryDispatcher
#[derive(Copy, Drop, starknet::Store, Serde)]
pub struct AccountContractLibraryDispatcher {
pub class_hash: starknet::ClassHash,
}
Members
class_hash
Fully qualified path: core::starknet::account::AccountContractLibraryDispatcher::class_hash
pub class_hash: starknet::ClassHash
AccountContractSafeLibraryDispatcher
Fully qualified path: core::starknet::account::AccountContractSafeLibraryDispatcher
#[derive(Copy, Drop, starknet::Store, Serde)]
pub struct AccountContractSafeLibraryDispatcher {
pub class_hash: starknet::ClassHash,
}
Members
class_hash
Fully qualified path: core::starknet::account::AccountContractSafeLibraryDispatcher::class_hash
pub class_hash: starknet::ClassHash
AccountContractSafeDispatcher
Fully qualified path: core::starknet::account::AccountContractSafeDispatcher
#[derive(Copy, Drop, starknet::Store, Serde)]
pub struct AccountContractSafeDispatcher {
pub contract_address: starknet::ContractAddress,
}
Members
contract_address
Fully qualified path: core::starknet::account::AccountContractSafeDispatcher::contract_address
pub contract_address: starknet::ContractAddress
StoragePointer
A pointer to an address in storage, can be used to read and write values, if the generic type supports it (e.g. basic types like felt252
).
Fully qualified path: core::starknet::storage::StoragePointer
pub struct StoragePointer<T> {
pub __storage_pointer_address__: StorageBaseAddress,
pub __storage_pointer_offset__: u8,
}
Members
storage_pointer_address
Fully qualified path: core::starknet::storage::StoragePointer::__storage_pointer_address__
pub __storage_pointer_address__: StorageBaseAddress
storage_pointer_offset
Fully qualified path: core::starknet::storage::StoragePointer::__storage_pointer_offset__
pub __storage_pointer_offset__: u8
StoragePointer0Offset
Same as StoragePointer
, but with offset
0, which allows for some optimizations.
Fully qualified path: core::starknet::storage::StoragePointer0Offset
pub struct StoragePointer0Offset<T> {
pub __storage_pointer_address__: StorageBaseAddress,
}
Members
storage_pointer_address
Fully qualified path: core::starknet::storage::StoragePointer0Offset::__storage_pointer_address__
pub __storage_pointer_address__: StorageBaseAddress
StoragePath
An intermediate struct to store a hash state, in order to be able to hash multiple values and get the final address. Storage path should have two interfaces, if T
is storable then it should implement StorageAsPointer
in order to be able to get the address of the storage path. Otherwise, if T
is not storable then it should implement some kind of updating trait, e.g. StoragePathEntry
.
Fully qualified path: core::starknet::storage::StoragePath
pub struct StoragePath<T> {
__hash_state__: StoragePathHashState,
}
PendingStoragePath
A struct for delaying the creation of a storage path, used for lazy evaluation in storage nodes.
Fully qualified path: core::starknet::storage::PendingStoragePath
pub struct PendingStoragePath<T> {
__hash_state__: StoragePathHashState,
__pending_key__: felt252,
}
Mutable
A wrapper around different storage related types, indicating that the instance is mutable, i.e. originally created from a ref
contract state.
Fully qualified path: core::starknet::storage::Mutable
#[phantom]
pub struct Mutable<T> {}
Map
A persistent key-value store in contract storage.This type cannot be instantiated as it is marked with #[phantom]
. This is by design: Map
is a compile-time type that only exists to provide type information for the compiler. It represents a mapping in storage, but the actual storage operations are handled by the StorageMapReadAccess
, StorageMapWriteAccess
, and StoragePathEntry
traits.
Fully qualified path: core::starknet::storage::map::Map
#[phantom]
pub struct Map<K, V> {}
FlattenedStorage
A type that represents a flattened storage, i.e. a storage object which does not have any effect on the path taken into consideration when computing the address of the storage object.
Fully qualified path: core::starknet::storage::storage_base::FlattenedStorage
pub struct FlattenedStorage<T> {}
StorageBase
A struct for holding an address to initialize a storage path with. The members (not direct members, but accessible using deref
) of a contract state are either StorageBase
or FlattenedStorage
instances, with the generic type representing the type of the stored member.
Fully qualified path: core::starknet::storage::storage_base::StorageBase
pub struct StorageBase<T> {
pub __base_address__: felt252,
}
Members
base_address
Fully qualified path: core::starknet::storage::storage_base::StorageBase::__base_address__
pub __base_address__: felt252
Vec
Represents a dynamic array in contract storage.This type is zero-sized and cannot be instantiated. Vectors can only be used in storage contexts and manipulated using the associated VecTrait
and MutableVecTrait
traits.
Fully qualified path: core::starknet::storage::vec::Vec
#[phantom]
pub struct Vec<T> {}
DropWith
Wrapper type to ensure that a type T
is dropped using a specific Drop
impl.
Fully qualified path: core::internal::DropWith
pub struct DropWith<T, impl DropT: Drop<T>> {
pub value: T,
}
Members
value
Fully qualified path: core::internal::DropWith::value
pub value: T
InferDrop
Helper to have the same interface as DropWith
while inferring the Drop
implementation.
Fully qualified path: core::internal::InferDrop
#[derive(Drop)]
pub struct InferDrop<T> {
pub value: T,
}
Members
value
Fully qualified path: core::internal::InferDrop::value
pub value: T
DestructWith
Wrapper type to ensure that a type T
is destructed using a specific Destruct
impl.
Fully qualified path: core::internal::DestructWith
pub struct DestructWith<T, impl DestructT: Destruct<T>> {
pub value: T,
}
Members
value
Fully qualified path: core::internal::DestructWith::value
pub value: T
InferDestruct
Helper to have the same interface as DestructWith
while inferring the Destruct
implementation.
Fully qualified path: core::internal::InferDestruct
#[derive(Destruct)]
pub struct InferDestruct<T> {
pub value: T,
}
Members
value
Fully qualified path: core::internal::InferDestruct::value
pub value: T
ByteArray
Byte array type.
Fully qualified path: core::byte_array::ByteArray
#[derive(Drop, Clone, PartialEq, Serde, Default)]
pub struct ByteArray {
pub(crate) data: Array<bytes31>,
pub(crate) pending_word: felt252,
pub(crate) pending_word_len: usize,
}
ByteArrayIter
An iterator struct over a ByteArray.
Fully qualified path: core::byte_array::ByteArrayIter
#[derive(Drop, Clone)]
pub struct ByteArrayIter {
ba: ByteArray,
current_index: crate::ops::RangeIterator<usize>,
}
Enums
bool
bool
enum representing either false
or true
.
Fully qualified path: core::bool
#[derive(Copy, Drop, Default)]
pub enum bool {
#[default]
False,
True,
}
Variants
False
Fully qualified path: core::bool::False
#[default]
False
True
Fully qualified path: core::bool::True
True
never
Fully qualified path: core::never
pub enum never {}
AddInputResult
The result of filling an input in the circuit instance's data.This enum represents the state of input filling process, indicating whether all inputs have been provided or more are needed.
Fully qualified path: core::circuit::AddInputResult
pub enum AddInputResult<C> {
Done: CircuitData<C>,
More: CircuitInputAccumulator<C>,
}
Variants
Done
All inputs have been filled and the circuit data is complete.
Fully qualified path: core::circuit::AddInputResult::Done
Done : CircuitData < C >
More
More inputs are needed to complete the circuit instance's data.
Fully qualified path: core::circuit::AddInputResult::More
More : CircuitInputAccumulator < C >
FromNullableResult
Represents the result of matching a Nullable
value.Used to safely handle both null and non-null cases when using match_nullable
on a Nullable
.
Fully qualified path: core::nullable::FromNullableResult
pub enum FromNullableResult<T> {
Null,
NotNull: Box<T>,
}
Variants
Null
Represents a null value
Fully qualified path: core::nullable::FromNullableResult::Null
Null
NotNull
The boxed value when not null
Fully qualified path: core::nullable::FromNullableResult::NotNull
NotNull : Box < T >
Result
The type used for returning and propagating errors. It is an enum with the variants Ok: T
, representing success and containing a value, and Err: E
, representing error and containing an error value.
Fully qualified path: core::result::Result
#[must_use]
#[derive(Copy, Drop, Debug, Serde, PartialEq)]
pub enum Result<T, E> {
Ok: T,
Err: E,
}
Variants
Ok
Fully qualified path: core::result::Result::Ok
Ok : T
Err
Fully qualified path: core::result::Result::Err
Err : E
Option
The Option<T>
enum representing either Some(value)
or None
.
Fully qualified path: core::option::Option
#[must_use]
#[derive(Copy, Drop, Debug, Serde, PartialEq)]
pub enum Option<T> {
Some: T,
None,
}
Variants
Some
Fully qualified path: core::option::Option::Some
Some : T
None
Fully qualified path: core::option::Option::None
None
PanicResult
Result type for operations that can trigger a panic.
Fully qualified path: core::panics::PanicResult
pub enum PanicResult<T> {
Ok: T,
Err: (Panic, Array<felt252>),
}
Variants
Ok
Fully qualified path: core::panics::PanicResult::Ok
Ok : T
Err
Fully qualified path: core::panics::PanicResult::Err
Err : ( Panic , Array < felt252 > )
OptionRev
Same as Option
, except that the order of the variants is reversed. This is used as the return type of some libfuncs for efficiency reasons.
Fully qualified path: core::internal::OptionRev
#[must_use]
#[derive(Copy, Drop, Debug, PartialEq)]
pub enum OptionRev<T> {
None,
Some: T,
}
Variants
None
Fully qualified path: core::internal::OptionRev::None
None
Some
Fully qualified path: core::internal::OptionRev::Some
Some : T
LoopResult
The return type for loops with an early return.
Fully qualified path: core::internal::LoopResult
pub enum LoopResult<N, E> {
Normal: N,
EarlyReturn: E,
}
Variants
Normal
Fully qualified path: core::internal::LoopResult::Normal
Normal : N
EarlyReturn
Fully qualified path: core::internal::LoopResult::EarlyReturn
EarlyReturn : E
Type aliases
usize
usize
is an alias for u32
type.
Fully qualified path: core::usize
pub type usize = u32;
u96
A 96-bit unsigned integer type used as the basic building block for multi-limb arithmetic.
Fully qualified path: core::circuit::u96
pub type u96 = crate::internal::bounded_int::BoundedInt<0, 79228162514264337593543950335>;
ConstZero
Expose the const required by the libfunc to allow the compiler const reusage.
Fully qualified path: core::circuit::ConstZero
pub type ConstZero = crate::internal::bounded_int::UnitInt<0>;
ConstOne
Fully qualified path: core::circuit::ConstOne
pub type ConstOne = crate::internal::bounded_int::UnitInt<1>;
NonZeroEcPoint
A non-zero point on the STARK curve (cannot be the point at infinity).
Fully qualified path: core::ec::NonZeroEcPoint
pub type NonZeroEcPoint = NonZero<EcPoint>;
SyscallResult
The Result
type for a syscall.
Fully qualified path: core::starknet::SyscallResult
pub type SyscallResult<T> = Result<T, Array<felt252>>;
Traits
Copy
A trait for copying values.By default, variables in Cairo have 'move semantics', meaning they are moved when used. However, types implementing Copy
have 'copy semantics', allowing the value to be duplicated instead of moved. # DerivingThis trait can be automatically derived using #[derive(Copy)]
. Most basic types implement Copy
by default. # ExamplesWithout Copy
(move semantics):
[derive(Drop)]
struct Point {
x: u128,
y: u128,
}
fn main() {
let p1 = Point { x: 5, y: 10 };
foo(p1);
foo(p1); // error: Variable was previously moved.
}
fn foo(p: Point) {}
With Copy
(copy semantics):
[derive(Copy, Drop)]
struct Point {
x: u128,
y: u128,
}
fn main() {
let p1 = Point { x: 5, y: 10 };
foo(p1);
foo(p1); // works: `p1` is copied when passed to `foo`
}
fn foo(p: Point) {}
Fully qualified path: core::traits::Copy
pub trait Copy<T>;
Drop
A trait for types that can be safely dropped.Types implementing Drop
can be automatically discarded when they go out of scope. The drop operation is a no-op - it simply indicates to the compiler that this type can be safely discarded. # DerivingThis trait can be automatically derived using #[derive(Drop)]
. All basic types implement Drop
by default, except for Felt252Dict
. # ExamplesWithout Drop
:
struct Point {
x: u128,
y: u128,
}
fn foo(p: Point) {} // Error: `p` cannot be dropped
With Drop
:
[derive(Drop)]
struct Point {
x: u128,
y: u128,
}
fn foo(p: Point) {} // OK: `p` is dropped at the end of the function
Fully qualified path: core::traits::Drop
pub trait Drop<T>;
Add
The addition operator +
. # ExamplesAdd
able types:
assert!(1_u8 + 2_u8 == 3_u8);
Implementing Add
for a type:
[derive(Copy, Drop, PartialEq)]
struct Point {
x: u32,
y: u32,
}
impl PointAdd of Add<Point> {
fn add(lhs: Point, rhs: Point) -> Point {
Point {
x: lhs.x + rhs.x,
y: lhs.y + rhs.y,
}
}
}
let p1 = Point { x: 1, y: 0 };
let p2 = Point { x: 2, y: 3 };
let p3 = p1 + p2;
assert!(p3 == Point { x: 3, y: 3 });
Fully qualified path: core::traits::Add
pub trait Add<T>
Trait functions
add
Performs the +
operation. # Examples
assert!(12 + 1 == 13);
Fully qualified path: core::traits::Add::add
fn add(lhs: T, rhs: T) -> T
AddEq
Fully qualified path: core::traits::AddEq
pub trait AddEq<T>
Trait functions
add_eq
Fully qualified path: core::traits::AddEq::add_eq
fn add_eq(ref self: T, other: T)
Sub
The subtraction operator -
. # ExamplesSub
tractable types:
assert!(3_u8 - 2_u8 == 1_u8);
Implementing Sub
for a type:
[derive(Copy, Drop, PartialEq)]
struct Point {
x: u32,
y: u32,
}
impl PointSub of Sub<Point> {
fn sub(lhs: Point, rhs: Point) -> Point {
Point {
x: lhs.x - rhs.x,
y: lhs.y - rhs.y,
}
}
}
let p1 = Point { x: 2, y: 3 };
let p2 = Point { x: 1, y: 0 };
let p3 = p1 - p2;
assert!(p3 == Point { x: 1, y: 3 });
Fully qualified path: core::traits::Sub
pub trait Sub<T>
Trait functions
sub
Performs the -
operation. # Examples
assert!(12 - 1 == 11);
Fully qualified path: core::traits::Sub::sub
fn sub(lhs: T, rhs: T) -> T
SubEq
Fully qualified path: core::traits::SubEq
pub trait SubEq<T>
Trait functions
sub_eq
Fully qualified path: core::traits::SubEq::sub_eq
fn sub_eq(ref self: T, other: T)
Mul
The multiplication operator *
. # ExamplesMul
tipliable types:
assert!(3_u8 * 2_u8 == 6_u8);
Implementing Mul
for a type:
[derive(Copy, Drop, PartialEq)]
struct Point {
x: u32,
y: u32,
}
impl PointMul of Mul<Point> {
fn mul(lhs: Point, rhs: Point) -> Point {
Point {
x: lhs.x * rhs.x,
y: lhs.y * rhs.y,
}
}
}
let p1 = Point { x: 2, y: 3 };
let p2 = Point { x: 1, y: 0 };
let p3 = p1 * p2;
assert!(p3 == Point { x: 2, y: 0 });
Fully qualified path: core::traits::Mul
pub trait Mul<T>
Trait functions
mul
Performs the *
operation. # Examples
assert!(12 * 2 == 24);
Fully qualified path: core::traits::Mul::mul
fn mul(lhs: T, rhs: T) -> T
MulEq
Fully qualified path: core::traits::MulEq
pub trait MulEq<T>
Trait functions
mul_eq
Fully qualified path: core::traits::MulEq::mul_eq
fn mul_eq(ref self: T, other: T)
Div
The division operator /
.Types implementing this trait support the division operation via the /
operator. # ExamplesDiv
isible types:
assert!(4_u8 / 2_u8 == 2_u8);
Implementing Div
for a type:
[derive(Copy, Drop, PartialEq)]
struct Point {
x: u32,
y: u32,
}
impl PointDiv of Div<Point> {
fn div(lhs: Point, rhs: Point) -> Point {
Point {
x: lhs.x / rhs.x,
y: lhs.y / rhs.y,
}
}
}
let p1 = Point { x: 2, y: 4 };
let p2 = Point { x: 2, y: 2 };
let p3 = p1 / p2;
assert!(p3 == Point { x: 1, y: 2 });
Fully qualified path: core::traits::Div
pub trait Div<T>
Trait functions
div
Performs the /
operation. # Examples
assert!(12 / 2 == 6);
Fully qualified path: core::traits::Div::div
fn div(lhs: T, rhs: T) -> T
DivEq
Fully qualified path: core::traits::DivEq
pub trait DivEq<T>
Trait functions
div_eq
Fully qualified path: core::traits::DivEq::div_eq
fn div_eq(ref self: T, other: T)
Rem
The remainder operator %
.Types implementing this trait support the remainder operation via the %
operator. # Examples
assert!(3_u8 % 2_u8 == 1_u8);
Fully qualified path: core::traits::Rem
pub trait Rem<T>
Trait functions
rem
Performs the %
operation. # Examples
assert!(12_u8 % 10_u8 == 2_u8);
Fully qualified path: core::traits::Rem::rem
fn rem(lhs: T, rhs: T) -> T
RemEq
Fully qualified path: core::traits::RemEq
pub trait RemEq<T>
Trait functions
rem_eq
Fully qualified path: core::traits::RemEq::rem_eq
fn rem_eq(ref self: T, other: T)
DivRem
Performs truncated division and remainder.This trait provides a way to efficiently compute both the quotient and remainder in a single operation. The division truncates towards zero, matching the behavior of the /
and %
operators. # Examples
assert!(DivRem::div_rem(7_u32, 3) == (2, 1));
Fully qualified path: core::traits::DivRem
pub trait DivRem<T>
Trait functions
div_rem
Performs the /
and the %
operations, returning both the quotient and remainder. # Examples
assert!(DivRem::div_rem(12_u32, 10) == (1, 2));
Fully qualified path: core::traits::DivRem::div_rem
fn div_rem(lhs: T, rhs: NonZero<T>) -> (T, T)
PartialEq
Trait for comparisons using the equality operator.Implementing this trait for types provides the ==
and !=
operators for those types. # DerivableThis trait can be used with #[derive]
. When derive
d on structs, two instances are equal if all fields are equal, and not equal if any fields are not equal. When derive
d on enums, two instances are equal if they are the same variant and all fields are equal. # Implementing PartialEq
An example in which two points are equal if their x and y coordinates are equal.
[derive(Copy, Drop)]
struct Point {
x: u32,
y: u32
}
impl PointEq of PartialEq<Point> {
fn eq(lhs: @Point, rhs: @Point) -> bool {
lhs.x == rhs.x && lhs.y == rhs.y
}
}
let p1 = Point { x: 1, y: 2 };
let p2 = Point { x: 1, y: 2 };
assert!(p1 == p2);
assert!(!(p1 != p2));
Fully qualified path: core::traits::PartialEq
pub trait PartialEq<T>
Trait functions
eq
Returns whether lhs
and rhs
equal, and is used by ==
. # Examples
assert!(1 == 1);
Fully qualified path: core::traits::PartialEq::eq
fn eq(lhs: @T, rhs: @T) -> bool
ne
Returns whether lhs
and rhs
are not equal, and is used by !=
. # Examples
assert!(0 != 1);
Fully qualified path: core::traits::PartialEq::ne
fn ne(lhs: @T, rhs: @T) -> bool
BitAnd
The bitwise AND operator &
. # ExamplesAn implementation of BitAnd
for a wrapper around bool
.
use core::traits::BitAnd;
[derive(Drop, PartialEq)]
struct Scalar {
inner: bool,
}
impl BitAndScalar of BitAnd<Scalar> {
fn bitand(lhs: Scalar, rhs: Scalar) -> Scalar {
Scalar { inner: lhs.inner & rhs.inner }
}
}
assert!(Scalar { inner: true } & Scalar { inner: true } == Scalar { inner: true });
assert!(Scalar { inner: true } & Scalar { inner: false } == Scalar { inner: false });
assert!(Scalar { inner: false } & Scalar { inner: true } == Scalar { inner: false });
assert!(Scalar { inner: false } & Scalar { inner: false } == Scalar { inner: false });
Fully qualified path: core::traits::BitAnd
pub trait BitAnd<T>
Trait functions
bitand
Performs the &
operation. # Examples
assert_eq!(true & false, false);
assert_eq!(5_u8 & 1_u8, 1);
assert_eq!(true & true, true);
assert_eq!(5_u8 & 2_u8, 0);
Fully qualified path: core::traits::BitAnd::bitand
fn bitand(lhs: T, rhs: T) -> T
BitOr
The bitwise OR operator |
. # ExamplesAn implementation of BitOr
for a wrapper around bool
.
use core::traits::BitOr;
[derive(Drop, PartialEq)]
struct Scalar {
inner: bool,
}
impl BitOrScalar of BitOr<Scalar> {
fn bitor(lhs: Scalar, rhs: Scalar) -> Scalar {
Scalar { inner: lhs.inner | rhs.inner }
}
}
assert!(Scalar { inner: true } | Scalar { inner: true } == Scalar { inner: true });
assert!(Scalar { inner: true } | Scalar { inner: false } == Scalar { inner: true });
assert!(Scalar { inner: false } | Scalar { inner: true } == Scalar { inner: true });
assert!(Scalar { inner: false } | Scalar { inner: false } == Scalar { inner: false });
Fully qualified path: core::traits::BitOr
pub trait BitOr<T>
Trait functions
bitor
Performs the |
operation. # Examples
assert!(1_u8 | 2_u8 == 3);
Fully qualified path: core::traits::BitOr::bitor
fn bitor(lhs: T, rhs: T) -> T
BitXor
The bitwise XOR operator ^
. # ExamplesAn implementation of BitXor
for a wrapper around bool
.
use core::traits::BitXor;
[derive(Drop, PartialEq)]
struct Scalar {
inner: bool,
}
impl BitXorScalar of BitXor<Scalar> {
fn bitxor(lhs: Scalar, rhs: Scalar) -> Scalar {
Scalar { inner: lhs.inner ^ rhs.inner }
}
}
assert!(Scalar { inner: true } ^ Scalar { inner: true } == Scalar { inner: false });
assert!(Scalar { inner: true } ^ Scalar { inner: false } == Scalar { inner: true });
assert!(Scalar { inner: false } ^ Scalar { inner: true } == Scalar { inner: true });
assert!(Scalar { inner: false } ^ Scalar { inner: false } == Scalar { inner: false });
Fully qualified path: core::traits::BitXor
pub trait BitXor<T>
Trait functions
bitxor
Performs the ^
operation. # Examples
assert!(1_u8 ^ 2_u8 == 3);
Fully qualified path: core::traits::BitXor::bitxor
fn bitxor(lhs: T, rhs: T) -> T
BitNot
The bitwise NOT operator ~
. # ExamplesAn implementation of BitNot
for a wrapper around u8
.
use core::traits::BitNot;
[derive(Drop, PartialEq)]
struct Wrapper {
u8: u8,
}
impl BitNotWrapper of BitNot<Wrapper> {
fn bitnot(a: Wrapper) -> Wrapper {
Wrapper { u8: ~a.u8 }
}
}
assert!(~Wrapper { u8: 0 } == Wrapper { u8 : 255 });
assert!(~Wrapper { u8: 1 } == Wrapper { u8 : 254 });
Fully qualified path: core::traits::BitNot
pub trait BitNot<T>
Trait functions
bitnot
Performs the ~
operation. # Examples
assert!(~1_u8 == 254);
Fully qualified path: core::traits::BitNot::bitnot
fn bitnot(a: T) -> T
PartialOrd
Trait for comparing types that form a partial order.The lt
, le
, gt
, and ge
methods of this trait can be called using the <
, <=
, >
, and >=
operators, respectively.PartialOrd is not derivable, but can be implemented manually # Implementing PartialOrd
Here's how to implement PartialOrd
for a custom type. This example implements comparison operations for a 2D point where points are compared based on their squared Euclidean distance from the origin (0,0):
[derive(Copy, Drop, PartialEq)]
struct Point {
x: u32,
y: u32,
}
impl PointPartialOrd of PartialOrd<Point> {
fn lt(lhs: Point, rhs: Point) -> bool {
let lhs_dist = lhs.x * lhs.x + lhs.y * lhs.y;
let rhs_dist = rhs.x * rhs.x + rhs.y * rhs.y;
lhs_dist < rhs_dist
}
}
let p1 = Point { x: 1, y: 1 }; // distance = 2
let p2 = Point { x: 2, y: 2 }; // distance = 8
assert!(p1 < p2);
assert!(p1 <= p2);
assert!(p2 > p1);
assert!(p2 >= p1);
Note that only the lt
method needs to be implemented. The other comparison operations (le
, gt
, ge
) are automatically derived from lt
. However, you can override them for better performance if needed.
Fully qualified path: core::traits::PartialOrd
pub trait PartialOrd<T>
Trait functions
lt
Tests less than (for self
and other
) and is used by the <
operator. # Examples
assert_eq!(1 < 1, false);
assert_eq!(1 < 2, true);
assert_eq!(2 < 1, false);
Fully qualified path: core::traits::PartialOrd::lt
fn lt(lhs: T, rhs: T) -> bool
ge
Tests less than or equal to (for self
and other
) and is used by the <=
operator. # Examples
assert_eq!(1 <= 1, true);
assert_eq!(1 <= 2, true);
assert_eq!(2 <= 1, false);
Fully qualified path: core::traits::PartialOrd::ge
fn ge(lhs: T, rhs: T) -> bool
gt
Tests greater than (for self
and other
) and is used by the >
operator. # Examples
assert_eq!(1 > 1, false);
assert_eq!(1 > 2, false);
assert_eq!(2 > 1, true);
Fully qualified path: core::traits::PartialOrd::gt
fn gt(lhs: T, rhs: T) -> bool
le
Tests greater than or equal to (for self
and other
) and is used by the >=
operator. # Examples
assert_eq!(1 >= 1, true);
assert_eq!(1 >= 2, false);
assert_eq!(2 >= 1, true);
Fully qualified path: core::traits::PartialOrd::le
fn le(lhs: T, rhs: T) -> bool
Into
A value-to-value conversion that consumes the input value.Note: This trait must not fail. If the conversion can fail, use TryInto
. # Generic ImplementationsInto
is reflexive, which means that Into<T, T>
is implemented # ExamplesConverting from RGB components to a packed color value:
[derive(Copy, Drop, PartialEq)]
struct Color {
// Packed as 0x00RRGGBB
value: u32,
}
impl RGBIntoColor of Into<(u8, u8, u8), Color> {
fn into(self: (u8, u8, u8)) -> Color {
let (r, g, b) = self;
let value = (r.into() * 0x10000_u32) +
(g.into() * 0x100_u32) +
b.into();
Color { value }
}
}
// Convert RGB(255, 128, 0) to 0x00FF8000
let orange: Color = (255_u8, 128_u8, 0_u8).into();
assert!(orange == Color { value: 0x00FF8000_u32 });
Fully qualified path: core::traits::Into
pub trait Into<T, S>
Trait functions
into
Converts the input type T into the output type S. # Examples
let a: u8 = 1;
let b: u16 = a.into();
Fully qualified path: core::traits::Into::into
fn into(self: T) -> S
TryInto
Simple and safe type conversions that may fail in a controlled way under some circumstances.This is useful when you are doing a type conversion that may trivially succeed but may also need special handling. For example, there is no way to convert an i64
into an i32
using the Into
trait, because an i64
may contain a value that an i32
cannot represent and so the conversion would lose data. This might be handled by truncating the i64
to an i32
or by simply returning Bounded::<i32>::MAX
, or by some other method. The Into
trait is intended for perfect conversions, so the TryInto
trait informs the programmer when a type conversion could go bad and lets them decide how to handle it. # Generic ImplementationsTryInto
is reflexive, which means that TryInto<T, T>
is implemented - TryInto
is implemented for all types that implement Into
# ExamplesConverting chess coordinates (like 'e4') into a validated position:
[derive(Copy, Drop, PartialEq)]
struct Position {
file: u8, // Column a-h (0-7)
rank: u8, // Row 1-8 (0-7)
}
impl TupleTryIntoPosition of TryInto<(u8, u8), Position> {
fn try_into(self: (u8, u8)) -> Option<Position> {
let (file_char, rank) = self;
// Validate rank is between 1 and 8
if rank < 1 || rank > 8 {
return None;
}
// Validate and convert file character (a-h) to number (0-7)
if file_char < 'a' || file_char > 'h' {
return None;
}
let file = file_char - 'a';
Some(Position {
file,
rank: rank - 1 // Convert 1-8 (chess notation) to 0-7 (internal index)
})
}
}
// Valid positions
let e4 = ('e', 4).try_into();
assert!(e4 == Some(Position { file: 4, rank: 3 }));
// Invalid positions
let invalid_file = ('x', 4).try_into();
let invalid_rank = ('a', 9).try_into();
assert!(invalid_file == None);
assert!(invalid_rank == None);
Fully qualified path: core::traits::TryInto
pub trait TryInto<T, S>
Trait functions
try_into
Attempts to convert the input type T into the output type S. In the event of a conversion error, returns None
. # Examples
let a: Option<u8> = 1_u16.try_into();
assert!(a == Some(1));
let b: Option<u8> = 256_u16.try_into();
assert!(b == None);
Fully qualified path: core::traits::TryInto::try_into
fn try_into(self: T) -> Option<S>
Neg
The unary negation operator -
. # ExamplesAn implementation of Neg
for Sign
, which allows the use of -
to negate its value.
[derive(Copy, Drop, PartialEq)]
enum Sign {
Negative,
Zero,
Positive,
}
impl SignNeg of Neg<Sign> {
fn neg(a: Sign) -> Sign {
match a {
Sign::Negative => Sign::Positive,
Sign::Zero => Sign::Zero,
Sign::Positive => Sign::Negative,
}
}
}
// A negative positive is a negative
assert!(-Sign::Positive == Sign::Negative);
// A double negative is a positive
assert!(-Sign::Negative == Sign::Positive);
// Zero is its own negation
assert!(-Sign::Zero == Sign::Zero);
Fully qualified path: core::traits::Neg
pub trait Neg<T>
Trait functions
neg
Performs the unary -
operation. # Examples
let x: i8 = 1;
assert!(-x == -1);
Fully qualified path: core::traits::Neg::neg
fn neg(a: T) -> T
Not
The unary logical negation operator !
. # ExamplesAn implementation of Not
for Answer
, which enables the use of !
to invert its value.
[derive(Drop, PartialEq)]
enum Answer {
Yes,
No,
}
impl AnswerNot of Not<Answer> {
fn not(a: Answer) -> Answer {
match a {
Answer::Yes => Answer::No,
Answer::No => Answer::Yes,
}
}
}
assert!(!Answer::Yes == Answer::No);
assert!(!Answer::No == Answer::Yes);
Fully qualified path: core::traits::Not
pub trait Not<T>
Trait functions
not
Performs the unary !
operation. # Examples
assert!(!true == false);
assert!(!false == true);
Fully qualified path: core::traits::Not::not
fn not(a: T) -> T
IndexView
Fully qualified path: core::traits::IndexView
pub trait IndexView<C, I, V>
Trait functions
index
Fully qualified path: core::traits::IndexView::index
fn index(self: @C, index: I) -> V
Index
Fully qualified path: core::traits::Index
pub trait Index<C, I, V>
Trait functions
index
Fully qualified path: core::traits::Index::index
fn index(ref self: C, index: I) -> V
Destruct
A trait that allows for custom destruction behavior of a type.In Cairo, values must be explicitly handled - they cannot be silently dropped. Types can only go out of scope in two ways: 1. Implement Drop
- for types that can be discarded trivially 2. Implement Destruct
- for types that need cleanup when destroyed. Typically, any type that contains a Felt252Dict
must implement Destruct
, as the Felt252Dict
needs to be "squashed" when going out of scope to ensure a program is sound.Generally, Destruct
does not need to be implemented manually. It can be derived from the Drop
and Destruct
implementations of the type's fields. # ExamplesHere's a simple type that wraps a Felt252Dict
and needs to be destructed:
use core::dict::Felt252Dict;
// A struct containing a Felt252Dict must implement Destruct
[derive(Destruct, Default)]
struct ResourceManager {
resources: Felt252Dict<u32>,
count: u32,
}
[generate_trait]
impl ResourceManagerImpl of ResourceManagerTrait{
fn add_resource(ref self: ResourceManager, resource_id: felt252, amount: u32){
assert!(self.resources.get(resource_id) == 0, "Resource already exists");
self.resources.insert(resource_id, amount);
self.count += amount;
}
}
let mut manager = Default::default();
// Add some resources
manager.add_resource(1, 100);
// When manager goes out of scope here, Destruct is automatically called,
// which ensures the dictionary is properly squashed
Fully qualified path: core::traits::Destruct
pub trait Destruct<T>
Trait functions
destruct
Fully qualified path: core::traits::Destruct::destruct
fn destruct(self: T) nopanic
PanicDestruct
A trait that allows for destruction of a value in case of a panic.This trait is automatically implemented from the Destruct
implementation for a type.
Fully qualified path: core::traits::PanicDestruct
pub trait PanicDestruct<T>
Trait functions
panic_destruct
Fully qualified path: core::traits::PanicDestruct::panic_destruct
fn panic_destruct(self: T, ref panic: Panic) nopanic
Default
A trait for giving a type a useful default value.Cairo implements Default
for various primitives types. # DerivableThis trait can be used with #[derive]
if all of the type's fields implement Default
. When derive
d, it will use the default value for each field's type. ## enum
sWhen using #[derive(Default)]
on an enum
, you need to choose which unit variant will be default. You do this by placing the #[default]
attribute on the variant.
[derive(Default)]
enum Kind {
[default]
A,
B,
C,
}
You can even use the #[default]
attribute even on non-unit variants, provided that the associated type implements Default
. # How can I implement Default
?Provide an implementation for the default()
method that returns the value of your type that should be the default:
[derive(Copy, Drop)]
enum Kind {
A,
B,
C,
}
impl DefaultKind of Default<Kind> {
fn default() -> Kind { Kind::A }
}
Examples#[derive(Drop, Default, PartialEq)](derive(Drop, Default, PartialEq)) struct SomeOptions {foo: i32,bar: u32,}assert!(Default::default() == SomeOptions { foo: 0, bar: 0 });
Fully qualified path: core::traits::Default
pub trait Default<T>
Trait functions
default
Returns the "default value" for a type.Default values are often some kind of initial value, identity value, or anything else that may make sense as a default. # Examples
let i: i8 = Default::default();
let (x, y): (Option<ByteArray>, u64) = Default::default();
let (a, b, (c, d)): (i32, u32, (bool, bool)) = Default::default();
Fully qualified path: core::traits::Default::default
fn default() -> T
Felt252DictValue
A trait that must be implemented for any type that will be stored as a value in a Felt252Dict
.When working with dictionaries in Cairo, we need a way to represent "empty" or "uninitialized" slots. This trait provides a zero-like default value that is returned when accessing a key that hasn't been explicitly set. # Why is this needed?The Felt252Dict
implementation needs to handle cases where a key hasn't been assigned a value yet. Instead of using Option
or similar constructs, it uses a zero-like value specific to each type.This trait is only implemented for primitive scalar types and Nullable<T>
. It cannot be implemented manually. Instead, if you want to use a custom type as a value in a dictionary, you can wrap your type in a Nullable
, which implements Felt252DictValue
for any wrapped type. # Examples
use core::dict::Felt252Dict;
[derive(Copy, Drop, Default)]
struct Counter {
value: u32,
}
// u8 already implements Felt252DictValue
let mut dict: Felt252Dict<u8> = Default::default();
assert!(dict.get(123) == 0);
// Counter is wrapped in a Nullable, as it doesn't implement Felt252DictValue
let mut counters: Felt252Dict<Nullable<Counter>> = Default::default();
// If the key is not set, `deref` would panic. `deref_or` returns the default value.
let maybe_counter: Nullable<Counter> = counters.get(123);
assert!(maybe_counter.deref_or(Default::default()).value == 0);
Fully qualified path: core::traits::Felt252DictValue
pub trait Felt252DictValue<T>
Trait functions
zero_default
Returns the default value for this type when used in a Felt252Dict
. This value should be logically equivalent to zero or an "empty" state.
Fully qualified path: core::traits::Felt252DictValue::zero_default
fn zero_default() -> T nopanic
BoolTrait
Fully qualified path: core::boolean::BoolTrait
pub trait BoolTrait<T, +Drop<T>>
Trait functions
then_some
Returns Some(t)
if the bool
is true
, None
otherwise. # Examples
assert!(false.then_some(0) == None);
assert!(true.then_some(0) == Some(0));
Fully qualified path: core::boolean::BoolTrait::then_some
fn then_some(self: bool, t: T) -> Option<T> nopanic
CircuitElementTrait
A marker trait for keeping track of which types are valid circuit elements.This trait is implemented for all valid circuit components including inputs and gates. It provides type safety when composing circuit elements.
Fully qualified path: core::circuit::CircuitElementTrait
pub trait CircuitElementTrait<T>
CircuitDefinition
A trait for defining a circuit's structure and behavior.This trait is used to define the structure of a circuit, including its inputs, gates, and outputs. It provides the foundation for circuit evaluation. The CES
type parameter represents a tuple of CircuitElement
s that together define the circuit's structure.
Fully qualified path: core::circuit::CircuitDefinition
pub trait CircuitDefinition<CES>
Trait types
CircuitType
The internal circuit type representing a tuple of CircuitElement
s.
Fully qualified path: core::circuit::CircuitDefinition::CircuitType
type CircuitType;
CircuitOutputsTrait
A trait for retrieving output values from a circuit evaluation.This trait provides methods to access the output values of a circuit after successful evaluation. # Examples
let a = CircuitElement::<CircuitInput<0>> {};
let b = CircuitElement::<CircuitInput<1>> {};
let modulus = TryInto::<_, CircuitModulus>::try_into([2, 0, 0, 0]).unwrap();
let circuit = (a,b).new_inputs()
.next([10, 0, 0, 0])
.next([11, 0, 0, 0])
.done()
.eval(modulus)
.unwrap();
let a_mod_2 = circuit.get_output(a); // Returns the output value of `a mod 2`
let b_mod_2 = circuit.get_output(b); // Returns the output value of `b mod 2`
assert!(a_mod_2 == 0.into());
assert!(b_mod_2 == 1.into());
Fully qualified path: core::circuit::CircuitOutputsTrait
pub trait CircuitOutputsTrait<Outputs, OutputElement>
Trait functions
get_output
Gets the output value for a specific circuit element. # Argumentsoutput
- The circuit element to get the output for # ReturnsThe output value as a u384
Fully qualified path: core::circuit::CircuitOutputsTrait::get_output
fn get_output(self: Outputs, output: OutputElement) -> u384
CircuitInputs
Fully qualified path: core::circuit::CircuitInputs
pub trait CircuitInputs<CES>
Trait functions
new_inputs
Initializes a new circuit instance with inputs.This function creates a new input accumulator for the circuit, which can then be used to add input values sequentially. # ReturnsAn AddInputResult
that can be used to add input values to the circuit
Fully qualified path: core::circuit::CircuitInputs::new_inputs
fn new_inputs<impl CD: CircuitDefinition<CES>, +Drop<CES>>(
self: CES,
) -> AddInputResult<CD::CircuitType>
AddInputResultTrait
Fully qualified path: core::circuit::AddInputResultTrait
pub trait AddInputResultTrait<C>
Trait functions
next
Adds an input value to the circuit instance. # Argumentsvalue
- The value to add as input, must be convertible to circuit input value # ReturnsA new AddInputResult
that can be used to add more inputs or finalize # PanicsPanics if all inputs have already been filled
Fully qualified path: core::circuit::AddInputResultTrait::next
fn next<Value, +IntoCircuitInputValue<Value>, +Drop<Value>>(
self: AddInputResult<C>, value: Value,
) -> AddInputResult<C>
done
Finalizes the input process and returns the circuit data. # ReturnsThe complete circuit data ready for evaluation # PanicsPanics if not all required inputs have been filled
Fully qualified path: core::circuit::AddInputResultTrait::done
fn done(self: AddInputResult<C>) -> CircuitData<C>
EvalCircuitTrait
Fully qualified path: core::circuit::EvalCircuitTrait
pub trait EvalCircuitTrait<C>
Trait functions
eval
Evaluates the circuit with the given modulus. # Argumentsmodulus
- The modulus to use for arithmetic operations # ReturnsResult containing either the circuit outputs or a failure indication
Fully qualified path: core::circuit::EvalCircuitTrait::eval
fn eval(self: CircuitData<C>, modulus: CircuitModulus) -> crate::circuit::EvalCircuitResult<C>
eval_ex
Evaluates the circuit with an explicit descriptor and modulus. # Argumentsdescriptor
- The circuit descriptor * modulus
- The modulus to use for arithmetic operations # ReturnsResult containing either the circuit outputs or a failure indication
Fully qualified path: core::circuit::EvalCircuitTrait::eval_ex
fn eval_ex(
self: CircuitData<C>, descriptor: CircuitDescriptor<C>, modulus: CircuitModulus,
) -> crate::circuit::EvalCircuitResult<C>
BoxTrait
Fully qualified path: core::box::BoxTrait
pub trait BoxTrait<T>
Trait functions
new
Creates a new Box
with the given value.Allocates space in the boxed segment for the provided value and returns a Box<T>
that points to it. # Examples
let x = 42;
let boxed_x = BoxTrait::new(x);
Fully qualified path: core::box::BoxTrait::new
fn new(value: T) -> Box<T> nopanic
unbox
Unboxes the given Box
and returns the wrapped value. # Examples
let boxed = BoxTrait::new(42);
assert!(boxed.unbox() == 42);
Fully qualified path: core::box::BoxTrait::unbox
fn unbox(self: Box<T>) -> T nopanic
as_snapshot
Converts the given snapshot of a Box
into a Box
of a snapshot. Useful for structures that aren't copyable. # Examples
let snap_boxed_arr = @BoxTraits::new(array![1, 2, 3]);
let boxed_snap_arr = snap_boxed_arr.as_snapshot();
let snap_arr = boxed_snap_arr.unbox();
Fully qualified path: core::box::BoxTrait::as_snapshot
fn as_snapshot(self: @Box<T>) -> Box<@T> nopanic
NullableTrait
Fully qualified path: core::nullable::NullableTrait
pub trait NullableTrait<T>
Trait functions
deref
Wrapper for Deref::deref
. Prefer using Deref::deref
directly.This function exists for backwards compatibility. # ExamplesPreferred way:
let value: Nullable<u32> = NullableTrait::new(42);
let unwrapped = value.deref();
This function method does the same thing:
use core::nullable::NullableTrait;
let also_unwrapped = NullableTrait::deref(value);
Fully qualified path: core::nullable::NullableTrait::deref
fn deref(nullable: Nullable<T>) -> T
deref_or
Returns the contained value if not null, or returns the provided default value. # Examples
let value: Nullable<u32> = NullableTrait::new(42);
assert!(value.deref_or(0) == 42);
let null_value: Nullable<u32> = Default::default();
assert!(null_value.deref_or(0) == 0);
Fully qualified path: core::nullable::NullableTrait::deref_or
fn deref_or<+Drop<T>>(self: Nullable<T>, default: T) -> T
new
Creates a new non-null Nullable
with the given value. # Examples
let value: Nullable<u32> = NullableTrait::new(42);
assert!(!value.is_null());
Fully qualified path: core::nullable::NullableTrait::new
fn new(value: T) -> Nullable<T>
is_null
Returns true
if the value is null. # Examples
let value: Nullable<u32> = NullableTrait::new(42);
assert!(!value.is_null());
let null_value: Nullable<u32> = Default::default();
assert!(null_value.is_null());
Fully qualified path: core::nullable::NullableTrait::is_null
fn is_null(self: @Nullable<T>) -> bool
as_snapshot
Creates a new Nullable
containing a snapshot of the value.This is useful when working with non-copyable types inside a Nullable
. This allows you to keep using the original value while also having access to a snapshot of it, preventing the original value from being moved. # Examples
let value: Nullable<Array<u32>> = NullableTrait::new(array![1, 2, 3]);
let res = (@value).as_snapshot();
assert!(res.deref() == @array![1, 2, 3]);
assert!(value.deref() == array![1, 2, 3]);
Fully qualified path: core::nullable::NullableTrait::as_snapshot
fn as_snapshot(self: @Nullable<T>) -> Nullable<@T> nopanic
ToSpanTrait
ToSpanTrait
converts a data structure into a span of its data.
Fully qualified path: core::array::ToSpanTrait
pub trait ToSpanTrait<C, T>
Trait functions
span
Returns a span pointing to the data in the input.
Fully qualified path: core::array::ToSpanTrait::span
fn span(self: @C) -> Span<T>
ArrayTrait
Fully qualified path: core::array::ArrayTrait
pub trait ArrayTrait<T>
Trait functions
new
Constructs a new, empty Array<T>
. # Examples
let arr: Array<u32> = ArrayTrait::new();
let arr = ArrayTrait::<u128>::new();
It is also possible to use the array!
macro to create a new array.
let arr: Array<bool> = array![];
Fully qualified path: core::array::ArrayTrait::new
fn new() -> Array<T> nopanic
append
Adds a value of type T
to the end of the array. # Examples
let mut arr: Array<u8> = array![1, 2];
arr.append(3);
assert!(arr == array![1, 2, 3]);
Fully qualified path: core::array::ArrayTrait::append
fn append(ref self: Array<T>, value: T) nopanic
append_span
Adds a span to the end of the array. # Examples
let mut arr: Array<u8> = array![];
arr.append_span(array![1, 2, 3].span());
assert!(arr == array![1, 2, 3]);
Fully qualified path: core::array::ArrayTrait::append_span
fn append_span<+Clone<T>, +Drop<T>>(ref self: Array<T>, span: Span<T>)
pop_front
Pops a value from the front of the array. Returns Some(value)
if the array is not empty, None
otherwise. # Examples
let mut arr = array![2, 3, 4];
assert!(arr.pop_front() == Some(2));
assert!(arr.pop_front() == Some(3));
assert!(arr.pop_front() == Some(4));
assert!(arr.pop_front().is_none());
Fully qualified path: core::array::ArrayTrait::pop_front
fn pop_front(ref self: Array<T>) -> Option<T> nopanic
pop_front_consume
Pops a value from the front of the array. Returns an option containing the remaining array and the value removed if the array is not empty, otherwise None
and drops the array. # Examples
let arr = array![2, 3, 4];
assert!(arr.pop_front_consume() == Some((array![3, 4], 2)));
let arr: Array<u8> = array![];
assert!(arr.pop_front_consume().is_none());
Fully qualified path: core::array::ArrayTrait::pop_front_consume
fn pop_front_consume(self: Array<T>) -> Option<(Array<T>, T)> nopanic
get
Returns an option containing a box of a snapshot of the element at the given 'index' if the array contains this index, 'None' otherwise.Element at index 0 is the front of the array. # Examples
let arr = array![2, 3, 4];
assert!(arr.get(1).unwrap().unbox() == @3);
Fully qualified path: core::array::ArrayTrait::get
fn get(self: @Array<T>, index: usize) -> Option<Box<@T>>
at
Returns a snapshot of the element at the given index.Element at index 0 is the front of the array. # PanicsPanics if the index is out of bounds. # Examples
let mut arr: Array<usize> = array![3,4,5,6];
assert!(arr.at(1) == @4);
Fully qualified path: core::array::ArrayTrait::at
fn at(self: @Array<T>, index: usize) -> @T
len
Returns the length of the array as a usize
value. # Examples
let arr = array![2, 3, 4];
assert!(arr.len() == 3);
Fully qualified path: core::array::ArrayTrait::len
fn len(self: @Array<T>) -> usize
is_empty
Returns whether the array is empty or not. # Examples
let mut arr = array![];
assert!(arr.is_empty());
arr.append(1);
assert!(!arr.is_empty());
Fully qualified path: core::array::ArrayTrait::is_empty
fn is_empty(self: @Array<T>) -> bool
span
Returns a span of the array. # Examples
let arr: Array<u8> = array![1, 2, 3];
let span: Span<u8> = arr.span();
Fully qualified path: core::array::ArrayTrait::span
fn span(snapshot: @Array<T>) -> Span<T>
SpanTrait
Fully qualified path: core::array::SpanTrait
pub trait SpanTrait<T>
Trait functions
pop_front
Pops a value from the front of the span. Returns Some(@value)
if the array is not empty, None
otherwise. # Examples
let mut span = array![1, 2, 3].span();
assert!(span.pop_front() == Some(@1));
Fully qualified path: core::array::SpanTrait::pop_front
fn pop_front(ref self: Span<T>) -> Option<@T>
pop_back
Pops a value from the back of the span. Returns Some(@value)
if the array is not empty, None
otherwise. # Examples
let mut span = array![1, 2, 3].span();
assert!(span.pop_back() == Some(@3));
Fully qualified path: core::array::SpanTrait::pop_back
fn pop_back(ref self: Span<T>) -> Option<@T>
multi_pop_front
Pops multiple values from the front of the span. Returns an option containing a snapshot of a box that contains the values as a fixed-size array if the action completed successfully, 'None' otherwise. # Examples
let mut span = array![1, 2, 3].span();
let result = *(span.multi_pop_front::<2>().unwrap());
let unboxed_result = result.unbox();
assert!(unboxed_result == [1, 2]);
Fully qualified path: core::array::SpanTrait::multi_pop_front
fn multi_pop_front<const SIZE: usize>(ref self: Span<T>) -> Option<@Box<[T; SIZE]>>
multi_pop_back
Pops multiple values from the back of the span. Returns an option containing a snapshot of a box that contains the values as a fixed-size array if the action completed successfully, 'None' otherwise. # Examples
let mut span = array![1, 2, 3].span();
let result = *(span.multi_pop_back::<2>().unwrap());
let unboxed_result = result.unbox();
assert!(unboxed_result == [2, 3]);
Fully qualified path: core::array::SpanTrait::multi_pop_back
fn multi_pop_back<const SIZE: usize>(ref self: Span<T>) -> Option<@Box<[T; SIZE]>>
get
Returns an option containing a box of a snapshot of the element at the given 'index' if the span contains this index, 'None' otherwise.Element at index 0 is the front of the array. # Examples
let span = array![2, 3, 4];
assert!(span.get(1).unwrap().unbox() == @3);
Fully qualified path: core::array::SpanTrait::get
fn get(self: Span<T>, index: usize) -> Option<Box<@T>>
at
Returns a snapshot of the element at the given index.Element at index 0 is the front of the array. # PanicsPanics if the index is out of bounds. # Examples
let span = array![2, 3, 4].span();
assert!(span.at(1) == @3);
Fully qualified path: core::array::SpanTrait::at
fn at(self: Span<T>, index: usize) -> @T
slice
Returns a span containing values from the 'start' index, with amount equal to 'length'. # Examples
let span = array![1, 2, 3].span();
assert!(span.slice(1, 2) == array![2, 3].span());
Fully qualified path: core::array::SpanTrait::slice
fn slice(self: Span<T>, start: usize, length: usize) -> Span<T>
len
Returns the length of the span as a usize
value. # Examples
let span = array![2, 3, 4].span();
assert!(span.len() == 3);
Fully qualified path: core::array::SpanTrait::len
fn len(self: Span<T>) -> usize
is_empty
Returns whether the span is empty or not. # Examples
let span: Span<felt252> = array![].span();
assert!(span.is_empty());
let span = array![1, 2, 3].span();
assert!(!span.is_empty());
Fully qualified path: core::array::SpanTrait::is_empty
fn is_empty(self: Span<T>) -> bool
Felt252DictTrait
Basic trait for the Felt252Dict
type.
Fully qualified path: core::dict::Felt252DictTrait
pub trait Felt252DictTrait<T>
Trait functions
insert
Inserts the given value for the given key. # Examples
use core::dict::Felt252Dict;
let mut dict: Felt252Dict<u8> = Default::default();
dict.insert(0, 10);
Fully qualified path: core::dict::Felt252DictTrait::insert
fn insert<+Destruct<T>>(ref self: Felt252Dict<T>, key: felt252, value: T)
get
Returns the value stored at the given key. If no value was previously inserted at this key, returns the default value for type T. # Examples
use core::dict::Felt252Dict;
let mut dict: Felt252Dict<u8> = Default::default();
dict.insert(0, 10);
let value = dict.get(0);
assert!(value == 10);
Fully qualified path: core::dict::Felt252DictTrait::get
fn get<+Copy<T>>(ref self: Felt252Dict<T>, key: felt252) -> T
squash
Squashes a dictionary and returns the associated SquashedFelt252Dict
. # Examples
use core::dict::Felt252Dict;
let mut dict: Felt252Dict<u8> = Default::default();
dict.insert(0, 10);
let squashed_dict = dict.squash();
Fully qualified path: core::dict::Felt252DictTrait::squash
fn squash(self: Felt252Dict<T>) -> SquashedFelt252Dict<T> nopanic
entry
Retrieves the last entry for a certain key. This method takes ownership of the dictionary and returns the entry to update, as well as the previous value at the given key. # Examples
use core::dict::Felt252Dict;
let mut dict: Felt252Dict<u8> = Default::default();
dict.insert(0, 10);
let (entry, prev_value) = dict.entry(0);
assert!(prev_value == 10);
Fully qualified path: core::dict::Felt252DictTrait::entry
fn entry(self: Felt252Dict<T>, key: felt252) -> (Felt252DictEntry<T>, T) nopanic
Felt252DictEntryTrait
Basic trait for the Felt252DictEntryTrait
type.
Fully qualified path: core::dict::Felt252DictEntryTrait
pub trait Felt252DictEntryTrait<T>
Trait functions
finalize
Finalizes the changes made to a dictionary entry and gives back the ownership of the dictionary. # Examples
use core::dict::Felt252DictEntryTrait;
// Create a dictionary that stores arrays
let mut dict: Felt252Dict<Nullable<Array<felt252>>> = Default::default();
let a = array![1, 2, 3];
dict.insert(0, NullableTrait::new(a));
let (entry, prev_value) = dict.entry(0);
let new_value = NullableTrait::new(array![4, 5, 6]);
dict = entry.finalize(new_value);
assert!(prev_value == a);
assert!(dict.get(0) == new_value);
Fully qualified path: core::dict::Felt252DictEntryTrait::finalize
fn finalize(self: Felt252DictEntry<T>, new_value: T) -> Felt252Dict<T>
SquashedFelt252DictTrait
Fully qualified path: core::dict::SquashedFelt252DictTrait
pub trait SquashedFelt252DictTrait<T>
Trait functions
into_entries
Returns an array of (key, first_value, last_value)
tuples. The first value is always 0. # Example
let squashed_dict = dict.squash();
let entries = squashed_dict.entries();
Fully qualified path: core::dict::SquashedFelt252DictTrait::into_entries
fn into_entries(self: SquashedFelt252Dict<T>) -> Array<(felt252, T, T)>
ResultTrait
Fully qualified path: core::result::ResultTrait
pub trait ResultTrait<T, E>
Trait functions
expect
Returns the contained Ok
value, consuming the self
value. # PanicsPanics if the value is an Err
, with the provided felt252
panic message. # Examples
let result: Result<felt252, felt252> = Ok(123);
assert!(result.expect('no value') == 123);
Fully qualified path: core::result::ResultTrait::expect
const fn expect<+PanicDestruct<E>>(self: Result<T, E>, err: felt252) -> T
unwrap
Returns the contained Ok
value, consuming the self
value. # PanicsPanics if the value is an Err
, with a standard Result::unwrap failed
panic message. # Examples
let result: Result<felt252, felt252> = Ok(123);
assert!(result.unwrap() == 123);
Fully qualified path: core::result::ResultTrait::unwrap
const fn unwrap<+Destruct<E>>(self: Result<T, E>) -> T
unwrap_or
Returns the contained Ok
value or a provided default. # Examples
let result: Result<felt252, felt252> = Ok(123);
assert!(result.unwrap_or(456) == 123);
let result: Result<felt252, felt252> = Err('no value');
assert!(result.unwrap_or(456) == 456);
Fully qualified path: core::result::ResultTrait::unwrap_or
const fn unwrap_or<+Destruct<T>, +Destruct<E>>(self: Result<T, E>, default: T) -> T
unwrap_or_default
Returns the contained Ok
value or Default::<T>::default()
. # Examples
let result: Result<felt252, felt252> = Ok(123);
assert!(result.unwrap_or_default() == 123);
let result: Result<felt252, felt252> = Err('no value');
assert!(result.unwrap_or_default() == 0);
Fully qualified path: core::result::ResultTrait::unwrap_or_default
fn unwrap_or_default<+Destruct<E>, +Default<T>>(self: Result<T, E>) -> T
unwrap_or_else
Returns the contained Ok
value or computes it from a closure. # Examples
assert!(Ok(2).unwrap_or_else(|e: ByteArray| e.len()) == 2);
assert!(Err("foo").unwrap_or_else(|e: ByteArray| e.len()) == 3);
Fully qualified path: core::result::ResultTrait::unwrap_or_else
fn unwrap_or_else<F, +Destruct<E>, +Drop<F>, +core::ops::FnOnce<F, (E,)>[Output: T]>(
self: Result<T, E>, f: F,
) -> T
and
Returns other
if the result is Ok
, otherwise returns the Err
value of self
. # Examples
let x: Result<u32, ByteArray> = Ok(2);
let y: Result<ByteArray, ByteArray> = Err("late error");
assert!(x.and(y) == Err("late error"));
let x: Result<u32, ByteArray> = Err("early error");
let y: Result<ByteArray, ByteArray> = Ok("foo");
assert!(x.and(y) == Err("early error"));
let x: Result<u32, ByteArray> = Err("not a 2");
let y: Result<ByteArray, ByteArray> = Err("late error");
assert!(x.and(y) == Err("not a 2"));
let x: Result<u32, ByteArray> = Ok(2);
let y: Result<ByteArray, ByteArray> = Ok("different result type");
assert!(x.and(y) == Ok("different result type"));
Fully qualified path: core::result::ResultTrait::and
fn and<U, +Destruct<T>, +Drop<E>, +Drop<U>>(self: Result<T, E>, other: Result<U, E>) -> Result<U, E>
and_then
Calls op
if the result is Ok
, otherwise returns the Err
value of self
.This function can be used for control flow based on Result
values. # Examples
use core::num::traits::CheckedMul;
fn sq_then_string(x: u32) -> Result<ByteArray, ByteArray> {
let res = x.checked_mul(x).ok_or("overflowed");
res.and_then(|v| Ok(format!("{}", v)))
}
let x = sq_then_string(4);
assert!(x == Ok("16"));
let y = sq_then_string(65536);
assert!(y == Err("overflowed"));
Fully qualified path: core::result::ResultTrait::and_then
fn and_then<U, F, +Drop<F>, +core::ops::FnOnce<F, (T,)>[Output: Result<U, E>]>(
self: Result<T, E>, op: F,
) -> Result<U, E>
or
Returns other
if the result is Err
, otherwise returns the Ok
value of self
. # Examples
let x: Result<u32, ByteArray> = Ok(2);
let y: Result<u32, ByteArray> = Err("late error");
assert!(x.or(y) == Ok(2));
let x: Result<u32, ByteArray> = Err("early error");
let y: Result<u32, ByteArray> = Ok(2);
assert!(x.or(y) == Ok(2));
let x: Result<u32, ByteArray> = Err("not a 2");
let y: Result<u32, ByteArray> = Err("late error");
assert!(x.or(y) == Err("late error"));
let x: Result<u32, ByteArray> = Ok(2);
let y: Result<u32, ByteArray> = Ok(100);
assert!(x.or(y) == Ok(2));
Fully qualified path: core::result::ResultTrait::or
fn or<F, +Drop<T>, +Drop<F>, +Destruct<E>>(self: Result<T, E>, other: Result<T, F>) -> Result<T, F>
or_else
Calls op
if the result is Err
, otherwise returns the Ok
value of self
.This function can be used for control flow based on result values. # Examples
let x: Result::<u32, ByteArray> = Result::<u32, ByteArray>::Err("bad input")
.or_else(|_e| Ok(42));
assert!(x == Ok(42));
let y: Result::<u32, ByteArray> = Result::<u32, ByteArray>::Err("bad input")
.or_else(|_e| Err("not 42"));
assert!(y == Err("not 42"));
let z: Result::<u32, ByteArray> = Result::<u32, ByteArray>::Ok(100)
.or_else(|_e| Ok(42));
assert!(z == Ok(100));
Fully qualified path: core::result::ResultTrait::or_else
fn or_else<F, O, +Drop<O>, +core::ops::FnOnce<O, (E,)>[Output: Result<T, F>]>(
self: Result<T, E>, op: O,
) -> Result<T, F>
expect_err
Returns the contained Err
value, consuming the self
value. # PanicsPanics if the value is an Ok
, with the provided felt252
panic message. # Examples
let result: Result<felt252, felt252> = Err('no value');
assert!(result.expect_err('result is ok') == 'no value');
Fully qualified path: core::result::ResultTrait::expect_err
const fn expect_err<+PanicDestruct<T>>(self: Result<T, E>, err: felt252) -> E
unwrap_err
Returns the contained Err
value, consuming the self
value. # PanicsPanics if the value is an Ok
, with a standard Result::unwrap_err failed.
panic message. # Examples
let result: Result<felt252, felt252> = Err('no value');
assert!(result.unwrap_err() == 'no value');
Fully qualified path: core::result::ResultTrait::unwrap_err
const fn unwrap_err<+PanicDestruct<T>>(self: Result<T, E>) -> E
is_ok
Returns true
if the Result
is Ok
. # Examples
let result: Result<felt252, felt252> = Ok(123);
assert!(result.is_ok());
Fully qualified path: core::result::ResultTrait::is_ok
fn is_ok(self: @Result<T, E>) -> bool
is_err
Returns true
if the Result
is Err
. # Examples
let result: Result<felt252, felt252> = Ok(123);
assert!(!result.is_err());
Fully qualified path: core::result::ResultTrait::is_err
fn is_err(self: @Result<T, E>) -> bool
into_is_ok
Returns true
if the Result
is Ok
, and consumes the value. # Examples
let result: Result<felt252, felt252> = Ok(123);
assert!(result.into_is_ok());
Fully qualified path: core::result::ResultTrait::into_is_ok
fn into_is_ok<+Destruct<T>, +Destruct<E>>(self: Result<T, E>) -> bool
into_is_err
Returns true
if the Result
is Err
, and consumes the value. # Examples
let result: Result<felt252, felt252> = Ok(123);
assert!(!result.into_is_err());
Fully qualified path: core::result::ResultTrait::into_is_err
fn into_is_err<+Destruct<T>, +Destruct<E>>(self: Result<T, E>) -> bool
ok
Converts from Result<T, E>
to Option<T>
.Converts self
into an Option<T>
, consuming self
, and discarding the error, if any. # Examples
let x: Result<u32, ByteArray> = Ok(2);
assert!(x.ok() == Some(2));
let x: Result<u32, ByteArray> = Err("Nothing here");
assert!(x.ok().is_none());
Fully qualified path: core::result::ResultTrait::ok
fn ok<+Destruct<T>, +Destruct<E>>(self: Result<T, E>) -> Option<T>
err
Converts from Result<T, E>
to Option<E>
.Converts self
into an Option<E>
, consuming self
, and discarding the success value, if any. # Examples
let x: Result<u32, ByteArray> = Err("Nothing here");
assert!(x.err() == Some("Nothing here"));
let x: Result<u32, ByteArray> = Ok(2);
assert!(x.err().is_none());
Fully qualified path: core::result::ResultTrait::err
fn err<+Destruct<T>, +Destruct<E>>(self: Result<T, E>) -> Option<E>
map
Maps a Result<T, E>
to Result<U, E>
by applying a function to a contained Ok
value, leaving an Err
value untouched.This function can be used to compose the results of two functions. # ExamplesPrint the square of the number contained in the Result
, otherwise print the error.
let inputs: Array<Result<u32, ByteArray>> = array![
Ok(1), Err("error"), Ok(3), Ok(4),
];
for i in inputs {
match i.map(|i| i * 2) {
Ok(x) => println!("{x}"),
Err(e) => println!("{e}"),
}
}
Fully qualified path: core::result::ResultTrait::map
fn map<U, F, +Drop<F>, +core::ops::FnOnce<F, (T,)>[Output: U]>(
self: Result<T, E>, f: F,
) -> Result<U, E>
map_or
Returns the provided default (if Err
), or applies a function to the contained value (if Ok
). # Examples
let x: Result<_, ByteArray> = Ok("foo");
assert!(x.map_or(42, |v: ByteArray| v.len()) == 3);
let x: Result<_, ByteArray> = Err("bar");
assert!(x.map_or(42, |v: ByteArray| v.len()) == 42);
Fully qualified path: core::result::ResultTrait::map_or
fn map_or<U, F, +Destruct<E>, +Destruct<U>, +Drop<F>, +core::ops::FnOnce<F, (T,)>[Output: U]>(
self: Result<T, E>, default: U, f: F,
) -> U
map_or_else
Maps a Result<T, E>
to U
by applying fallback function default
to a contained Err
value, or function f
to a contained Ok
value.This function can be used to unpack a successful result while handling an error. # Examples
let k = 21;
let x: Result<ByteArray, _> = Ok("foo");
assert!(x.map_or_else(|_e: ByteArray| k * 2, |v: ByteArray| v.len()) == 3);
let x: Result<_, ByteArray> = Err("bar");
assert!(x.map_or_else(|_e: ByteArray| k * 2, |v: ByteArray| v.len()) == 42);
Fully qualified path: core::result::ResultTrait::map_or_else
fn map_or_else<
U,
D,
F,
+Drop<D>,
+Drop<F>,
+core::ops::FnOnce<D, (E,)>[Output: U],
+core::ops::FnOnce<F, (T,)>[Output: U],
>(
self: Result<T, E>, default: D, f: F,
) -> U
map_err
Maps a Result<T, E>
to Result<T, F>
by applying a function to a contained Err
value, leaving an Ok
value untouched.This function can be used to pass through a successful result while handling an error. # Examples
let stringify = |x: u32| -> ByteArray { format!("error code: {x}") };
let x: Result<u32, u32> = Ok(2);
assert!(x.map_err(stringify) == Result::<u32, ByteArray>::Ok(2));
let x: Result<u32, u32> = Err(13);
assert!(x.map_err(stringify) == Err("error code: 13"));
Fully qualified path: core::result::ResultTrait::map_err
fn map_err<F, O, +Drop<O>, +core::ops::FnOnce<O, (E,)>[Output: F]>(
self: Result<T, E>, op: O,
) -> Result<T, F>
OptionTrait
A trait for handling Option<T>
related operations.
Fully qualified path: core::option::OptionTrait
pub trait OptionTrait<T>
Trait functions
expect
Returns the contained Some
value, consuming the self
value. # PanicsPanics if the option value is None
with a custom felt252
panic message err
. # Examples
let option = Some(123);
let value = option.expect('no value');
assert!(value == 123);
Fully qualified path: core::option::OptionTrait::expect
const fn expect(self: Option<T>, err: felt252) -> T
unwrap
Returns the contained Some
value, consuming the self
value. # PanicsPanics if the self
value equals None
. # Examples
let option = Some(123);
let value = option.unwrap();
assert!(value == 123);
Fully qualified path: core::option::OptionTrait::unwrap
const fn unwrap(self: Option<T>) -> T
ok_or
Transforms the Option<T>
into a Result<T, E>
, mapping Some(v)
to Ok(v)
and None
to Err(err)
. # Examples
assert_eq!(Some('foo').ok_or(0), Ok('foo'));
let option: Option<felt252> = None;
assert_eq!(option.ok_or(0), Err(0));
Fully qualified path: core::option::OptionTrait::ok_or
fn ok_or<E, +Destruct<E>>(self: Option<T>, err: E) -> Result<T, E>
ok_or_else
Transforms the Option<T>
into a Result<T, E>
, mapping Some(v)
to Ok(v)
and None
to Err(err())
. # Examples
assert_eq!(Some('foo').ok_or_else(|| 0), Ok('foo'));
let option: Option<felt252> = None;
assert_eq!(option.ok_or_else(|| 0), Err(0));
Fully qualified path: core::option::OptionTrait::ok_or_else
fn ok_or_else<E, F, +Destruct<E>, +core::ops::FnOnce<F, ()>[Output: E], +Drop<F>>(
self: Option<T>, err: F,
) -> Result<T, E>
and
Returns None
if the option is None
, otherwise returns optb
.Arguments passed to and
are eagerly evaluated; if you are passing the result of a function call, it is recommended to use and_then
, which is lazily evaluated. # Examples
let x = Some(2);
let y: Option<ByteArray> = None;
assert_eq!(x.and(y), None);
let x: Option<u32> = None;
let y: Option<ByteArray> = Some("foo");
assert_eq!(x.and(y), None);
let x = Some(2);
let y: Option<ByteArray> = Some("foo");
assert_eq!(x.and(y), Some("foo"));
let x: Option<u32> = None;
let y: Option<ByteArray> = None;
assert_eq!(x.and(y), None);
Fully qualified path: core::option::OptionTrait::and
fn and<U, +Drop<T>, +Drop<U>>(self: Option<T>, optb: Option<U>) -> Option<U>
and_then
Returns None
if the option is None
, otherwise calls f
with the wrapped value and returns the result.Some languages call this operation flatmap. # Examples
use core::num::traits::CheckedMul;
let option: Option<ByteArray> = checked_mul(2_u32, 2_u32)
.and_then(|v| Some(format!("{}", v)));
assert_eq!(option, Some("4"));
let option: Option<ByteArray> = checked_mul(65536_u32, 65536_u32)
.and_then(|v| Some(format!("{}", v)));
assert_eq!(option, None); // overflowed!
let option: Option<ByteArray> = Option::<u32>::None
.and_then(|v| Some(format!("{}", v)));
assert_eq!(option, None);
Fully qualified path: core::option::OptionTrait::and_then
fn and_then<U, F, +Drop<F>, +core::ops::FnOnce<F, (T,)>[Output: Option<U>]>(
self: Option<T>, f: F,
) -> Option<U>
or
Returns the option if it contains a value, otherwise returns optb
.Arguments passed to or
are eagerly evaluated; if you are passing the result of a function call, it is recommended to use or_else
, which is lazily evaluated. # Examples
let x = Some(2);
let y = None;
assert_eq!(x.or(y), Some(2));
let x = None;
let y = Some(100);
assert_eq!(x.or(y), Some(100));
let x = Some(2);
let y = Some(100);
assert_eq!(x.or(y), Some(2));
let x: Option<u32> = None;
let y = None;
assert_eq!(x.or(y), None);
Fully qualified path: core::option::OptionTrait::or
fn or<+Drop<T>>(self: Option<T>, optb: Option<T>) -> Option<T>
or_else
Returns the option if it contains a value, otherwise calls f
and returns the result. # Examples
let nobody = || Option::<ByteArray>::None;
let vikings = || Option::<ByteArray>::Some("vikings");
assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians"));
assert_eq!(None.or_else(vikings), Some("vikings"));
assert_eq!(None.or_else(nobody), None);
Fully qualified path: core::option::OptionTrait::or_else
fn or_else<F, +Drop<F>, +core::ops::FnOnce<F, ()>[Output: Option<T>]>(
self: Option<T>, f: F,
) -> Option<T>
xor
Returns Some
if exactly one of self
, optb
is Some
, otherwise returns None
. # Examples
let x = Some(2);
let y: Option<u32> = None;
assert_eq!(x.xor(y), Some(2));
let x: Option<u32> = None;
let y = Some(2);
assert_eq!(x.xor(y), Some(2));
let x = Some(2);
let y = Some(2);
assert_eq!(x.xor(y), None);
let x: Option<u32> = None;
let y: Option<u32> = None;
assert_eq!(x.xor(y), None);
Fully qualified path: core::option::OptionTrait::xor
fn xor<+Drop<T>>(self: Option<T>, optb: Option<T>) -> Option<T>
is_some
Returns true
if the Option
is Some
, false
otherwise. # Examples
let option = Some(123);
assert!(option.is_some());
Fully qualified path: core::option::OptionTrait::is_some
fn is_some(self: @Option<T>) -> bool
is_some_and
Returns true
if the Option
is Some
and the value inside of it matches a predicate. # Examples
assert_eq!(Some(2_u8).is_some_and(|x| x > 1), true);
assert_eq!(Some(0_u8).is_some_and(|x| x > 1), false);
let option: Option<u8> = None;
assert_eq!(option.is_some_and(|x| x > 1), false);
Fully qualified path: core::option::OptionTrait::is_some_and
fn is_some_and<F, +Drop<F>, +core::ops::FnOnce<F, (T,)>[Output: bool]>(
self: Option<T>, f: F,
) -> bool
is_none
Returns true
if the Option
is None
, false
otherwise. # Examples
let option = Some(123);
assert!(!option.is_none());
Fully qualified path: core::option::OptionTrait::is_none
fn is_none(self: @Option<T>) -> bool
is_none_or
Returns true
if the Option
is None
or the value inside of it matches a predicate. # Examples
assert_eq!(Some(2_u8).is_none_or(|x| x > 1), true);
assert_eq!(Some(0_u8).is_none_or(|x| x > 1), false);
let option: Option<u8> = None;
assert_eq!(option.is_none_or(|x| x > 1), true);
Fully qualified path: core::option::OptionTrait::is_none_or
fn is_none_or<F, +Drop<F>, +core::ops::FnOnce<F, (T,)>[Output: bool]>(self: Option<T>, f: F) -> bool
unwrap_or
Returns the contained Some
value if self
is Some(x)
. Otherwise, returns the provided default. # Examples
let option = Some(123);
assert!(option.unwrap_or(456) == 123);
let option = None;
assert!(option.unwrap_or(456) == 456);
Fully qualified path: core::option::OptionTrait::unwrap_or
const fn unwrap_or<+Destruct<T>>(self: Option<T>, default: T) -> T
unwrap_or_default
Returns the contained Some
value if self
is Some(x)
. Otherwise, returns Default::<T>::default()
. # Examples
let option = Some(123);
assert!(option.unwrap_or_default() == 123);
let option: Option<felt252> = None;
assert!(option.unwrap_or_default() == Default::default());
Fully qualified path: core::option::OptionTrait::unwrap_or_default
fn unwrap_or_default<+Default<T>>(self: Option<T>) -> T
unwrap_or_else
Returns the contained Some
value or computes it from a closure. # Examples
let k = 10;
assert!(Some(4).unwrap_or_else(|| 2 * k) == 4);
assert!(None.unwrap_or_else(|| 2 * k) == 20);
Fully qualified path: core::option::OptionTrait::unwrap_or_else
fn unwrap_or_else<F, +Drop<F>, impl func: core::ops::FnOnce<F, ()>[Output: T], +Drop<func::Output>>(
self: Option<T>, f: F,
) -> T
map
Maps an Option<T>
to Option<U>
by applying a function to a contained value (if Some
) or returns None
(if None
). # Examples
let maybe_some_string: Option<ByteArray> = Some("Hello, World!");
// `Option::map` takes self *by value*, consuming `maybe_some_string`
let maybe_some_len = maybe_some_string.map(|s: ByteArray| s.len());
assert!(maybe_some_len == Some(13));
let x: Option<ByteArray> = None;
assert!(x.map(|s: ByteArray| s.len()) == None);
Fully qualified path: core::option::OptionTrait::map
fn map<U, F, +Destruct<F>, +core::ops::FnOnce<F, (T,)>[Output: U]>(
self: Option<T>, f: F,
) -> Option<U>
map_or
Returns the provided default result (if none), or applies a function to the contained value (if any).Arguments passed to map_or
are eagerly evaluated; if you are passing the result of a function call, it is recommended to use map_or_else
, which is lazily evaluated. # Examples
assert_eq!(Some("foo").map_or(42, |v: ByteArray| v.len()), 3);
let x: Option<ByteArray> = None;
assert_eq!(x.map_or(42, |v: ByteArray| v.len()), 42);
Fully qualified path: core::option::OptionTrait::map_or
fn map_or<U, F, +Drop<U>, +Drop<F>, +core::ops::FnOnce<F, (T,)>[Output: U]>(
self: Option<T>, default: U, f: F,
) -> U
map_or_else
Computes a default function result (if none), or applies a different function to the contained value (if any). # Basic examples
let k = 21;
let x = Some("foo");
assert_eq!(x.map_or_else( || 2 * k, |v: ByteArray| v.len()), 3);
let x: Option<ByteArray> = None;
assert_eq!(x.map_or_else( || 2 * k, |v: ByteArray| v.len()), 42);
Fully qualified path: core::option::OptionTrait::map_or_else
fn map_or_else<
U,
D,
F,
+Drop<U>,
+Drop<D>,
+Drop<F>,
+core::ops::FnOnce<D, ()>[Output: U],
+core::ops::FnOnce<F, (T,)>[Output: U],
>(
self: Option<T>, default: D, f: F,
) -> U
take
Takes the value out of the option, leaving a None
in its place. # Examples
let mut x = Some(2);
let y = x.take();
assert_eq!(x, None);
assert_eq!(y, Some(2));
let mut x: Option<u32> = None;
let y = x.take();
assert_eq!(x, None);
assert_eq!(y, None);
Fully qualified path: core::option::OptionTrait::take
fn take(ref self: Option<T>) -> Option<T>
filter
Returns None
if the option is None
, otherwise calls predicate
with the wrapped value and returns:Some(t)
if predicate
returns true
(where t
is the wrapped value), and - None
if predicate
returns false
. # Example
let is_even = |n: @u32| -> bool {
*n % 2 == 0
};
assert_eq!(None.filter(is_even), None);
assert_eq!(Some(3).filter(is_even), None);
assert_eq!(Some(4).filter(is_even), Some(4));
Fully qualified path: core::option::OptionTrait::filter
fn filter<P, +core::ops::FnOnce<P, (@T,)>[Output: bool], +Destruct<T>, +Destruct<P>>(
self: Option<T>, predicate: P,
) -> Option<T>
flatten
Converts from Option<Option<T>>
to Option<T>
. # ExamplesBasic usage:
let x: Option<Option<u32>> = Some(Some(6));
assert_eq!(Some(6), x.flatten());
let x: Option<Option<u32>> = Some(None);
assert_eq!(None, x.flatten());
let x: Option<Option<u32>> = None;
assert_eq!(None, x.flatten());
Flattening only removes one level of nesting at a time:
let x: Option<Option<Option<u32>>> = Some(Some(Some(6)));
assert_eq!(Some(Some(6)), x.flatten());
assert_eq!(Some(6), x.flatten().flatten());
Fully qualified path: core::option::OptionTrait::flatten
fn flatten(self: Option<Option<T>>) -> Option<T>
Clone
A common trait for the ability to explicitly duplicate an object.Differs from Copy
in that Copy
is implicit and inexpensive, while Clone
is always explicit and may or may not be expensive.Since Clone
is more general than Copy
, you can automatically make anything Copy
be Clone
as well. ## DerivableThis trait can be used with #[derive]
if all fields are Clone
. The derive
d implementation of Clone
calls clone
on each field.
Fully qualified path: core::clone::Clone
pub trait Clone<T>
Trait functions
clone
Returns a copy of the value. # Examples
let arr = array![1, 2, 3];
assert!(arr == arr.clone());
Fully qualified path: core::clone::Clone::clone
fn clone(self: @T) -> T
EcStateTrait
Fully qualified path: core::ec::EcStateTrait
pub trait EcStateTrait
Trait functions
init
Initializes an EC computation with the zero point. # Examples
let mut state = EcStateTrait::init();
Fully qualified path: core::ec::EcStateTrait::init
fn init() -> EcState nopanic
add
Adds a point to the computation. # Argumentsp
- The non-zero point to add
Fully qualified path: core::ec::EcStateTrait::add
fn add(ref self: EcState, p: NonZeroEcPoint) nopanic
sub
Subtracts a point to the computation. # Argumentsp
- The non-zero point to subtract
Fully qualified path: core::ec::EcStateTrait::sub
fn sub(ref self: EcState, p: NonZeroEcPoint)
add_mul
Adds the product p * scalar
to the state. # Argumentsscalar
- The scalar to multiply the point by * p
- The non-zero point to multiply and add
Fully qualified path: core::ec::EcStateTrait::add_mul
fn add_mul(ref self: EcState, scalar: felt252, p: NonZeroEcPoint) nopanic
finalize_nz
Finalizes the EC computation and returns the result as a non-zero point. # ReturnsOption<NonZeroEcPoint>
- The resulting point, or None if the result is the zero point # PanicsPanics if the result is the point at infinity.
Fully qualified path: core::ec::EcStateTrait::finalize_nz
fn finalize_nz(self: EcState) -> Option<NonZeroEcPoint> nopanic
finalize
Finalizes the EC computation and returns the result.Returns the zero point if the computation results in the point at infinity.
Fully qualified path: core::ec::EcStateTrait::finalize
fn finalize(self: EcState) -> EcPoint
EcPointTrait
Fully qualified path: core::ec::EcPointTrait
pub trait EcPointTrait
Trait functions
new
Creates a new EC point from its (x, y) coordinates. # Argumentsx
- The x-coordinate of the point * y
- The y-coordinate of the point # ReturnsReturns None
if the point (x, y) is not on the curve. # Examples
let point = EcPointTrait::new(
x: 336742005567258698661916498343089167447076063081786685068305785816009957563,
y: 1706004133033694959518200210163451614294041810778629639790706933324248611779,
).unwrap();
Fully qualified path: core::ec::EcPointTrait::new
fn new(x: felt252, y: felt252) -> Option<EcPoint>
new_nz
Creates a new NonZero EC point from its (x, y) coordinates.
Fully qualified path: core::ec::EcPointTrait::new_nz
fn new_nz(x: felt252, y: felt252) -> Option<NonZeroEcPoint>
new_from_x
Creates a new EC point from its x coordinate. # Argumentsx
- The x-coordinate of the point # ReturnsReturns None
if no point with the given x-coordinate exists on the curve. # PanicsPanics if x
is 0, as this would be the point at infinity. # Examples
let valid = EcPointTrait::new_from_x(1);
assert!(valid.is_some());
let invalid = EcPointTrait::new_from_x(0);
assert!(invalid.is_none());
Fully qualified path: core::ec::EcPointTrait::new_from_x
fn new_from_x(x: felt252) -> Option<EcPoint>
new_nz_from_x
Creates a new NonZero EC point from its x coordinate.
Fully qualified path: core::ec::EcPointTrait::new_nz_from_x
fn new_nz_from_x(x: felt252) -> Option<NonZeroEcPoint>
coordinates
Returns the coordinates of the EC point. # ReturnsA tuple containing the (x, y) coordinates of the point. # PanicsPanics if the point is the point at infinity. # Examples
let point_nz = EcPointTrait::new_nz_from_x(1).unwrap();
let (x, _y) = point_nz.coordinates();
assert!(x == 1);
Fully qualified path: core::ec::EcPointTrait::coordinates
fn coordinates(self: NonZeroEcPoint) -> (felt252, felt252)
x
Returns the x coordinate of the EC point. # PanicsPanics if the point is the point at infinity. # Examples
let point_nz = EcPointTrait::new_nz_from_x(1).unwrap();
let x = point_nz.x();
assert!(x == 1);
Fully qualified path: core::ec::EcPointTrait::x
fn x(self: NonZeroEcPoint) -> felt252
y
Returns the y coordinate of the EC point. # PanicsPanics if the point is the point at infinity. # Examples
let gen_point =
EcPointTrait::new_nz_from_x(0x1ef15c18599971b7beced415a40f0c7deacfd9b0d1819e03d723d8bc943cfca).unwrap();
let y = gen_point.y();
assert!(y == 0x5668060aa49730b7be4801df46ec62de53ecd11abe43a32873000c36e8dc1f);
Fully qualified path: core::ec::EcPointTrait::y
fn y(self: NonZeroEcPoint) -> felt252
mul
Computes the product of an EC point by the given scalar. # Argumentsscalar
- The scalar to multiply the point by # ReturnsThe resulting point after scalar multiplication.
Fully qualified path: core::ec::EcPointTrait::mul
fn mul(self: EcPoint, scalar: felt252) -> EcPoint
NumericLiteral
Fully qualified path: core::integer::NumericLiteral
pub trait NumericLiteral<T>;
BoundedInt
Trait for getting the maximal and minimal values of an integer type.
Fully qualified path: core::integer::BoundedInt
pub trait BoundedInt<T>
Trait functions
min
Returns the minimal value of the type.
Fully qualified path: core::integer::BoundedInt::min
fn min() -> T nopanic
max
Returns the maximal value of the type.
Fully qualified path: core::integer::BoundedInt::max
fn max() -> T nopanic
Zero
Defines an additive identity element for T
. # Laws
a + 0 = a ∀ a ∈ T
0 + a = a ∀ a ∈ T
Fully qualified path: core::num::traits::zero::Zero
pub trait Zero<T>
Trait functions
zero
Returns the additive identity element of T
, 0
. # Examples
use core::num::traits::Zero;
assert!(Zero::<u32>::zero() == 0);
Fully qualified path: core::num::traits::zero::Zero::zero
fn zero() -> T
is_zero
Returns true if self
is equal to the additive identity. # Examples
use core::num::traits::Zero;
assert!(0.is_zero());
assert!(!5.is_zero());
Fully qualified path: core::num::traits::zero::Zero::is_zero
fn is_zero(self: @T) -> bool
is_non_zero
Returns false if self
is equal to the additive identity. # Examples
use core::num::traits::Zero;
assert!(5.is_non_zero());
assert!(!0.is_non_zero());
Fully qualified path: core::num::traits::zero::Zero::is_non_zero
fn is_non_zero(self: @T) -> bool
One
Defines a multiplicative identity element for T
. # Laws
a * 1 = a ∀ a ∈ T
1 * a = a ∀ a ∈ T
Fully qualified path: core::num::traits::one::One
pub trait One<T>
Trait functions
one
Returns the multiplicative identity element of T
, 1
. # Examples
use core::num::traits::One;
assert!(One::<u32>::one() == 1);
Fully qualified path: core::num::traits::one::One::one
fn one() -> T
is_one
Returns true if self
is equal to the multiplicative identity. # Examples
use core::num::traits::One;
assert!(1.is_one());
assert!(!0.is_one());
Fully qualified path: core::num::traits::one::One::is_one
fn is_one(self: @T) -> bool
is_non_one
Returns false if self
is equal to the multiplicative identity. # Examples
use core::num::traits::One;
assert!(0.is_non_one());
assert!(!1.is_non_one());
Fully qualified path: core::num::traits::one::One::is_non_one
fn is_non_one(self: @T) -> bool
BitSize
A trait used to retrieve the size of a type in bits.
Fully qualified path: core::num::traits::bit_size::BitSize
pub trait BitSize<T>
Trait functions
bits
Returns the bit size of T
as a usize
. # Examples
use core::num::traits::BitSize;
let bits = BitSize::<u8>::bits();
assert!(bits == 8);
Fully qualified path: core::num::traits::bit_size::BitSize::bits
fn bits() -> usize
Bounded
A trait defining minimum and maximum bounds for numeric types.This trait only supports types that can have constant values.
Fully qualified path: core::num::traits::bounded::Bounded
pub trait Bounded<T>
Trait constants
MIN
Returns the minimum value for type T
. # Examples
use core::num::traits::Bounded;
let min = Bounded::<u8>::MIN;
assert!(min == 0);
Fully qualified path: core::num::traits::bounded::Bounded::MIN
const MIN: T;
MAX
Returns the maximum value for type T
. # Examples
use core::num::traits::Bounded;
let max = Bounded::<u8>::MAX;
assert!(max == 255);
Fully qualified path: core::num::traits::bounded::Bounded::MAX
const MAX: T;
CheckedAdd
Performs addition that returns None
instead of wrapping around on overflow. # Examples
use core::num::traits::CheckedAdd;
let result = 1_u8.checked_add(2);
assert!(result == Some(3));
let result = 255_u8.checked_add(1);
assert!(result == None); // Overflow
Fully qualified path: core::num::traits::ops::checked::CheckedAdd
pub trait CheckedAdd<T>
Trait functions
checked_add
Adds two numbers, checking for overflow. If overflow happens, None
is returned.
Fully qualified path: core::num::traits::ops::checked::CheckedAdd::checked_add
fn checked_add(self: T, v: T) -> Option<T>
CheckedMul
Performs multiplication that returns None
instead of wrapping around on underflow or overflow. # Examples
use core::num::traits::CheckedMul;
let result = 10_u8.checked_mul(20);
assert!(result == Some(200));
let result = 10_u8.checked_mul(30);
assert!(result == None); // Overflow
Fully qualified path: core::num::traits::ops::checked::CheckedMul
pub trait CheckedMul<T>
Trait functions
checked_mul
Multiplies two numbers, checking for underflow or overflow. If underflow or overflow happens, None
is returned.
Fully qualified path: core::num::traits::ops::checked::CheckedMul::checked_mul
fn checked_mul(self: T, v: T) -> Option<T>
CheckedSub
Performs subtraction that returns None
instead of wrapping around on underflow. # Examples
use core::num::traits::CheckedSub;
let result = 1_u8.checked_sub(1);
assert!(result == Some(0));
let result = 1_u8.checked_sub(2);
assert!(result == None); // Underflow
Fully qualified path: core::num::traits::ops::checked::CheckedSub
pub trait CheckedSub<T>
Trait functions
checked_sub
Subtracts two numbers, checking for underflow. If underflow happens, None
is returned.
Fully qualified path: core::num::traits::ops::checked::CheckedSub::checked_sub
fn checked_sub(self: T, v: T) -> Option<T>
OverflowingAdd
Performs addition with a flag for overflow. # Examples
use core::num::traits::OverflowingAdd;
let (result, is_overflow) = 1_u8.overflowing_add(255_u8);
assert!(result == 0);
assert!(is_overflow);
Fully qualified path: core::num::traits::ops::overflowing::OverflowingAdd
pub trait OverflowingAdd<T>
Trait functions
overflowing_add
Returns a tuple of the sum along with a boolean indicating whether an arithmetic overflow would occur. If an overflow would have occurred then the wrapped value is returned.
Fully qualified path: core::num::traits::ops::overflowing::OverflowingAdd::overflowing_add
fn overflowing_add(self: T, v: T) -> (T, bool)
OverflowingMul
Performs multiplication with a flag for overflow. # Examples
use core::num::traits::OverflowingMul;
let (result, is_overflow) = 1_u8.overflowing_mul(2_u8);
assert!(result == 2);
assert!(!is_overflow);
Fully qualified path: core::num::traits::ops::overflowing::OverflowingMul
pub trait OverflowingMul<T>
Trait functions
overflowing_mul
Returns a tuple of the product along with a boolean indicating whether an arithmetic overflow would occur. If an overflow would have occurred then the wrapped value is returned.
Fully qualified path: core::num::traits::ops::overflowing::OverflowingMul::overflowing_mul
fn overflowing_mul(self: T, v: T) -> (T, bool)
OverflowingSub
Performs subtraction with a flag for overflow. # Examples
use core::num::traits::OverflowingSub;
let (result, is_underflow) = 1_u8.overflowing_sub(2_u8);
assert!(result == 255);
assert!(is_underflow);
Fully qualified path: core::num::traits::ops::overflowing::OverflowingSub
pub trait OverflowingSub<T>
Trait functions
overflowing_sub
Returns a tuple of the difference along with a boolean indicating whether an arithmetic overflow would occur. If an overflow would have occurred then the wrapped value is returned.
Fully qualified path: core::num::traits::ops::overflowing::OverflowingSub::overflowing_sub
fn overflowing_sub(self: T, v: T) -> (T, bool)
Pow
Raises a value to the power of exp
.Note that 0⁰
(pow(0, 0)
) returns 1
. Mathematically this is undefined. # PanicsPanics if the result of the exponentiation operation overflows the output type. # Examples
use core::num::traits::Pow;
assert!(2_i8.pow(4_usize) == 16_i8);
assert!(6_u8.pow(3_usize) == 216_u8);
assert!(0_u8.pow(0_usize) == 1_u8);
Fully qualified path: core::num::traits::ops::pow::Pow
pub trait Pow<Base, Exp>
Trait functions
pow
Returns self
to the power exp
.
Fully qualified path: core::num::traits::ops::pow::Pow::pow
fn pow(self: Base, exp: Exp) -> Self::Output
Trait types
Output
The type of the result of the power calculation.
Fully qualified path: core::num::traits::ops::pow::Pow::Output
type Output;
SaturatingAdd
Performs addition that saturates at the numeric bounds instead of overflowing. # Examples
use core::num::traits::SaturatingAdd;
assert!(255_u8.saturating_add(1_u8) == 255);
Fully qualified path: core::num::traits::ops::saturating::SaturatingAdd
pub trait SaturatingAdd<T>
Trait functions
saturating_add
Saturating addition. Computes self + other
, saturating at the relevant high or low boundary of the type.
Fully qualified path: core::num::traits::ops::saturating::SaturatingAdd::saturating_add
fn saturating_add(self: T, other: T) -> T
SaturatingMul
Performs multiplication that saturates at the numeric bounds instead of overflowing. # Examples
use core::num::traits::SaturatingMul;
assert!(100_u8.saturating_mul(3_u8) == 255);
Fully qualified path: core::num::traits::ops::saturating::SaturatingMul
pub trait SaturatingMul<T>
Trait functions
saturating_mul
Saturating multiplication. Computes self * other
, saturating at the relevant high or low boundary of the type.
Fully qualified path: core::num::traits::ops::saturating::SaturatingMul::saturating_mul
fn saturating_mul(self: T, other: T) -> T
SaturatingSub
Performs subtraction that saturates at the numeric bounds instead of overflowing. # Examples
use core::num::traits::SaturatingSub;
assert!(1_u8.saturating_sub(2_u8) == 0);
Fully qualified path: core::num::traits::ops::saturating::SaturatingSub
pub trait SaturatingSub<T>
Trait functions
saturating_sub
Saturating subtraction. Computes self - other
, saturating at the relevant high or low boundary of the type.
Fully qualified path: core::num::traits::ops::saturating::SaturatingSub::saturating_sub
fn saturating_sub(self: T, other: T) -> T
Sqrt
A trait for computing the square root of a number. # Examples
use core::num::traits::Sqrt;
assert!(9_u8.sqrt() == 3);
Fully qualified path: core::num::traits::ops::sqrt::Sqrt
pub trait Sqrt<T>
Trait functions
sqrt
Computes the square root of a number.
Fully qualified path: core::num::traits::ops::sqrt::Sqrt::sqrt
fn sqrt(self: T) -> Self::Target
Trait types
Target
The type of the result of the square root operation.
Fully qualified path: core::num::traits::ops::sqrt::Sqrt::Target
type Target;
WideMul
A trait for types that can be multiplied together to produce a wider type.This trait enables multiplication operations where the result type has double the bit width of the input types, preventing overflow in cases where the result would exceed the input type's maximum value. # Examples
use core::num::traits::WideMul;
let a: u8 = 255; // maximum value for u8
let b: u8 = 255;
let result: u16 = a.wide_mul(b);
assert!(result == 65025);
Fully qualified path: core::num::traits::ops::widemul::WideMul
pub trait WideMul<Lhs, Rhs>
Trait functions
wide_mul
Multiply two values together, producing a wider type.
Fully qualified path: core::num::traits::ops::widemul::WideMul::wide_mul
fn wide_mul(self: Lhs, other: Rhs) -> Self::Target
Trait types
Target
The type of the result of the multiplication.
Fully qualified path: core::num::traits::ops::widemul::WideMul::Target
type Target;
WideSquare
A trait for a type that can be squared to produce a wider type.This trait enables squaring operations where the result type has double the bit width of the input type, preventing overflow in cases where the result would exceed the input type's maximum value. # Examples
use core::num::traits::WideSquare;
let a: u8 = 16;
let result: u16 = a.wide_square();
assert!(result == 256);
Fully qualified path: core::num::traits::ops::widesquare::WideSquare
pub trait WideSquare<T>
Trait functions
wide_square
Calculates the square, producing a wider type.
Fully qualified path: core::num::traits::ops::widesquare::WideSquare::wide_square
fn wide_square(self: T) -> Self::Target
Trait types
Target
The type of the result of the square.
Fully qualified path: core::num::traits::ops::widesquare::WideSquare::Target
type Target;
WrappingAdd
Performs addition that wraps around on overflow. # Examples
use core::num::traits::WrappingAdd;
let result = 255_u8.wrapping_add(1);
assert!(result == 0);
let result = 100_u8.wrapping_add(200);
assert!(result == 44); // (100 + 200) % 256 = 44
Fully qualified path: core::num::traits::ops::wrapping::WrappingAdd
pub trait WrappingAdd<T>
Trait functions
wrapping_add
Wrapping (modular) addition. Computes self + other
, wrapping around at the boundary of the type.
Fully qualified path: core::num::traits::ops::wrapping::WrappingAdd::wrapping_add
fn wrapping_add(self: T, v: T) -> T
WrappingMul
Performs multiplication that wraps around on overflow. # Examples
use core::num::traits::WrappingMul;
let result = 10_u8.wrapping_mul(30);
assert!(result == 44); // (10 * 30) % 256 = 44
let result = 200_u8.wrapping_mul(2);
assert!(result == 144); // (200 * 2) % 256 = 144
Fully qualified path: core::num::traits::ops::wrapping::WrappingMul
pub trait WrappingMul<T>
Trait functions
wrapping_mul
Wrapping (modular) multiplication. Computes self * other
, wrapping around at the boundary of the type.
Fully qualified path: core::num::traits::ops::wrapping::WrappingMul::wrapping_mul
fn wrapping_mul(self: T, v: T) -> T
WrappingSub
Performs subtraction that wraps around on overflow. # Examples
use core::num::traits::WrappingSub;
let result = 0_u8.wrapping_sub(1);
assert!(result == 255);
let result = 100_u8.wrapping_sub(150);
assert!(result == 206);
Fully qualified path: core::num::traits::ops::wrapping::WrappingSub
pub trait WrappingSub<T>
Trait functions
wrapping_sub
Wrapping (modular) subtraction. Computes self - other
, wrapping around at the boundary of the type.
Fully qualified path: core::num::traits::ops::wrapping::WrappingSub::wrapping_sub
fn wrapping_sub(self: T, v: T) -> T
Zero
Defines an additive identity element for T
. # Laws
a + 0 = a ∀ a ∈ T
0 + a = a ∀ a ∈ T
Fully qualified path: core::num::traits::zero::Zero
pub trait Zero<T>
Trait functions
zero
Returns the additive identity element of T
, 0
. # Examples
use core::num::traits::Zero;
assert!(Zero::<u32>::zero() == 0);
Fully qualified path: core::num::traits::zero::Zero::zero
fn zero() -> T
is_zero
Returns true if self
is equal to the additive identity. # Examples
use core::num::traits::Zero;
assert!(0.is_zero());
assert!(!5.is_zero());
Fully qualified path: core::num::traits::zero::Zero::is_zero
fn is_zero(self: @T) -> bool
is_non_zero
Returns false if self
is equal to the additive identity. # Examples
use core::num::traits::Zero;
assert!(5.is_non_zero());
assert!(!0.is_non_zero());
Fully qualified path: core::num::traits::zero::Zero::is_non_zero
fn is_non_zero(self: @T) -> bool
One
Defines a multiplicative identity element for T
. # Laws
a * 1 = a ∀ a ∈ T
1 * a = a ∀ a ∈ T
Fully qualified path: core::num::traits::one::One
pub trait One<T>
Trait functions
one
Returns the multiplicative identity element of T
, 1
. # Examples
use core::num::traits::One;
assert!(One::<u32>::one() == 1);
Fully qualified path: core::num::traits::one::One::one
fn one() -> T
is_one
Returns true if self
is equal to the multiplicative identity. # Examples
use core::num::traits::One;
assert!(1.is_one());
assert!(!0.is_one());
Fully qualified path: core::num::traits::one::One::is_one
fn is_one(self: @T) -> bool
is_non_one
Returns false if self
is equal to the multiplicative identity. # Examples
use core::num::traits::One;
assert!(0.is_non_one());
assert!(!1.is_non_one());
Fully qualified path: core::num::traits::one::One::is_non_one
fn is_non_one(self: @T) -> bool
BitSize
A trait used to retrieve the size of a type in bits.
Fully qualified path: core::num::traits::bit_size::BitSize
pub trait BitSize<T>
Trait functions
bits
Returns the bit size of T
as a usize
. # Examples
use core::num::traits::BitSize;
let bits = BitSize::<u8>::bits();
assert!(bits == 8);
Fully qualified path: core::num::traits::bit_size::BitSize::bits
fn bits() -> usize
CheckedAdd
Performs addition that returns None
instead of wrapping around on overflow. # Examples
use core::num::traits::CheckedAdd;
let result = 1_u8.checked_add(2);
assert!(result == Some(3));
let result = 255_u8.checked_add(1);
assert!(result == None); // Overflow
Fully qualified path: core::num::traits::ops::checked::CheckedAdd
pub trait CheckedAdd<T>
Trait functions
checked_add
Adds two numbers, checking for overflow. If overflow happens, None
is returned.
Fully qualified path: core::num::traits::ops::checked::CheckedAdd::checked_add
fn checked_add(self: T, v: T) -> Option<T>
CheckedSub
Performs subtraction that returns None
instead of wrapping around on underflow. # Examples
use core::num::traits::CheckedSub;
let result = 1_u8.checked_sub(1);
assert!(result == Some(0));
let result = 1_u8.checked_sub(2);
assert!(result == None); // Underflow
Fully qualified path: core::num::traits::ops::checked::CheckedSub
pub trait CheckedSub<T>
Trait functions
checked_sub
Subtracts two numbers, checking for underflow. If underflow happens, None
is returned.
Fully qualified path: core::num::traits::ops::checked::CheckedSub::checked_sub
fn checked_sub(self: T, v: T) -> Option<T>
CheckedMul
Performs multiplication that returns None
instead of wrapping around on underflow or overflow. # Examples
use core::num::traits::CheckedMul;
let result = 10_u8.checked_mul(20);
assert!(result == Some(200));
let result = 10_u8.checked_mul(30);
assert!(result == None); // Overflow
Fully qualified path: core::num::traits::ops::checked::CheckedMul
pub trait CheckedMul<T>
Trait functions
checked_mul
Multiplies two numbers, checking for underflow or overflow. If underflow or overflow happens, None
is returned.
Fully qualified path: core::num::traits::ops::checked::CheckedMul::checked_mul
fn checked_mul(self: T, v: T) -> Option<T>
OverflowingAdd
Performs addition with a flag for overflow. # Examples
use core::num::traits::OverflowingAdd;
let (result, is_overflow) = 1_u8.overflowing_add(255_u8);
assert!(result == 0);
assert!(is_overflow);
Fully qualified path: core::num::traits::ops::overflowing::OverflowingAdd
pub trait OverflowingAdd<T>
Trait functions
overflowing_add
Returns a tuple of the sum along with a boolean indicating whether an arithmetic overflow would occur. If an overflow would have occurred then the wrapped value is returned.
Fully qualified path: core::num::traits::ops::overflowing::OverflowingAdd::overflowing_add
fn overflowing_add(self: T, v: T) -> (T, bool)
OverflowingSub
Performs subtraction with a flag for overflow. # Examples
use core::num::traits::OverflowingSub;
let (result, is_underflow) = 1_u8.overflowing_sub(2_u8);
assert!(result == 255);
assert!(is_underflow);
Fully qualified path: core::num::traits::ops::overflowing::OverflowingSub
pub trait OverflowingSub<T>
Trait functions
overflowing_sub
Returns a tuple of the difference along with a boolean indicating whether an arithmetic overflow would occur. If an overflow would have occurred then the wrapped value is returned.
Fully qualified path: core::num::traits::ops::overflowing::OverflowingSub::overflowing_sub
fn overflowing_sub(self: T, v: T) -> (T, bool)
OverflowingMul
Performs multiplication with a flag for overflow. # Examples
use core::num::traits::OverflowingMul;
let (result, is_overflow) = 1_u8.overflowing_mul(2_u8);
assert!(result == 2);
assert!(!is_overflow);
Fully qualified path: core::num::traits::ops::overflowing::OverflowingMul
pub trait OverflowingMul<T>
Trait functions
overflowing_mul
Returns a tuple of the product along with a boolean indicating whether an arithmetic overflow would occur. If an overflow would have occurred then the wrapped value is returned.
Fully qualified path: core::num::traits::ops::overflowing::OverflowingMul::overflowing_mul
fn overflowing_mul(self: T, v: T) -> (T, bool)
Pow
Raises a value to the power of exp
.Note that 0⁰
(pow(0, 0)
) returns 1
. Mathematically this is undefined. # PanicsPanics if the result of the exponentiation operation overflows the output type. # Examples
use core::num::traits::Pow;
assert!(2_i8.pow(4_usize) == 16_i8);
assert!(6_u8.pow(3_usize) == 216_u8);
assert!(0_u8.pow(0_usize) == 1_u8);
Fully qualified path: core::num::traits::ops::pow::Pow
pub trait Pow<Base, Exp>
Trait functions
pow
Returns self
to the power exp
.
Fully qualified path: core::num::traits::ops::pow::Pow::pow
fn pow(self: Base, exp: Exp) -> Self::Output
Trait types
Output
The type of the result of the power calculation.
Fully qualified path: core::num::traits::ops::pow::Pow::Output
type Output;
SaturatingAdd
Performs addition that saturates at the numeric bounds instead of overflowing. # Examples
use core::num::traits::SaturatingAdd;
assert!(255_u8.saturating_add(1_u8) == 255);
Fully qualified path: core::num::traits::ops::saturating::SaturatingAdd
pub trait SaturatingAdd<T>
Trait functions
saturating_add
Saturating addition. Computes self + other
, saturating at the relevant high or low boundary of the type.
Fully qualified path: core::num::traits::ops::saturating::SaturatingAdd::saturating_add
fn saturating_add(self: T, other: T) -> T
SaturatingSub
Performs subtraction that saturates at the numeric bounds instead of overflowing. # Examples
use core::num::traits::SaturatingSub;
assert!(1_u8.saturating_sub(2_u8) == 0);
Fully qualified path: core::num::traits::ops::saturating::SaturatingSub
pub trait SaturatingSub<T>
Trait functions
saturating_sub
Saturating subtraction. Computes self - other
, saturating at the relevant high or low boundary of the type.
Fully qualified path: core::num::traits::ops::saturating::SaturatingSub::saturating_sub
fn saturating_sub(self: T, other: T) -> T
SaturatingMul
Performs multiplication that saturates at the numeric bounds instead of overflowing. # Examples
use core::num::traits::SaturatingMul;
assert!(100_u8.saturating_mul(3_u8) == 255);
Fully qualified path: core::num::traits::ops::saturating::SaturatingMul
pub trait SaturatingMul<T>
Trait functions
saturating_mul
Saturating multiplication. Computes self * other
, saturating at the relevant high or low boundary of the type.
Fully qualified path: core::num::traits::ops::saturating::SaturatingMul::saturating_mul
fn saturating_mul(self: T, other: T) -> T
WrappingAdd
Performs addition that wraps around on overflow. # Examples
use core::num::traits::WrappingAdd;
let result = 255_u8.wrapping_add(1);
assert!(result == 0);
let result = 100_u8.wrapping_add(200);
assert!(result == 44); // (100 + 200) % 256 = 44
Fully qualified path: core::num::traits::ops::wrapping::WrappingAdd
pub trait WrappingAdd<T>
Trait functions
wrapping_add
Wrapping (modular) addition. Computes self + other
, wrapping around at the boundary of the type.
Fully qualified path: core::num::traits::ops::wrapping::WrappingAdd::wrapping_add
fn wrapping_add(self: T, v: T) -> T
WrappingSub
Performs subtraction that wraps around on overflow. # Examples
use core::num::traits::WrappingSub;
let result = 0_u8.wrapping_sub(1);
assert!(result == 255);
let result = 100_u8.wrapping_sub(150);
assert!(result == 206);
Fully qualified path: core::num::traits::ops::wrapping::WrappingSub
pub trait WrappingSub<T>
Trait functions
wrapping_sub
Wrapping (modular) subtraction. Computes self - other
, wrapping around at the boundary of the type.
Fully qualified path: core::num::traits::ops::wrapping::WrappingSub::wrapping_sub
fn wrapping_sub(self: T, v: T) -> T
WrappingMul
Performs multiplication that wraps around on overflow. # Examples
use core::num::traits::WrappingMul;
let result = 10_u8.wrapping_mul(30);
assert!(result == 44); // (10 * 30) % 256 = 44
let result = 200_u8.wrapping_mul(2);
assert!(result == 144); // (200 * 2) % 256 = 144
Fully qualified path: core::num::traits::ops::wrapping::WrappingMul
pub trait WrappingMul<T>
Trait functions
wrapping_mul
Wrapping (modular) multiplication. Computes self * other
, wrapping around at the boundary of the type.
Fully qualified path: core::num::traits::ops::wrapping::WrappingMul::wrapping_mul
fn wrapping_mul(self: T, v: T) -> T
AddAssign
The addition assignment operator +=
.
Fully qualified path: core::ops::arith::AddAssign
pub trait AddAssign<Lhs, Rhs>
Trait functions
add_assign
Performs the +=
operation. # Examples
let mut x: u8 = 3;
x += x;
assert!(x == 6);
Fully qualified path: core::ops::arith::AddAssign::add_assign
fn add_assign(ref self: Lhs, rhs: Rhs)
DivAssign
The division assignment operator /=
.
Fully qualified path: core::ops::arith::DivAssign
pub trait DivAssign<Lhs, Rhs>
Trait functions
div_assign
Performs the /=
operation. # Examples
let mut x: u8 = 3;
x /= x;
assert!(x == 1);
Fully qualified path: core::ops::arith::DivAssign::div_assign
fn div_assign(ref self: Lhs, rhs: Rhs)
MulAssign
The multiplication assignment operator *=
.
Fully qualified path: core::ops::arith::MulAssign
pub trait MulAssign<Lhs, Rhs>
Trait functions
mul_assign
Performs the *=
operation. # Examples
let mut x: u8 = 3;
x *= x;
assert!(x == 9);
Fully qualified path: core::ops::arith::MulAssign::mul_assign
fn mul_assign(ref self: Lhs, rhs: Rhs)
RemAssign
The remainder assignment operator %=
.
Fully qualified path: core::ops::arith::RemAssign
pub trait RemAssign<Lhs, Rhs>
Trait functions
rem_assign
Performs the %=
operation. # Examples
let mut x: u8 = 3;
x %= x;
assert!(x == 0);
Fully qualified path: core::ops::arith::RemAssign::rem_assign
fn rem_assign(ref self: Lhs, rhs: Rhs)
SubAssign
The subtraction assignment operator -=
.
Fully qualified path: core::ops::arith::SubAssign
pub trait SubAssign<Lhs, Rhs>
Trait functions
sub_assign
Performs the -=
operation. # Examples
let mut x: u8 = 3;
x -= x;
assert!(x == 0);
Fully qualified path: core::ops::arith::SubAssign::sub_assign
fn sub_assign(ref self: Lhs, rhs: Rhs)
Deref
A trait for dereferencing a value to provide transparent access to its contents.Implementing this trait allows a type to behave like its inner type, enabling direct access to the inner type's fields.Note: The Deref
mechanism is limited and cannot be used to implicitly convert a type to its target type when passing arguments to functions. For example, if you have a function that takes an Inner
, you cannot pass an Outer
to it even if Outer
implements Deref
. # Examples
struct Wrapper<T> { inner: T }
impl WrapperDeref<T> of Deref<Wrapper<T>> {
type Target = T;
fn deref(self: Wrapper<T>) -> T { self.inner }
}
let wrapped = Wrapper { inner: 42 };
assert!(wrapped.deref() == 42);
Fully qualified path: core::ops::deref::Deref
pub trait Deref<T>
Trait functions
deref
Returns the dereferenced value.
Fully qualified path: core::ops::deref::Deref::deref
fn deref(self: T) -> Self::Target
Trait types
Target
The type of the dereferenced value.
Fully qualified path: core::ops::deref::Deref::Target
type Target;
DerefMut
A trait for dereferencing in mutable contexts.This trait is similar to Deref
but specifically handles cases where the value accessed is mutable. Despite its name, DerefMut
does NOT allow modifying the inner value - it only indicates that the container itself is mutable. # Examples
[derive(Copy, Drop)]
struct MutWrapper<T> {
value: T
}
impl MutWrapperDerefMut<T, +Copy<T>> of DerefMut<MutWrapper<T>> {
type Target = T;
fn deref_mut(ref self: MutWrapper<T>) -> T {
self.value
}
}
// This will work since x is mutable
let mut x = MutWrapper { value: 42 };
let val = x.deref_mut();
assert!(val == 42);
// This would fail to compile since y is not mutable
let y = MutWrapper { value: 42 };
let val = y.deref_mut(); // Compile error
Fully qualified path: core::ops::deref::DerefMut
pub trait DerefMut<T>
Trait functions
deref_mut
Returns the dereferenced value.
Fully qualified path: core::ops::deref::DerefMut::deref_mut
fn deref_mut(ref self: T) -> Self::Target
Trait types
Target
The type of the dereferenced value.
Fully qualified path: core::ops::deref::DerefMut::Target
type Target;
Fn
The version of the call operator that takes a by-snapshot receiver.Instances of Fn
can be called repeatedly.Fn
is implemented automatically by closures which only whose captured variable are all Copy
. Additionally, for any type F
that implements Fn
, @F
implements Fn
, too.Since FnOnce
is implemented for all implementers of Fn
, any instance of Fn
can be used as a parameter where a FnOnce
is expected.Use Fn
as a bound when you want to accept a parameter of function-like type and need to call it repeatedly. If you do not need such strict requirements, use FnOnce
as bounds. # Examples ## Calling a closure
let square = |x| x * x;
assert_eq!(square(5), 25);
Using a Fn
parameter
fn call_with_one<F, +Drop<F>, +core::ops::Fn<F, (usize,)>[Output: usize]>(func: F) -> usize {
func(1)
}
let double = |x| x * 2;
assert_eq!(call_with_one(double), 2);
Fully qualified path: core::ops::function::Fn
pub trait Fn<T, Args>
Trait functions
call
Performs the call operation.
Fully qualified path: core::ops::function::Fn::call
fn call(self: @T, args: Args) -> Self::Output
Trait types
Output
The returned type after the call operator is used.
Fully qualified path: core::ops::function::Fn::Output
type Output;
FnOnce
The version of the call operator that takes a by-value receiver.Instances of FnOnce
can be called, but might not be callable multiple times. Because of this, if the only thing known about a type is that it implements FnOnce
, it can only be called once.FnOnce
is implemented automatically by closures that might consume captured variables.
Examples
fn consume_with_relish<
F, O, +Drop<F>, +core::ops::FnOnce<F, ()>[Output: O], +core::fmt::Display<O>, +Drop<O>,
>(
func: F,
) {
// `func` consumes its captured variables, so it cannot be run more
// than once.
println!("Consumed: {}", func());
println!("Delicious!");
// Attempting to invoke `func()` again will throw a `Variable was previously moved.`
// error for `func`.
}
let x: ByteArray = "x";
let consume_and_return_x = || x;
consume_with_relish(consume_and_return_x);
// `consume_and_return_x` can no longer be invoked at this point
Fully qualified path: core::ops::function::FnOnce
pub trait FnOnce<T, Args>
Trait functions
call
Performs the call operation.
Fully qualified path: core::ops::function::FnOnce::call
fn call(self: T, args: Args) -> Self::Output
Trait types
Output
The returned type after the call operator is used.
Fully qualified path: core::ops::function::FnOnce::Output
type Output;
Index
A trait for indexing operations (container[index]
) where the input type is mutated.This trait should be implemented when you want to implement indexing operations on a type that's mutated by a read access. This is useful for any type depending on a Felt252Dict
, where dictionary accesses are modifying the data structure itself.container[index]
is syntactic sugar for container.index(index)
. # ExamplesThe following example implements Index
on a Stack
type. This Stack
is implemented based on a Felt252Dict
, where dictionary accesses are modifying the dictionary itself. As such, we must implement the Index
trait instead of the IndexView
trait.
use core::ops::Index;
[derive(Destruct, Default)]
struct Stack {
items: Felt252Dict<u128>,
len: usize
}
[generate_trait]
impl StackImpl of StackTrait {
fn push(ref self: Stack, item: u128) {
self.items.insert(self.len.into(), item);
self.len += 1;
}
}
impl StackIndex of Index<Stack, usize> {
type Target = u128;
fn index(ref self: Stack, index: usize) -> Self::Target {
if index >= self.len {
panic!("Index out of bounds");
}
self.items.get(index.into())
}
}
let mut stack: Stack = Default::default();
stack.push(1);
assert!(stack[0] == 1);
Fully qualified path: core::ops::index::Index
pub trait Index<C, I>
Trait functions
index
Performs the indexing (container[index]
) operation. # PanicsMay panic if the index is out of bounds.
Fully qualified path: core::ops::index::Index::index
fn index(ref self: C, index: I) -> Self::Target
Trait types
Target
The returned type after indexing.
Fully qualified path: core::ops::index::Index::Target
type Target;
IndexView
A trait for indexing operations (container[index]
) where the input type is not modified.container[index]
is syntactic sugar for container.index(index)
. # ExamplesThe following example implements IndexView
on a NucleotideCount
container, which can be indexed without modifying the input, enabling individual counts to be retrieved with index syntax.
use core::ops::IndexView;
[derive(Copy, Drop)]
enum Nucleotide {
A,
C,
G,
T,
}
[derive(Copy, Drop)]
struct NucleotideCount {
a: usize,
c: usize,
g: usize,
t: usize,
}
impl NucleotideIndex of IndexView<NucleotideCount, Nucleotide> {
type Target = usize;
fn index(self: @NucleotideCount, index: Nucleotide) -> Self::Target {
match index {
Nucleotide::A => *self.a,
Nucleotide::C => *self.c,
Nucleotide::G => *self.g,
Nucleotide::T => *self.t,
}
}
}
let nucleotide_count = NucleotideCount {a: 14, c: 9, g: 10, t: 12};
assert!(nucleotide_count[Nucleotide::A] == 14);
assert!(nucleotide_count[Nucleotide::C] == 9);
assert!(nucleotide_count[Nucleotide::G] == 10);
assert!(nucleotide_count[Nucleotide::T] == 12);
Fully qualified path: core::ops::index::IndexView
pub trait IndexView<C, I>
Trait functions
index
Performs the indexing (container[index]
) operation. # PanicsMay panic if the index is out of bounds.
Fully qualified path: core::ops::index::IndexView::index
fn index(self: @C, index: I) -> Self::Target
Trait types
Target
The returned type after indexing.
Fully qualified path: core::ops::index::IndexView::Target
type Target;
RangeInclusiveTrait
Fully qualified path: core::ops::range::RangeInclusiveTrait
pub trait RangeInclusiveTrait<T, +Destruct<T>, +PartialOrd<@T>>
Trait functions
contains
Returns true
if item
is contained in the range. # Examples
assert!(!(3..=5).contains(@2));
assert!( (3..=5).contains(@3));
assert!( (3..=5).contains(@4));
assert!( (3..=5).contains(@5));
assert!(!(3..=5).contains(@6));
assert!( (3..=3).contains(@3));
assert!(!(3..=2).contains(@3));
Fully qualified path: core::ops::range::RangeInclusiveTrait::contains
fn contains(self: @RangeInclusive<T>, item: @T) -> bool
is_empty
Returns true
if the range contains no items. # Examples
assert!(!(3_u8..=5_u8).is_empty());
assert!(!(3_u8..=3_u8).is_empty());
assert!( (3_u8..=2_u8).is_empty());
Fully qualified path: core::ops::range::RangeInclusiveTrait::is_empty
fn is_empty(self: @RangeInclusive<T>) -> bool
RangeTrait
Fully qualified path: core::ops::range::RangeTrait
pub trait RangeTrait<T, +Destruct<T>, +PartialOrd<@T>>
Trait functions
contains
Returns true
if item
is contained in the range. # Examples
assert!(!(3..5).contains(@2));
assert!( (3..5).contains(@3));
assert!( (3..5).contains(@4));
assert!(!(3..5).contains(@5));
assert!(!(3..3).contains(@3));
assert!(!(3..2).contains(@3));
Fully qualified path: core::ops::range::RangeTrait::contains
fn contains(self: @Range<T>, item: @T) -> bool
is_empty
Returns true
if the range contains no items. # Examples
assert!(!(3_u8..5_u8).is_empty());
assert!( (3_u8..3_u8).is_empty());
assert!( (3_u8..2_u8).is_empty());
Fully qualified path: core::ops::range::RangeTrait::is_empty
fn is_empty(self: @Range<T>) -> bool
IndexView
A trait for indexing operations (container[index]
) where the input type is not modified.container[index]
is syntactic sugar for container.index(index)
. # ExamplesThe following example implements IndexView
on a NucleotideCount
container, which can be indexed without modifying the input, enabling individual counts to be retrieved with index syntax.
use core::ops::IndexView;
[derive(Copy, Drop)]
enum Nucleotide {
A,
C,
G,
T,
}
[derive(Copy, Drop)]
struct NucleotideCount {
a: usize,
c: usize,
g: usize,
t: usize,
}
impl NucleotideIndex of IndexView<NucleotideCount, Nucleotide> {
type Target = usize;
fn index(self: @NucleotideCount, index: Nucleotide) -> Self::Target {
match index {
Nucleotide::A => *self.a,
Nucleotide::C => *self.c,
Nucleotide::G => *self.g,
Nucleotide::T => *self.t,
}
}
}
let nucleotide_count = NucleotideCount {a: 14, c: 9, g: 10, t: 12};
assert!(nucleotide_count[Nucleotide::A] == 14);
assert!(nucleotide_count[Nucleotide::C] == 9);
assert!(nucleotide_count[Nucleotide::G] == 10);
assert!(nucleotide_count[Nucleotide::T] == 12);
Fully qualified path: core::ops::index::IndexView
pub trait IndexView<C, I>
Trait functions
index
Performs the indexing (container[index]
) operation. # PanicsMay panic if the index is out of bounds.
Fully qualified path: core::ops::index::IndexView::index
fn index(self: @C, index: I) -> Self::Target
Trait types
Target
The returned type after indexing.
Fully qualified path: core::ops::index::IndexView::Target
type Target;
Index
A trait for indexing operations (container[index]
) where the input type is mutated.This trait should be implemented when you want to implement indexing operations on a type that's mutated by a read access. This is useful for any type depending on a Felt252Dict
, where dictionary accesses are modifying the data structure itself.container[index]
is syntactic sugar for container.index(index)
. # ExamplesThe following example implements Index
on a Stack
type. This Stack
is implemented based on a Felt252Dict
, where dictionary accesses are modifying the dictionary itself. As such, we must implement the Index
trait instead of the IndexView
trait.
use core::ops::Index;
[derive(Destruct, Default)]
struct Stack {
items: Felt252Dict<u128>,
len: usize
}
[generate_trait]
impl StackImpl of StackTrait {
fn push(ref self: Stack, item: u128) {
self.items.insert(self.len.into(), item);
self.len += 1;
}
}
impl StackIndex of Index<Stack, usize> {
type Target = u128;
fn index(ref self: Stack, index: usize) -> Self::Target {
if index >= self.len {
panic!("Index out of bounds");
}
self.items.get(index.into())
}
}
let mut stack: Stack = Default::default();
stack.push(1);
assert!(stack[0] == 1);
Fully qualified path: core::ops::index::Index
pub trait Index<C, I>
Trait functions
index
Performs the indexing (container[index]
) operation. # PanicsMay panic if the index is out of bounds.
Fully qualified path: core::ops::index::Index::index
fn index(ref self: C, index: I) -> Self::Target
Trait types
Target
The returned type after indexing.
Fully qualified path: core::ops::index::Index::Target
type Target;
HashStateTrait
A trait for hash state accumulators.Provides methods to update a hash state with new values and finalize it into a hash result.
Fully qualified path: core::hash::HashStateTrait
pub trait HashStateTrait<S>
Trait functions
update
Updates the current hash state self
with the given felt252
value and returns a new hash state. # Examples
use core::pedersen::PedersenTrait;
use core::hash::HashStateTrait;
let mut state = PedersenTrait::new(0);
state = state.update(1);
Fully qualified path: core::hash::HashStateTrait::update
fn update(self: S, value: felt252) -> S
finalize
Takes the current state self
and returns the hash result. # Examples
use core::pedersen::PedersenTrait;
use core::hash::HashStateTrait;
let mut state = PedersenTrait::new(0);
let hash = state.finalize();
Fully qualified path: core::hash::HashStateTrait::finalize
fn finalize(self: S) -> felt252
Hash
A trait for values that can be hashed.This trait should be implemented for any type that can be included in a hash calculation. The most common way to implement this trait is by using #[derive(Hash)]
.
Fully qualified path: core::hash::Hash
pub trait Hash<T, S, +HashStateTrait<S>>
Trait functions
update_state
Updates the hash state with the given value and returns a new hash state. # Examples
use core::pedersen::PedersenTrait;
use core::hash::Hash;
let mut state = PedersenTrait::new(0);
let new_state = Hash::update_state(state, 1);
Fully qualified path: core::hash::Hash::update_state
fn update_state(state: S, value: T) -> S
LegacyHash
A trait for hashing values using a felt252
as hash state, used for backwards compatibility. NOTE: Implement Hash
instead of this trait if possible.
Fully qualified path: core::hash::LegacyHash
pub trait LegacyHash<T>
Trait functions
hash
Takes a felt252
state and a value of type T
and returns the hash result. # Examples
use core::pedersen::PedersenTrait;
use core::hash::LegacyHash;
let hash = LegacyHash::hash(0, 1);
Fully qualified path: core::hash::LegacyHash::hash
fn hash(state: felt252, value: T) -> felt252
HashStateExTrait
Extension trait for hash state accumulators.This trait adds the update_with
method to hash states, allowing you to directly hash values of any type T that implements Hash
, rather than having to manually convert values to felt252 first. This provides a more ergonomic API when working with complex types.
Fully qualified path: core::hash::HashStateExTrait
pub trait HashStateExTrait<S, T>
Trait functions
update_with
Updates the hash state with the given value and returns the updated state. # Examples
use core::pedersen::PedersenTrait;
use core::hash::HashStateExTrait;
[derive(Copy, Drop, Hash)]
struct Point { x: u32, y: u32 }
let point = Point { x: 1, y: 2 };
let hash = PedersenTrait::new(0)
.update_with(point)
.update_with(42)
.finalize();
Fully qualified path: core::hash::HashStateExTrait::update_with
fn update_with(self: S, value: T) -> S
PedersenTrait
Fully qualified path: core::pedersen::PedersenTrait
pub trait PedersenTrait
Trait functions
new
Creates a new Pedersen hash state with the given base value. # Examples
use core::pedersen::PedersenTrait;
let mut state = PedersenTrait::new(0);
assert!(state.state == 0);
Fully qualified path: core::pedersen::PedersenTrait::new
fn new(base: felt252) -> HashState
Serde
A trait that allows for serializing and deserializing values of any type.The Serde<T>
trait defines two core operations: - serialize
: Converts a value into a sequence of felt252
s - deserialize
: Reconstructs a value from a sequence of felt252
s # Examples ## Simple Types (u8, u16, u32, u64, u128)Simple types are serialized into a single felt252
:
let value: u8 = 42;
let mut output: Array<felt252> = array![];
value.serialize(ref output);
assert!(output == array![42]); // Single value
Compound Types (u256)Compound types may be serialized into multiple felt252
values:
let value: u256 = u256 { low: 1, high: 2 };
let mut output: Array<felt252> = array![];
value.serialize(ref output);
assert!(output == array![1, 2]); // Two `felt252`s: low and high
Implementing Serde
## Using the Derive
MacroIn most cases, you can use the #[derive(Serde)]
attribute to automatically generate the implementation for your type:
[derive(Serde)]
struct Point {
x: u32,
y: u32
}
Manual ImplementationShould you need to customize the serialization behavior for a type in a way that derive does not support, you can implement the Serde
yourself:
impl PointSerde of Serde<Point> {
fn serialize(self: @Point, ref output: Array<felt252>) {
output.append((*self.x).into());
output.append((*self.y).into());
}
fn deserialize(ref serialized: Span<felt252>) -> Option<Point> {
let x = (*serialized.pop_front()?).try_into()?;
let y = (*serialized.pop_front()?).try_into()?;
Some(Point { x, y })
}
}
Fully qualified path: core::serde::Serde
pub trait Serde<T>
Trait functions
serialize
Serializes a value into a sequence of felt252
s. # Examples
let value: u256 = 1;
let mut serialized: Array<felt252> = array![];
value.serialize(ref serialized);
assert!(serialized == array![1, 0]); // `serialized` contains the [low, high] parts of the
`u256` value ```
Fully qualified path: core::serde::Serde::serialize
fn serialize(self: @T, ref output: Array<felt252>)
deserialize
Deserializes a value from a sequence of felt252
s. If the value cannot be deserialized, returns None
. # Examples
let mut serialized: Span<felt252> = array![1, 0].span();
let value: u256 = Serde::deserialize(ref serialized).unwrap();
assert!(value == 1);
Fully qualified path: core::serde::Serde::deserialize
fn deserialize(ref serialized: Span<felt252>) -> Option<T>
PoseidonTrait
Fully qualified path: core::poseidon::PoseidonTrait
pub trait PoseidonTrait
Trait functions
new
Creates an initial state with all fields set to 0. # Examples
use core::poseidon::PoseidonTrait;
let mut state = PoseidonTrait::new();
Fully qualified path: core::poseidon::PoseidonTrait::new
fn new() -> HashState
Display
A trait for standard formatting, using the empty format ("{}"). # Examples
let word: ByteArray = "123";
println!("{}", word);
Fully qualified path: core::fmt::Display
pub trait Display<T>
Trait functions
fmt
Fully qualified path: core::fmt::Display::fmt
fn fmt(self: @T, ref f: Formatter) -> Result<(), Error>
Debug
A trait for debug formatting, using the empty format ("{:?}"). # Examples
let word: ByteArray = "123";
println!("{:?}", word);
Fully qualified path: core::fmt::Debug
pub trait Debug<T>
Trait functions
fmt
Fully qualified path: core::fmt::Debug::fmt
fn fmt(self: @T, ref f: Formatter) -> Result<(), Error>
LowerHex
A trait for hex formatting in lower case, using the empty format ("{:x}").
Fully qualified path: core::fmt::LowerHex
pub trait LowerHex<T>
Trait functions
fmt
Fully qualified path: core::fmt::LowerHex::fmt
fn fmt(self: @T, ref f: Formatter) -> Result<(), Error>
SyscallResultTrait
Trait for handling syscall results.
Fully qualified path: core::starknet::SyscallResultTrait
pub trait SyscallResultTrait<T>
Trait functions
unwrap_syscall
Unwraps a syscall result, yielding the content of an Ok
. # PanicsPanics with the syscall error message if the value is an Err
. # Examples
let result = starknet::syscalls::get_execution_info_v2_syscall();
let info = result.unwrap_syscall();
Fully qualified path: core::starknet::SyscallResultTrait::unwrap_syscall
fn unwrap_syscall(self: SyscallResult<T>) -> T
Store
Trait for types that can be stored in Starknet contract storage.The Store
trait enables types to be stored in and retrieved from Starknet's contract storage. Cairo implements Store
for most primitive types. However, collection types (arrays, dicts, etc.) do not implement Store
directly. Instead, use specialized storage types, such as Vec
or Map
.Map
: starknet::storage::Map Vec
: starknet::storage::Vec # DerivationTo make a type storable in contract storage, simply derive the Store
trait:
[derive(Drop, starknet::Store)]
struct Sizes {
tiny: u8, // 8 bits
small: u32, // 32 bits
medium: u64, // 64 bits
}
This allows the Size
struct to be stored in a contract's storage.There's no real reason to implement this trait yourself, as it can be trivially derived. For efficiency purposes, consider manually implementing StorePacking
to optimize storage usage.
Fully qualified path: core::starknet::storage_access::Store
pub trait Store<T>
Trait functions
read
Reads a value from storage at the given domain and base address. # Argumentsaddress_domain
- The storage domain (currently only 0 is supported) * base
- The base storage address to read from
Fully qualified path: core::starknet::storage_access::Store::read
fn read(address_domain: u32, base: StorageBaseAddress) -> SyscallResult<T>
write
Writes a value to storage at the given domain and base address. # Argumentsaddress_domain
- The storage domain (currently only 0 is supported) * base
- The base storage address to write to * value
- The value to store
Fully qualified path: core::starknet::storage_access::Store::write
fn write(address_domain: u32, base: StorageBaseAddress, value: T) -> SyscallResult<()>
read_at_offset
Reads a value from storage at a base address plus an offset. # Argumentsaddress_domain
- The storage domain (currently only 0 is supported) * base
- The base storage address * offset
- The offset from the base address where the value should be read
Fully qualified path: core::starknet::storage_access::Store::read_at_offset
fn read_at_offset(address_domain: u32, base: StorageBaseAddress, offset: u8) -> SyscallResult<T>
write_at_offset
Writes a value to storage at a base address plus an offset. # Argumentsaddress_domain
- The storage domain (currently only 0 is supported) * base
- The base storage address * offset
- The offset from the base address where the value should be written * value
- The value to store
Fully qualified path: core::starknet::storage_access::Store::write_at_offset
fn write_at_offset(
address_domain: u32, base: StorageBaseAddress, offset: u8, value: T,
) -> SyscallResult<()>
size
Returns the size in storage for this type.This is bounded to 255, as the offset is a u8. As such, a single type can only take up to 255 slots in storage.
Fully qualified path: core::starknet::storage_access::Store::size
fn size() -> u8
scrub
Clears the storage area by writing zeroes to it. # Argumentsaddress_domain
- The storage domain * base
- The base storage address to start clearing * offset
- The offset from the base address where clearing should startThe operation writes zeroes to storage starting from the specified base address and offset, and continues for the size of the type as determined by the size()
function.
Fully qualified path: core::starknet::storage_access::Store::scrub
fn scrub(address_domain: u32, base: StorageBaseAddress, offset: u8) -> SyscallResult<()>
Event
A trait for handling serialization and deserialization of events.Events in Starknet are stored in transaction receipts as a combination of keys and data fields. This trait provides the methods needed to serialize event data into these fields and deserialize them back into their original form.This trait can easily be derived using the #[derive(starknet::Event)]
attribute. Fields can be marked as keys using the #[key]
attribute to serialize them as event keys. # Examples
[derive(Drop, starknet::Event)]
pub struct Transfer {
[key]
pub from: ContractAddress,
[key]
pub to: ContractAddress,
pub amount: u256,
}
Fully qualified path: core::starknet::event::Event
pub trait Event<T>
Trait functions
append_keys_and_data
Serializes the keys and data for event emission.The keys array will contain: - The event name selector as the first key - Any fields marked with #key as subsequent keysThe data array will contain all non-key fields.
Fully qualified path: core::starknet::event::Event::append_keys_and_data
fn append_keys_and_data(self: @T, ref keys: Array<felt252>, ref data: Array<felt252>)
deserialize
Deserializes events keys and data back into the original event structure.Returns None
if deserialization fails.
Fully qualified path: core::starknet::event::Event::deserialize
fn deserialize(ref keys: Span<felt252>, ref data: Span<felt252>) -> Option<T>
AccountContract
A trait for account contracts that support class declarations (only __validate__
and __execute__
are mandatory for an account).This trait assumes that the calldata for invoke transactions is Array<Call>
. This is the network standard following SNIP6. It is not enforced by Starknet, but deviating from the standard interface may lead to incompatibility with standard tooling.
Fully qualified path: core::starknet::account::AccountContract
pub trait AccountContract<TContractState>
Trait functions
validate_declare
An entry point that is called to check if the account is willing to pay for the declaration of the class with the given hash. The entry point should return starknet::VALIDATED
if the account is willing to pay for the declaration.
Fully qualified path: core::starknet::account::AccountContract::__validate_declare__
fn __validate_declare__(self: @TContractState, class_hash: felt252) -> felt252
validate
An entry point that is called to check if the account is willing to pay for executing a given set of calls. The entry point should return starknet::VALIDATED
if the account is willing to pay for the execution, in which case __execute__
will be called on the same set of calls.
Fully qualified path: core::starknet::account::AccountContract::__validate__
fn __validate__(ref self: TContractState, calls: Array<Call>) -> felt252
execute
An entry point that is called to execute a given set of calls. This entry point should block the deprecated v0 invoke transactions as they do not go through the __validate__
entry point.
Fully qualified path: core::starknet::account::AccountContract::__execute__
fn __execute__(ref self: TContractState, calls: Array<Call>) -> Array<Span<felt252>>
Store
Trait for types that can be stored in Starknet contract storage.The Store
trait enables types to be stored in and retrieved from Starknet's contract storage. Cairo implements Store
for most primitive types. However, collection types (arrays, dicts, etc.) do not implement Store
directly. Instead, use specialized storage types, such as Vec
or Map
.Map
: starknet::storage::Map Vec
: starknet::storage::Vec # DerivationTo make a type storable in contract storage, simply derive the Store
trait:
[derive(Drop, starknet::Store)]
struct Sizes {
tiny: u8, // 8 bits
small: u32, // 32 bits
medium: u64, // 64 bits
}
This allows the Size
struct to be stored in a contract's storage.There's no real reason to implement this trait yourself, as it can be trivially derived. For efficiency purposes, consider manually implementing StorePacking
to optimize storage usage.
Fully qualified path: core::starknet::storage_access::Store
pub trait Store<T>
Trait functions
read
Reads a value from storage at the given domain and base address. # Argumentsaddress_domain
- The storage domain (currently only 0 is supported) * base
- The base storage address to read from
Fully qualified path: core::starknet::storage_access::Store::read
fn read(address_domain: u32, base: StorageBaseAddress) -> SyscallResult<T>
write
Writes a value to storage at the given domain and base address. # Argumentsaddress_domain
- The storage domain (currently only 0 is supported) * base
- The base storage address to write to * value
- The value to store
Fully qualified path: core::starknet::storage_access::Store::write
fn write(address_domain: u32, base: StorageBaseAddress, value: T) -> SyscallResult<()>
read_at_offset
Reads a value from storage at a base address plus an offset. # Argumentsaddress_domain
- The storage domain (currently only 0 is supported) * base
- The base storage address * offset
- The offset from the base address where the value should be read
Fully qualified path: core::starknet::storage_access::Store::read_at_offset
fn read_at_offset(address_domain: u32, base: StorageBaseAddress, offset: u8) -> SyscallResult<T>
write_at_offset
Writes a value to storage at a base address plus an offset. # Argumentsaddress_domain
- The storage domain (currently only 0 is supported) * base
- The base storage address * offset
- The offset from the base address where the value should be written * value
- The value to store
Fully qualified path: core::starknet::storage_access::Store::write_at_offset
fn write_at_offset(
address_domain: u32, base: StorageBaseAddress, offset: u8, value: T,
) -> SyscallResult<()>
size
Returns the size in storage for this type.This is bounded to 255, as the offset is a u8. As such, a single type can only take up to 255 slots in storage.
Fully qualified path: core::starknet::storage_access::Store::size
fn size() -> u8
scrub
Clears the storage area by writing zeroes to it. # Argumentsaddress_domain
- The storage domain * base
- The base storage address to start clearing * offset
- The offset from the base address where clearing should startThe operation writes zeroes to storage starting from the specified base address and offset, and continues for the size of the type as determined by the size()
function.
Fully qualified path: core::starknet::storage_access::Store::scrub
fn scrub(address_domain: u32, base: StorageBaseAddress, offset: u8) -> SyscallResult<()>
StorePacking
Trait for efficient packing of values into optimized storage representations.This trait enables bit-packing of complex types into simpler storage types to reduce gas costs by minimizing the number of storage slots used. When a type implements StorePacking
, the compiler automatically uses StoreUsingPacking
to handle storage operations. As such, a type cannot implement both Store
and StorePacking
. # Storage OptimizationEach storage slot in Starknet is a felt252
, and storage operations are expensive. By packing multiple values into fewer slots, you can significantly reduce gas costs. For example: - Multiple small integers can be packed into a single felt252
- Structs with several fields can be compressed into a single storage slot # Implementation RequirementsTo implement StorePacking
, ensure that the PackedT
type implements Store
. The packed representation must preserve all necessary information to allow unpacking back to the original type. Additionally, the pack
and unpack
operations must be reversible, meaning that packing followed by unpacking should return the original value. # ExamplePacking multiple integer fields into a single storage slot:
use starknet::storage_access::StorePacking;
[derive(Drop)]
struct Sizes {
tiny: u8, // 8 bits
small: u32, // 32 bits
medium: u64, // 64 bits
}
const TWO_POW_8: u128 = 0x100;
const TWO_POW_40: u128 = 0x10000000000;
impl SizesStorePacking of StorePacking<Sizes, u128> {
fn pack(value: Sizes) -> u128 {
value.tiny.into() +
(value.small.into() * TWO_POW_8) +
(value.medium.into() * TWO_POW_40)
}
fn unpack(value: u128) -> Sizes {
let tiny = value & 0xff;
let small = (value / TWO_POW_8) & 0xffffffff;
let medium = (value / TWO_POW_40);
Sizes {
tiny: tiny.try_into().unwrap(),
small: small.try_into().unwrap(),
medium: medium.try_into().unwrap(),
}
}
}
By implementing StorePacking
for Sizes
, the Sizes
will be stored in it's packed form, using a single storage slot instead of 3. When retrieved, it will automatically be unpacked back into the original type.
Fully qualified path: core::starknet::storage_access::StorePacking
pub trait StorePacking<T, PackedT>
Trait functions
pack
Packs a value into its optimized storage representation.
Fully qualified path: core::starknet::storage_access::StorePacking::pack
fn pack(value: T) -> PackedT
unpack
Unpacks a storage representation back into the original type.
Fully qualified path: core::starknet::storage_access::StorePacking::unpack
fn unpack(value: PackedT) -> T
Secp256Trait
A trait for interacting with Secp256{k/r}1 curves.Provides operations needed to work with Secp256k1 and Secp256r1 elliptic curves. It includes methods for accessing curve parameters and creating curve points. # Examples
use starknet::secp256k1::Secp256k1Point;
use starknet::secp256_trait::Secp256Trait;
use starknet::SyscallResultTrait;
assert!(
Secp256Trait::<
Secp256k1Point,
>::get_curve_size() == 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141,
);
let generator = Secp256Trait::<Secp256k1Point>::get_generator_point();
let generator = Secp256Trait::<
Secp256k1Point,
>::secp256_ec_new_syscall(
0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798,
0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8,
)
.unwrap_syscall();
let random_point = Secp256Trait::<
Secp256k1Point,
>::secp256_ec_get_point_from_x_syscall(
0x4aebd3099c618202fcfe16ae7770b0c49ab5eadf74b754204a3bb6060e44eff3, true,
);
Fully qualified path: core::starknet::secp256_trait::Secp256Trait
pub trait Secp256Trait<Secp256Point>
Trait functions
get_curve_size
Returns the order (size) of the curve's underlying field.This is the number of points on the curve, also known as the curve order.
Fully qualified path: core::starknet::secp256_trait::Secp256Trait::get_curve_size
fn get_curve_size() -> u256
get_generator_point
Returns the generator point (G) for the curve.The generator point is a standard base point on the curve from which other points can be generated through scalar multiplication.
Fully qualified path: core::starknet::secp256_trait::Secp256Trait::get_generator_point
fn get_generator_point() -> Secp256Point
secp256_ec_new_syscall
Creates a new curve point from its x and y coordinates.Returns None
if the provided coordinates don't represent a valid point on the curve.
Fully qualified path: core::starknet::secp256_trait::Secp256Trait::secp256_ec_new_syscall
fn secp256_ec_new_syscall(x: u256, y: u256) -> SyscallResult<Option<Secp256Point>>
secp256_ec_get_point_from_x_syscall
Creates a curve point on the curve given its x-coordinate and y-parity. # Argumentsx
- The x coordinate of the point * y_parity
- If true, choose the odd y value; if false, choose the even y value # ReturnsReturns Some(point)
if a point exists with the given x coordinate, None
otherwise.
Fully qualified path: core::starknet::secp256_trait::Secp256Trait::secp256_ec_get_point_from_x_syscall
fn secp256_ec_get_point_from_x_syscall(
x: u256, y_parity: bool,
) -> SyscallResult<Option<Secp256Point>>
Secp256PointTrait
A trait for performing operations on Secp256{k/r}1 curve points.Provides operations needed for elliptic curve cryptography, including point addition and scalar multiplication. # Examples
use starknet::SyscallResultTrait;
use starknet::secp256k1::Secp256k1Point;
use starknet::secp256_trait::Secp256PointTrait;
use starknet::secp256_trait::Secp256Trait;
let generator = Secp256Trait::<Secp256k1Point>::get_generator_point();
assert!(
Secp256PointTrait::get_coordinates(generator)
.unwrap_syscall() == (
0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798,
0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8,
),
);
let point = Secp256PointTrait::add(generator, generator);
let other_point = Secp256PointTrait::mul(generator, 2);
Fully qualified path: core::starknet::secp256_trait::Secp256PointTrait
pub trait Secp256PointTrait<Secp256Point>
Trait functions
get_coordinates
Returns the x and y coordinates of the curve point.
Fully qualified path: core::starknet::secp256_trait::Secp256PointTrait::get_coordinates
fn get_coordinates(self: Secp256Point) -> SyscallResult<(u256, u256)>
add
Performs elliptic curve point addition.Adds self
and other
following the curve's addition law and returns the resulting point.
Fully qualified path: core::starknet::secp256_trait::Secp256PointTrait::add
fn add(self: Secp256Point, other: Secp256Point) -> SyscallResult<Secp256Point>
mul
Performs scalar multiplication of a curve point.Multiplies self
by the given scalar value.
Fully qualified path: core::starknet::secp256_trait::Secp256PointTrait::mul
fn mul(self: Secp256Point, scalar: u256) -> SyscallResult<Secp256Point>
Event
A trait for handling serialization and deserialization of events.Events in Starknet are stored in transaction receipts as a combination of keys and data fields. This trait provides the methods needed to serialize event data into these fields and deserialize them back into their original form.This trait can easily be derived using the #[derive(starknet::Event)]
attribute. Fields can be marked as keys using the #[key]
attribute to serialize them as event keys. # Examples
[derive(Drop, starknet::Event)]
pub struct Transfer {
[key]
pub from: ContractAddress,
[key]
pub to: ContractAddress,
pub amount: u256,
}
Fully qualified path: core::starknet::event::Event
pub trait Event<T>
Trait functions
append_keys_and_data
Serializes the keys and data for event emission.The keys array will contain: - The event name selector as the first key - Any fields marked with #key as subsequent keysThe data array will contain all non-key fields.
Fully qualified path: core::starknet::event::Event::append_keys_and_data
fn append_keys_and_data(self: @T, ref keys: Array<felt252>, ref data: Array<felt252>)
deserialize
Deserializes events keys and data back into the original event structure.Returns None
if deserialization fails.
Fully qualified path: core::starknet::event::Event::deserialize
fn deserialize(ref keys: Span<felt252>, ref data: Span<felt252>) -> Option<T>
EventEmitter
A trait for emitting Starknet events. # Examples
[derive(Drop, starknet::Event)]
pub struct NewOwner {
pub new_owner: ContractAddress,
}
fn emit_event(ref self: ContractState, new_owner: ContractAddress) {
self.emit(NewOwner { new_owner });
}
Fully qualified path: core::starknet::event::EventEmitter
pub trait EventEmitter<T, TEvent>
Trait functions
emit
Emits an event.
Fully qualified path: core::starknet::event::EventEmitter::emit
fn emit<S, +Into<S, TEvent>>(ref self: T, event: S)
AccountContract
A trait for account contracts that support class declarations (only __validate__
and __execute__
are mandatory for an account).This trait assumes that the calldata for invoke transactions is Array<Call>
. This is the network standard following SNIP6. It is not enforced by Starknet, but deviating from the standard interface may lead to incompatibility with standard tooling.
Fully qualified path: core::starknet::account::AccountContract
pub trait AccountContract<TContractState>
Trait functions
validate_declare
An entry point that is called to check if the account is willing to pay for the declaration of the class with the given hash. The entry point should return starknet::VALIDATED
if the account is willing to pay for the declaration.
Fully qualified path: core::starknet::account::AccountContract::__validate_declare__
fn __validate_declare__(self: @TContractState, class_hash: felt252) -> felt252
validate
An entry point that is called to check if the account is willing to pay for executing a given set of calls. The entry point should return starknet::VALIDATED
if the account is willing to pay for the execution, in which case __execute__
will be called on the same set of calls.
Fully qualified path: core::starknet::account::AccountContract::__validate__
fn __validate__(ref self: TContractState, calls: Array<Call>) -> felt252
execute
An entry point that is called to execute a given set of calls. This entry point should block the deprecated v0 invoke transactions as they do not go through the __validate__
entry point.
Fully qualified path: core::starknet::account::AccountContract::__execute__
fn __execute__(ref self: TContractState, calls: Array<Call>) -> Array<Span<felt252>>
AccountContractDispatcherTrait
Fully qualified path: core::starknet::account::AccountContractDispatcherTrait
pub trait AccountContractDispatcherTrait<T>
Trait functions
validate_declare
An entry point that is called to check if the account is willing to pay for the declaration of the class with the given hash. The entry point should return starknet::VALIDATED
if the account is willing to pay for the declaration.
Fully qualified path: core::starknet::account::AccountContractDispatcherTrait::__validate_declare__
fn __validate_declare__(self: T, class_hash: felt252) -> felt252
validate
An entry point that is called to check if the account is willing to pay for executing a given set of calls. The entry point should return starknet::VALIDATED
if the account is willing to pay for the execution, in which case __execute__
will be called on the same set of calls.
Fully qualified path: core::starknet::account::AccountContractDispatcherTrait::__validate__
fn __validate__(self: T, calls: Array<Call>) -> felt252
execute
An entry point that is called to execute a given set of calls. This entry point should block the deprecated v0 invoke transactions as they do not go through the __validate__
entry point.
Fully qualified path: core::starknet::account::AccountContractDispatcherTrait::__execute__
fn __execute__(self: T, calls: Array<Call>) -> Array<Span<felt252>>
AccountContractSafeDispatcherTrait
Fully qualified path: core::starknet::account::AccountContractSafeDispatcherTrait
pub trait AccountContractSafeDispatcherTrait<T>
Trait functions
validate_declare
An entry point that is called to check if the account is willing to pay for the declaration of the class with the given hash. The entry point should return starknet::VALIDATED
if the account is willing to pay for the declaration.
Fully qualified path: core::starknet::account::AccountContractSafeDispatcherTrait::__validate_declare__
fn __validate_declare__(self: T, class_hash: felt252) -> starknet::SyscallResult<felt252>
validate
An entry point that is called to check if the account is willing to pay for executing a given set of calls. The entry point should return starknet::VALIDATED
if the account is willing to pay for the execution, in which case __execute__
will be called on the same set of calls.
Fully qualified path: core::starknet::account::AccountContractSafeDispatcherTrait::__validate__
fn __validate__(self: T, calls: Array<Call>) -> starknet::SyscallResult<felt252>
execute
An entry point that is called to execute a given set of calls. This entry point should block the deprecated v0 invoke transactions as they do not go through the __validate__
entry point.
Fully qualified path: core::starknet::account::AccountContractSafeDispatcherTrait::__execute__
fn __execute__(self: T, calls: Array<Call>) -> starknet::SyscallResult<Array<Span<felt252>>>
StorageAsPointer
Trait for converting a storage member to a StoragePointer0Offset
.
Fully qualified path: core::starknet::storage::StorageAsPointer
pub trait StorageAsPointer<TMemberState>
Trait functions
as_ptr
Fully qualified path: core::starknet::storage::StorageAsPointer::as_ptr
fn as_ptr(self: @TMemberState) -> StoragePointer0Offset<Self::Value>
Trait types
Value
Fully qualified path: core::starknet::storage::StorageAsPointer::Value
type Value;
StoragePointerReadAccess
Trait for accessing the values in storage using a StoragePointer
. # Examples
Fully qualified path: core::starknet::storage::StoragePointerReadAccess
pub trait StoragePointerReadAccess<T>
Trait functions
read
Fully qualified path: core::starknet::storage::StoragePointerReadAccess::read
fn read(self: @T) -> Self::Value
Trait types
Value
Fully qualified path: core::starknet::storage::StoragePointerReadAccess::Value
type Value;
StoragePointerWriteAccess
Trait for writing values to storage using a StoragePointer
. # Examples
Fully qualified path: core::starknet::storage::StoragePointerWriteAccess
pub trait StoragePointerWriteAccess<T>
Trait functions
write
Fully qualified path: core::starknet::storage::StoragePointerWriteAccess::write
fn write(self: T, value: Self::Value)
Trait types
Value
Fully qualified path: core::starknet::storage::StoragePointerWriteAccess::Value
type Value;
StorageAsPath
Trait for creating a new StoragePath
from a storage member.
Fully qualified path: core::starknet::storage::StorageAsPath
pub trait StorageAsPath<TMemberState>
Trait functions
as_path
Fully qualified path: core::starknet::storage::StorageAsPath::as_path
fn as_path(self: @TMemberState) -> StoragePath<Self::Value>
Trait types
Value
Fully qualified path: core::starknet::storage::StorageAsPath::Value
type Value;
PendingStoragePathTrait
A trait for creating a PendingStoragePath
from a StoragePath
hash state and a key.
Fully qualified path: core::starknet::storage::PendingStoragePathTrait
pub trait PendingStoragePathTrait<T, S>
Trait functions
new
Fully qualified path: core::starknet::storage::PendingStoragePathTrait::new
fn new(storage_path: @StoragePath<S>, pending_key: felt252) -> PendingStoragePath<T>
IntoIterRange
Trait for turning collection of values into an iterator over a specific range.
Fully qualified path: core::starknet::storage::IntoIterRange
pub trait IntoIterRange<T>
Trait functions
into_iter_range
Creates an iterator over a range from a collection.
Fully qualified path: core::starknet::storage::IntoIterRange::into_iter_range
fn into_iter_range(self: T, range: core::ops::Range<u64>) -> Self::IntoIter
into_iter_full_range
Creates an iterator over the full range of a collection.
Fully qualified path: core::starknet::storage::IntoIterRange::into_iter_full_range
fn into_iter_full_range(self: T) -> Self::IntoIter
Trait types
IntoIter
Fully qualified path: core::starknet::storage::IntoIterRange::IntoIter
type IntoIter;
ValidStorageTypeTrait
Trait that ensures a type is valid for storage in Starknet contracts. This trait is used to enforce that only specific types, such as those implementing Store
or acting as a StorageNode
, can be a part of a storage hierarchy. Any type that does not implement this trait cannot be used in a storage struct.
Fully qualified path: core::starknet::storage::ValidStorageTypeTrait
pub trait ValidStorageTypeTrait<T>;
StorageMapReadAccess
Provides direct read access to values in a storage Map
. # Examples
use starknet::ContractAddress;
use starknet::storage::{Map, StorageMapReadAccess, StoragePathEntry};
[storage]
struct Storage {
balances: Map<ContractAddress, u256>,
allowances: Map<ContractAddress, Map<ContractAddress, u256>>,
}
fn read_storage(self: @ContractState, address: ContractAddress) {
// Read from single mapping
let balance = self.balances.read(address);
// Read from nested mapping
let allowance = self.allowances.entry(owner).read(spender);
}
Fully qualified path: core::starknet::storage::map::StorageMapReadAccess
pub trait StorageMapReadAccess<TMemberState>
Trait functions
read
Fully qualified path: core::starknet::storage::map::StorageMapReadAccess::read
fn read(self: TMemberState, key: Self::Key) -> Self::Value
Trait types
Key
Fully qualified path: core::starknet::storage::map::StorageMapReadAccess::Key
type Key;
Value
Fully qualified path: core::starknet::storage::map::StorageMapReadAccess::Value
type Value;
StorageMapWriteAccess
Provides direct write access to values in a storage Map
.Enables directly storing values in the contract's storage at the address of the given key. # Examples
use starknet::ContractAddress;
use starknet::storage::{Map, StorageMapWriteAccess, StoragePathEntry};
[storage]
struct Storage {
balances: Map<ContractAddress, u256>,
allowances: Map<ContractAddress, Map<ContractAddress, u256>>,
}
fn write_storage(ref self: ContractState, address: ContractAddress) {
// Write to single mapping
self.balances.write(address, 100);
// Write to nested mapping
self.allowances.entry(owner).write(spender, 50);
}
Fully qualified path: core::starknet::storage::map::StorageMapWriteAccess
pub trait StorageMapWriteAccess<TMemberState>
Trait functions
write
Fully qualified path: core::starknet::storage::map::StorageMapWriteAccess::write
fn write(self: TMemberState, key: Self::Key, value: Self::Value)
Trait types
Key
Fully qualified path: core::starknet::storage::map::StorageMapWriteAccess::Key
type Key;
Value
Fully qualified path: core::starknet::storage::map::StorageMapWriteAccess::Value
type Value;
StoragePathEntry
Computes storage paths for accessing Map
entries.The storage path combines the variable's base path with the key's hash to create a unique identifier for the storage slot. This path can then be used for subsequent read or write operations, or advanced further by chaining the entry
method. # Examples
use starknet::ContractAddress;
use starknet::storage::{Map, StoragePathEntry};
[storage]
struct Storage {
balances: Map<ContractAddress, u256>,
}
// Get the storage path for the balance of a specific address
let balance_path = self.balances.entry(address);
Fully qualified path: core::starknet::storage::map::StoragePathEntry
pub trait StoragePathEntry<C>
Trait functions
entry
Fully qualified path: core::starknet::storage::map::StoragePathEntry::entry
fn entry(self: C, key: Self::Key) -> StoragePath<Self::Value>
Trait types
Key
Fully qualified path: core::starknet::storage::map::StoragePathEntry::Key
type Key;
Value
Fully qualified path: core::starknet::storage::map::StoragePathEntry::Value
type Value;
StorageTrait
A trait for creating the struct containing the StorageBase
or FlattenedStorage
of all the members of a contract state.
Fully qualified path: core::starknet::storage::storage_base::StorageTrait
pub trait StorageTrait<T>
Trait functions
storage
Creates a struct containing the StorageBase
or FlattenedStorage
of all the members of a contract state. Should be called from the deref
method of the contract state.
Fully qualified path: core::starknet::storage::storage_base::StorageTrait::storage
fn storage(self: FlattenedStorage<T>) -> Self::BaseType
Trait types
BaseType
The type of the struct containing the StorageBase
or FlattenedStorage
of all the members of the type T
.
Fully qualified path: core::starknet::storage::storage_base::StorageTrait::BaseType
type BaseType;
StorageTraitMut
A trait for creating the struct containing the mutable StorageBase
or FlattenedStorage
of all the members of a contract state.
Fully qualified path: core::starknet::storage::storage_base::StorageTraitMut
pub trait StorageTraitMut<T>
Trait functions
storage_mut
Creates a struct containing a mutable version of the StorageBase
or FlattenedStorage
of all the members of a contract state. Should be called from the deref
method of the contract state.
Fully qualified path: core::starknet::storage::storage_base::StorageTraitMut::storage_mut
fn storage_mut(self: FlattenedStorage<Mutable<T>>) -> Self::BaseType
Trait types
BaseType
The type of the struct containing the mutable StorageBase
or FlattenedStorage
of all the members of the type T
.
Fully qualified path: core::starknet::storage::storage_base::StorageTraitMut::BaseType
type BaseType;
StorageNode
A trait that given a storage path of a struct, generates the storage node of this struct.
Fully qualified path: core::starknet::storage::storage_node::StorageNode
pub trait StorageNode<T>
Trait functions
storage_node
Fully qualified path: core::starknet::storage::storage_node::StorageNode::storage_node
fn storage_node(self: StoragePath<T>) -> Self::NodeType
Trait types
NodeType
Fully qualified path: core::starknet::storage::storage_node::StorageNode::NodeType
type NodeType;
StorageNodeMut
A mutable version of StorageNode
, works the same way, but on Mutable<T>
.
Fully qualified path: core::starknet::storage::storage_node::StorageNodeMut
pub trait StorageNodeMut<T>
Trait functions
storage_node_mut
Fully qualified path: core::starknet::storage::storage_node::StorageNodeMut::storage_node_mut
fn storage_node_mut(self: StoragePath<Mutable<T>>) -> Self::NodeType
Trait types
NodeType
Fully qualified path: core::starknet::storage::storage_node::StorageNodeMut::NodeType
type NodeType;
SubPointers
Similar to storage node, but for structs which are stored sequentially in the storage. In contrast to storage node, the fields of the struct are just at an offset from the base address of the struct.
Fully qualified path: core::starknet::storage::sub_pointers::SubPointers
pub trait SubPointers<T>
Trait functions
sub_pointers
Creates a sub pointers struct for the given storage pointer to a struct T.
Fully qualified path: core::starknet::storage::sub_pointers::SubPointers::sub_pointers
fn sub_pointers(self: StoragePointer<T>) -> Self::SubPointersType
Trait types
SubPointersType
The type of the storage pointers, generated for the struct T.
Fully qualified path: core::starknet::storage::sub_pointers::SubPointers::SubPointersType
type SubPointersType;
SubPointersForward
A trait for implementing SubPointers
for types which are not a StoragePointer
, such as StorageBase
and StoragePath
.
Fully qualified path: core::starknet::storage::sub_pointers::SubPointersForward
pub trait SubPointersForward<T>
Trait functions
sub_pointers
Fully qualified path: core::starknet::storage::sub_pointers::SubPointersForward::sub_pointers
fn sub_pointers(self: T) -> Self::SubPointersType
Trait types
SubPointersType
Fully qualified path: core::starknet::storage::sub_pointers::SubPointersForward::SubPointersType
type SubPointersType;
SubPointersMut
A mutable version of SubPointers
, works the same way, but on Mutable<T>
.
Fully qualified path: core::starknet::storage::sub_pointers::SubPointersMut
pub trait SubPointersMut<T>
Trait functions
sub_pointers_mut
Creates a sub pointers struct for the given storage pointer to a struct T.
Fully qualified path: core::starknet::storage::sub_pointers::SubPointersMut::sub_pointers_mut
fn sub_pointers_mut(self: StoragePointer<Mutable<T>>) -> Self::SubPointersType
Trait types
SubPointersType
The type of the storage pointers, generated for the struct T.
Fully qualified path: core::starknet::storage::sub_pointers::SubPointersMut::SubPointersType
type SubPointersType;
SubPointersMutForward
A trait for implementing SubPointersMut
for types which are not a StoragePointer
, such as StorageBase
and StoragePath
.
Fully qualified path: core::starknet::storage::sub_pointers::SubPointersMutForward
pub trait SubPointersMutForward<T>
Trait functions
sub_pointers_mut
Fully qualified path: core::starknet::storage::sub_pointers::SubPointersMutForward::sub_pointers_mut
fn sub_pointers_mut(self: T) -> Self::SubPointersType
Trait types
SubPointersType
Fully qualified path: core::starknet::storage::sub_pointers::SubPointersMutForward::SubPointersType
type SubPointersType;
MutableVecTrait
Provides mutable access to elements in a storage Vec
.This trait extends the read functionality with methods to append new elements and modify existing ones.
Fully qualified path: core::starknet::storage::vec::MutableVecTrait
pub trait MutableVecTrait<T>
Trait functions
get
Returns a mutable storage path to the element at the specified index, or None
if out of bounds. # Examples
use starknet::storage::{Vec, MutableVecTrait, StoragePointerWriteAccess};
[storage]
struct Storage {
numbers: Vec<u256>,
}
fn set_number(ref self: ContractState, index: u64, number: u256) -> bool {
if let Some(ptr) = self.numbers.get(index) {
ptr.write(number);
true
} else {
false
}
}
Fully qualified path: core::starknet::storage::vec::MutableVecTrait::get
fn get(self: T, index: u64) -> Option<StoragePath<Mutable<Self::ElementType>>>
at
Returns a mutable storage path to the element at the specified index. # PanicsPanics if the index is out of bounds. # Examples
use starknet::storage::{Vec, MutableVecTrait, StoragePointerWriteAccess};
[storage]
struct Storage {
numbers: Vec<u256>,
}
fn set_number(ref self: ContractState, index: u64, number: u256) {
self.numbers.at(index).write(number);
}
Fully qualified path: core::starknet::storage::vec::MutableVecTrait::at
fn at(self: T, index: u64) -> StoragePath<Mutable<Self::ElementType>>
len
Returns the number of elements in the vector.The length is stored at the vector's base storage address and is automatically updated when elements are appended. # Examples
use starknet::storage::{Vec, MutableVecTrait};
[storage]
struct Storage {
numbers: Vec<u256>,
}
fn is_empty(self: @ContractState) -> bool {
self.numbers.len() == 0
}
Fully qualified path: core::starknet::storage::vec::MutableVecTrait::len
fn len(self: T) -> u64
append
Returns a mutable storage path to write a new element at the end of the vector.This operation: 1. Increments the vector's length 2. Returns a storage path to write the new element # Examples
use starknet::storage::{Vec, MutableVecTrait, StoragePointerWriteAccess};
[storage]
struct Storage {
numbers: Vec<u256>,
}
fn push_number(ref self: ContractState, number: u256) {
self.numbers.append().write(number);
}
Fully qualified path: core::starknet::storage::vec::MutableVecTrait::append
fn append(self: T) -> StoragePath<Mutable<Self::ElementType>>
allocate
Allocates space for a new element at the end of the vector, returning a mutable storage path to write the element.This function is a replacement for the deprecated append
function, which allowed appending new elements to a vector. Unlike append
, allocate
is specifically useful when you need to prepare space for elements of unknown or dynamic size (e.g., appending another vector). # Use Caseallocate
is essential when pushing a vector into another vector, as the size of the nested vector is unknown at compile time. It allows the caller to allocate the required space first, then write the nested vector into the allocated space using .write()
.This is necessary because pushing directly (e.g., vec.push(nested_vec)
) is not supported due to Vec
being only a storage abstraction. # Deprecation NoteThe append
function is now deprecated. Use allocate
to achieve the same functionality with improved clarity and flexibility. # Examples
use starknet::storage::{Vec, MutableVecTrait, StoragePointerWriteAccess};
[storage]
struct Storage {
numbers: Vec<Vec<u256>>,
}
fn append_nested_vector(ref self: ContractState, elements: Array<u256>) {
// Allocate space for the nested vector in the outer vector.
let new_vec_storage_path = self.numbers.allocate();
for element in elements {
new_vec_storage_path.push(element)
}
}
Fully qualified path: core::starknet::storage::vec::MutableVecTrait::allocate
fn allocate(self: T) -> StoragePath<Mutable<Self::ElementType>>
push
Pushes a new value onto the vector.This operation: 1. Increments the vector's length. 2. Writes the provided value to the new storage location at the end of the vector. # NoteIf you need to allocate storage without writing a value (e.g., when appending another vector), consider using allocate
instead. # Examples
use starknet::storage::{Vec, MutableVecTrait};
[storage]
struct Storage {
numbers: Vec<u256>,
}
fn push_number(ref self: ContractState, number: u256) {
self.numbers.push(number);
}
Fully qualified path: core::starknet::storage::vec::MutableVecTrait::push
fn push<+Drop<Self::ElementType>, +starknet::Store<Self::ElementType>>(
self: T, value: Self::ElementType,
)
pop
Pops the last value off the vector.This operation: 1. Retrieves the value stored at the last position in the vector. 2. Decrements the vector's length. 3. Returns the retrieved value or None
if the vector is empty. # Examples
use starknet::storage::{Vec, MutableVecTrait};
[storage]
struct Storage {
numbers: Vec<u256>,
}
fn pop_number(ref self: ContractState) -> Option<u256> {
self.numbers.pop()
}
Fully qualified path: core::starknet::storage::vec::MutableVecTrait::pop
fn pop<+Drop<Self::ElementType>, +starknet::Store<Self::ElementType>>(
self: T,
) -> Option<Self::ElementType>
Trait types
ElementType
Fully qualified path: core::starknet::storage::vec::MutableVecTrait::ElementType
type ElementType;
VecTrait
Provides read-only access to elements in a storage Vec
.This trait enables retrieving elements and checking the vector's length without modifying the underlying storage.
Fully qualified path: core::starknet::storage::vec::VecTrait
pub trait VecTrait<T>
Trait functions
get
Returns a storage path to the element at the specified index, or None
if out of bounds. # Examples
use starknet::storage::{Vec, VecTrait, StoragePointerReadAccess};
[storage]
struct Storage {
numbers: Vec<u256>,
}
fn maybe_number(self: @ContractState, index: u64) -> Option<u256> {
self.numbers.get(index).map(|ptr| ptr.read())
}
Fully qualified path: core::starknet::storage::vec::VecTrait::get
fn get(self: T, index: u64) -> Option<StoragePath<Self::ElementType>>
at
Returns a storage path to access the element at the specified index. # PanicsPanics if the index is out of bounds. # Examples
use starknet::storage::{Vec, VecTrait, StoragePointerReadAccess};
[storage]
struct Storage {
numbers: Vec<u256>,
}
fn get_number(self: @ContractState, index: u64) -> u256 {
self.numbers.at(index).read()
}
Fully qualified path: core::starknet::storage::vec::VecTrait::at
fn at(self: T, index: u64) -> StoragePath<Self::ElementType>
len
Returns the number of elements in the vector.The length is stored at the vector's base storage address and is automatically updated when elements are appended. # Examples
use starknet::storage::{Vec, VecTrait};
[storage]
struct Storage {
numbers: Vec<u256>,
}
fn is_empty(self: @ContractState) -> bool {
self.numbers.len() == 0
}
Fully qualified path: core::starknet::storage::vec::VecTrait::len
fn len(self: T) -> u64
Trait types
ElementType
Fully qualified path: core::starknet::storage::vec::VecTrait::ElementType
type ElementType;
Bytes31Trait
Fully qualified path: core::bytes_31::Bytes31Trait
pub trait Bytes31Trait
Trait functions
at
Returns the byte at the given index (LSB's index is 0).Assumes that index < BYTES_IN_BYTES31
. If the assumption is not met, the behavior is undefined. # Examples
let bytes: bytes31 = 1_u8.into();
assert!(bytes.at(0) == 1);
Fully qualified path: core::bytes_31::Bytes31Trait::at
fn at(self: @bytes31, index: usize) -> u8
ByteArrayTrait
Fully qualified path: core::byte_array::ByteArrayTrait
pub trait ByteArrayTrait
Trait functions
append_word
Appends a single word of len
bytes to the end of the ByteArray
.This function assumes that: 1. word
could be validly converted to a bytes31
which has no more than len
bytes of data. 2. len <= BYTES_IN_BYTES31.If these assumptions are not met, it can corrupt the ByteArray
. Thus, this should be a private function. We could add masking/assertions but it would be more expensive. # Examples
let mut ba = "";
ba.append_word('word', 4);
assert!(ba == "word");
Fully qualified path: core::byte_array::ByteArrayTrait::append_word
fn append_word(ref self: ByteArray, word: felt252, len: usize)
append
Appends a ByteArray
to the end of another ByteArray
. # Examples
let mut ba: ByteArray = "1";
ba.append(@"2");
assert!(ba == "12");
Fully qualified path: core::byte_array::ByteArrayTrait::append
fn append(ref self: ByteArray, other: @ByteArray)
concat
Concatenates two ByteArray
and returns the result.The content of left
is cloned in a new memory segment. # Examples
let ba = "1";
let other_ba = "2";
let result = ByteArrayTrait::concat(@ba, @other_ba);
assert!(result == "12");
Fully qualified path: core::byte_array::ByteArrayTrait::concat
fn concat(left: @ByteArray, right: @ByteArray) -> ByteArray
append_byte
Appends a single byte to the end of the ByteArray
. # Examples
let mut ba = "";
ba.append_byte(0);
assert!(ba == "0");
Fully qualified path: core::byte_array::ByteArrayTrait::append_byte
fn append_byte(ref self: ByteArray, byte: u8)
len
Returns the length of the ByteArray
. # Examples
let ba: ByteArray = "byte array";
let len = ba.len();
assert!(len == 10);
Fully qualified path: core::byte_array::ByteArrayTrait::len
fn len(self: @ByteArray) -> usize
at
Returns an option of the byte at the given index of self
or None
if the index is out of bounds. # Examples
let ba: ByteArray = "byte array";
let byte = ba.at(0).unwrap();
assert!(byte == 98);
Fully qualified path: core::byte_array::ByteArrayTrait::at
fn at(self: @ByteArray, index: usize) -> Option<u8>
rev
Returns a ByteArray
with the reverse order of self
. # Examples
let ba: ByteArray = "123";
let rev_ba = ba.rev();
assert!(rev_ba == "321");
Fully qualified path: core::byte_array::ByteArrayTrait::rev
fn rev(self: @ByteArray) -> ByteArray
append_word_rev
Appends the reverse of the given word to the end of self
.This function assumes that: 1. len < 31 2. word is validly convertible to bytes31 of length len
. # Examples
let mut ba: ByteArray = "";
ba.append_word_rev('123', 3);
assert!(ba == "321");
Fully qualified path: core::byte_array::ByteArrayTrait::append_word_rev
fn append_word_rev(ref self: ByteArray, word: felt252, len: usize)
append_word_fits_into_pending
Appends a single word of len
bytes to the end of the ByteArray
, assuming there is enough space in the pending word (self.pending_word_len + len < BYTES_IN_BYTES31
).word
is of type felt252
but actually represents a bytes31
. It is represented as a felt252
to improve performance of building the ByteArray
.
Fully qualified path: core::byte_array::ByteArrayTrait::append_word_fits_into_pending
fn append_word_fits_into_pending(ref self: ByteArray, word: felt252, len: usize)
append_split_index_lt_16
Appends a single word to the end of self
, given that 0 < split_index < 16
.split_index
is the number of bytes left in self.pending_word
after this function. This is the index of the split (LSB's index is 0).Note: this function doesn't update the new pending length of self
. It's the caller's responsibility.
Fully qualified path: core::byte_array::ByteArrayTrait::append_split_index_lt_16
fn append_split_index_lt_16(ref self: ByteArray, word: felt252, split_index: usize)
append_split_index_16
Appends a single word to the end of self
, given that the index of splitting word
is exactly 16.split_index
is the number of bytes left in self.pending_word
after this function. This is the index of the split (LSB's index is 0).Note: this function doesn't update the new pending length of self
. It's the caller's responsibility.
Fully qualified path: core::byte_array::ByteArrayTrait::append_split_index_16
fn append_split_index_16(ref self: ByteArray, word: felt252)
append_split_index_gt_16
Appends a single word to the end of self
, given that the index of splitting word
is > 16.split_index
is the number of bytes left in self.pending_word
after this function. This is the index of the split (LSB's index is 0).Note: this function doesn't update the new pending length of self
. It's the caller's responsibility.
Fully qualified path: core::byte_array::ByteArrayTrait::append_split_index_gt_16
fn append_split_index_gt_16(ref self: ByteArray, word: felt252, split_index: usize)
append_split
A helper function to append a remainder to self
, by: 1. completing self.pending_word
to a full word using complete_full_word
, assuming it's validly convertible to a bytes31
of length exactly BYTES_IN_BYTES31 - self.pending_word_len
. 2. Setting self.pending_word
to new_pending
.Note: this function doesn't update the new pending length of self
. It's the caller's responsibility.
Fully qualified path: core::byte_array::ByteArrayTrait::append_split
fn append_split(ref self: ByteArray, complete_full_word: felt252, new_pending: felt252)
StringLiteral
Fully qualified path: core::string::StringLiteral
pub trait StringLiteral<T>;
PeekableTrait
Fully qualified path: core::iter::adapters::peekable::PeekableTrait
pub trait PeekableTrait<I, impl IterI: Iterator<I>, +Copy<IterI::Item>, +Drop<IterI::Item>>
Trait functions
peek
Returns a copy to the next() value without advancing the iterator.Like next
, if there is a value, it is wrapped in a Some(T)
. But if the iteration is over, None
is returned. # ExamplesBasic usage:
let mut iter = (1..4_u8).into_iter().peekable();
// peek() lets us see one step into the future
assert_eq!(iter.peek(), Some(1));
assert_eq!(iter.next(), Some(1));
assert_eq!(iter.next(), Some(2));
// The iterator does not advance even if we `peek` multiple times
assert_eq!(iter.peek(), Some(3));
assert_eq!(iter.peek(), Some(3));
assert_eq!(iter.next(), Some(3));
// After the iterator is finished, so is `peek()`
assert_eq!(iter.peek(), None);
assert_eq!(iter.next(), None);
Fully qualified path: core::iter::adapters::peekable::PeekableTrait::peek
fn peek(ref self: Peekable<I, IterI::Item>) -> Option<IterI::Item>
Extend
Extend a collection with the contents of an iterator.Iterators produce a series of values, and collections can also be thought of as a series of values. The Extend
trait bridges this gap, allowing you to extend a collection by including the contents of that iterator. When extending a collection with an already existing key, that entry is updated or, in the case of collections that permit multiple entries with equal keys, that entry is inserted. # ExamplesBasic usage:
let mut arr = array![1, 2];
arr.extend(array![3, 4, 5]);
assert_eq!(arr, array![1, 2, 3, 4, 5]);
Fully qualified path: core::iter::traits::collect::Extend
pub trait Extend<T, A>
Trait functions
extend
Extends a collection with the contents of an iterator.
Fully qualified path: core::iter::traits::collect::Extend::extend
fn extend<
I,
impl IntoIter: IntoIterator<I>,
+TypeEqual<IntoIter::Iterator::Item, A>,
+Destruct<IntoIter::IntoIter>,
+Destruct<I>,
>(
ref self: T, iter: I,
)
FromIterator
Conversion from an Iterator
.By implementing FromIterator
for a type, you define how it will be created from an iterator. This is common for types which describe a collection of some kind.If you want to create a collection from the contents of an iterator, the Iterator::collect()
method is preferred. However, when you need to specify the container type, FromIterator::from_iter()
can be more readable than using a turbofish (e.g. ::<Array<_>>()
). See the Iterator::collect()
documentation for more examples of its use.See also: IntoIterator
. # ExamplesBasic usage:
let v = FromIterator::from_iter(0..5_u32);
assert_eq!(v, array![0, 1, 2, 3, 4]);
Implementing FromIterator
for your type:
use core::metaprogramming::TypeEqual;
// A sample collection, that's just a wrapper over Array<T>
[derive(Drop, Debug)]
struct MyCollection {
arr: Array<u32>,
}
// Let's give it some methods so we can create one and add things
// to it.
[generate_trait]
impl MyCollectionImpl of MyCollectionTrait {
fn new() -> MyCollection {
MyCollection { arr: ArrayTrait::new() }
}
fn add(ref self: MyCollection, elem: u32) {
self.arr.append(elem);
}
}
// and we'll implement FromIterator
impl MyCollectionFromIterator of FromIterator<MyCollection, u32> {
fn from_iter<
I,
impl IntoIter: IntoIterator<I>,
+TypeEqual<IntoIter::Iterator::Item, u32>,
+Destruct<IntoIter::IntoIter>,
+Destruct<I>,
>(
iter: I
) -> MyCollection {
let mut c = MyCollectionTrait::new();
for i in iter {
c.add(i);
};
c
}
}
// Now we can make a new iterator...
let iter = (0..5_u32).into_iter();
// ... and make a MyCollection out of it
let c = FromIterator::<MyCollection>::from_iter(iter);
assert_eq!(c.arr, array![0, 1, 2, 3, 4]);
Fully qualified path: core::iter::traits::collect::FromIterator
pub trait FromIterator<T, A>
Trait functions
from_iter
Creates a value from an iterator.See the module-level documentation for more. # Examples
let iter = (0..5_u32).into_iter();
let v = FromIterator::from_iter(iter);
assert_eq!(v, array![0, 1, 2, 3, 4]);
Fully qualified path: core::iter::traits::collect::FromIterator::from_iter
fn from_iter<
I,
impl IntoIter: IntoIterator<I>,
+TypeEqual<IntoIter::Iterator::Item, A>,
+Destruct<IntoIter::IntoIter>,
+Destruct<I>,
>(
iter: I,
) -> T
IntoIterator
Conversion into an Iterator
.By implementing IntoIterator
for a type, you define how it will be converted to an iterator. This is common for types which describe a collection of some kind.One benefit of implementing IntoIterator
is that your type will work with Cairo's for
loop syntax.See also: FromIterator
. # ExamplesBasic usage:
let mut iter = array![1, 2, 3].into_iter();
assert!(Some(1) == iter.next());
assert!(Some(2) == iter.next());
assert!(Some(3) == iter.next());
assert!(None == iter.next());
Implementing IntoIterator
for your type:
// A sample collection, that's just a wrapper over `Array<u32>`
[derive(Drop, Debug)]
struct MyCollection {
arr: Array<u32>
}
// Let's give it some methods so we can create one and add things
// to it.
[generate_trait]
impl MyCollectionImpl of MyCollectionTrait {
fn new() -> MyCollection {
MyCollection {
arr: ArrayTrait::new()
}
}
fn add(ref self: MyCollection, elem: u32) {
self.arr.append(elem);
}
}
// and we'll implement `IntoIterator`
impl MyCollectionIntoIterator of IntoIterator<MyCollection> {
type IntoIter = core::array::ArrayIter<u32>;
fn into_iter(self: MyCollection) -> Self::IntoIter {
self.arr.into_iter()
}
}
// Now we can make a new collection...
let mut c = MyCollectionTrait::new();
// ... add some stuff to it ...
c.add(0);
c.add(1);
c.add(2);
// ... and then turn it into an `Iterator`:
let mut n = 0;
for i in c {
assert!(i == n);
n += 1;
};
Fully qualified path: core::iter::traits::collect::IntoIterator
pub trait IntoIterator<T>
Trait functions
into_iter
Creates an iterator from a value.See the module-level documentation for more. # Examples
let mut iter = array![1, 2, 3].into_iter();
assert_eq!(Some(1), iter.next());
assert_eq!(Some(2), iter.next());
assert_eq!(Some(3), iter.next());
assert_eq!(None, iter.next());
Fully qualified path: core::iter::traits::collect::IntoIterator::into_iter
fn into_iter(self: T) -> Self::IntoIter
Trait types
IntoIter
The iterator type that will be created.
Fully qualified path: core::iter::traits::collect::IntoIterator::IntoIter
type IntoIter;
Iterator
A trait for dealing with iterators.This is the main iterator trait. For more about the concept of iterators generally, please see the [module-level documentation](module-level documentation). In particular, you may want to know how to [implement Iterator
][impl].[module-level documentation](module-level documentation): crate::iter impl: crate::iter#implementing-iterator
Fully qualified path: core::iter::traits::iterator::Iterator
pub trait Iterator<T>
Trait functions
next
Advances the iterator and returns the next value.Returns None
when iteration is finished. Individual iterator implementations may choose to resume iteration, and so calling next()
again may or may not eventually start returning Some(Item)
again at some point.Some(Item)
: Some None
: None # Examples
let mut iter = [1, 2, 3].span().into_iter();
// A call to next() returns the next value...
assert_eq!(Some(@1), iter.next());
assert_eq!(Some(@2), iter.next());
assert_eq!(Some(@3), iter.next());
// ... and then None once it's over.
assert_eq!(None, iter.next());
// More calls may or may not return `None`. Here, they always will.
assert_eq!(None, iter.next());
assert_eq!(None, iter.next());
Fully qualified path: core::iter::traits::iterator::Iterator::next
fn next(ref self: T) -> Option<Self::Item>
count
Consumes the iterator, counting the number of iterations and returning it.This method will call next
repeatedly until None
is encountered, returning the number of times it saw Some
. Note that next
has to be called at least once even if the iterator does not have any elements. # Overflow BehaviorThe method does no guarding against overflows, so counting elements of an iterator with more than Bounded::<usize>::MAX
elements either produces the wrong result or panics. # PanicsThis function might panic if the iterator has more than Bounded::<usize>::MAX
elements. # Examples
let mut a = array![1, 2, 3].into_iter();
assert_eq!(a.count(), 3);
let mut a = array![1, 2, 3, 4, 5].into_iter();
assert_eq!(a.count(), 5);
Fully qualified path: core::iter::traits::iterator::Iterator::count
fn count<+Destruct<T>, +Destruct<Self::Item>>(self: T) -> usize
last
Consumes the iterator, returning the last element.This method will evaluate the iterator until it returns None
. While doing so, it keeps track of the current element. After None
is returned, last()
will then return the last element it saw. # Examples
let mut a = array![1, 2, 3].into_iter();
assert_eq!(a.last(), Option::Some(3));
let mut a = array![].into_iter();
assert_eq!(a.last(), Option::None);
Fully qualified path: core::iter::traits::iterator::Iterator::last
fn last<+Destruct<T>, +Destruct<Self::Item>>(self: T) -> Option<Self::Item>
advance_by
Advances the iterator by n
elements.This method will eagerly skip n
elements by calling next
up to n
times until None
is encountered.advance_by(n)
will return Ok(())
if the iterator successfully advances by n
elements, or a Err(NonZero<usize>)
with value k
if None
is encountered, where k
is remaining number of steps that could not be advanced because the iterator ran out. If self
is empty and n
is non-zero, then this returns Err(n)
. Otherwise, k
is always less than n
.None
: None next
: Iterator::next # Examples
let mut iter = array![1_u8, 2, 3, 4].into_iter();
assert_eq!(iter.advance_by(2), Ok(()));
assert_eq!(iter.next(), Some(3));
assert_eq!(iter.advance_by(0), Ok(()));
assert_eq!(iter.advance_by(100), Err(99));
Fully qualified path: core::iter::traits::iterator::Iterator::advance_by
fn advance_by<+Destruct<T>, +Destruct<Self::Item>>(
ref self: T, n: usize,
) -> Result<(), NonZero<usize>>
nth
Returns the n
th element of the iterator.Like most indexing operations, the count starts from zero, so nth(0)
returns the first value, nth(1)
the second, and so on.Note that all preceding elements, as well as the returned element, will be consumed from the iterator. That means that the preceding elements will be discarded, and also that calling nth(0)
multiple times on the same iterator will return different elements.nth()
will return None
if n
is greater than or equal to the length of the iterator. # ExamplesBasic usage:
let mut iter = array![1, 2, 3].into_iter();
assert_eq!(iter.nth(1), Some(2));
Calling nth()
multiple times doesn't rewind the iterator:
let mut iter = array![1, 2, 3].into_iter();
assert_eq!(iter.nth(1), Some(2));
assert_eq!(iter.nth(1), None);
Returning None
if there are less than n + 1
elements:
let mut iter = array![1, 2, 3].into_iter();
assert_eq!(iter.nth(10), None);
Fully qualified path: core::iter::traits::iterator::Iterator::nth
fn nth<+Destruct<T>, +Destruct<Self::Item>>(ref self: T, n: usize) -> Option<Self::Item>
map
Takes a closure and creates an iterator which calls that closure on each element.map()
transforms one iterator into another, by means of its argument: something that implements FnOnce
. It produces a new iterator which calls this closure on each element of the original iterator.If you are good at thinking in types, you can think of map()
like this: If you have an iterator that gives you elements of some type A
, and you want an iterator of some other type B
, you can use map()
, passing a closure that takes an A
and returns a B
.map()
is conceptually similar to a for
loop. However, as map()
is lazy, it is best used when you're already working with other iterators. If you're doing some sort of looping for a side effect, it's considered more idiomatic to use for
than map()
. # ExamplesBasic usage:
let mut iter = array![1, 2, 3].into_iter().map(|x| 2 * x);
assert!(iter.next() == Some(2));
assert!(iter.next() == Some(4));
assert!(iter.next() == Some(6));
assert!(iter.next() == None);
If you're doing some sort of side effect, prefer for
to map()
:
// don't do this:
let _ = (0..5_usize).into_iter().map(|x| println!("{x}"));
// it won't even execute, as it is lazy. Cairo will warn you about this if not specifically
ignored, as is done here.
// Instead, use for:
for x in 0..5_usize {
println!("{x}");
}
Fully qualified path: core::iter::traits::iterator::Iterator::map
fn map<B, F, +core::ops::Fn<F, (Self::Item,)>[Output: B], +Drop<T>, +Drop<F>>(
self: T, f: F,
) -> Map<T, F>
enumerate
Creates an iterator which gives the current iteration count as well as the next value.The iterator returned yields pairs (i, val)
, where i
is the current index of iteration and val
is the value returned by the iterator.enumerate()
keeps its count as a usize
. # Overflow BehaviorThe method does no guarding against overflows, so enumerating more than Bounded::<usize>::MAX
elements will always panic. # PanicsWill panic if the to-be-returned index overflows a usize
. # Examples
let mut iter = array!['a', 'b', 'c'].into_iter().enumerate();
assert_eq!(iter.next(), Some((0, 'a')));
assert_eq!(iter.next(), Some((1, 'b')));
assert_eq!(iter.next(), Some((2, 'c')));
assert_eq!(iter.next(), None);
Fully qualified path: core::iter::traits::iterator::Iterator::enumerate
fn enumerate(self: T) -> Enumerate<T>
fold
Folds every element into an accumulator by applying an operation, returning the final result.fold()
takes two arguments: an initial value, and a closure with two arguments: an 'accumulator', and an element. The closure returns the value that the accumulator should have for the next iteration.The initial value is the value the accumulator will have on the first call.After applying this closure to every element of the iterator, fold()
returns the accumulator.Folding is useful whenever you have a collection of something, and want to produce a single value from it.Note: fold()
, and similar methods that traverse the entire iterator, might not terminate for infinite iterators, even on traits for which a result is determinable in finite time.Note: fold()
combines elements in a left-associative fashion. For associative operators like +
, the order the elements are combined in is not important, but for non-associative operators like -
the order will affect the final result. # Note to ImplementersSeveral of the other (forward) methods have default implementations in terms of this one, so try to implement this explicitly if it can do something better than the default for
loop implementation.In particular, try to have this call fold()
on the internal parts from which this iterator is composed. # ExamplesBasic usage:
let mut iter = array![1, 2, 3].into_iter();
// the sum of all of the elements of the array
let sum = iter.fold(0, |acc, x| acc + x);
assert_eq!(sum, 6);
Let's walk through each step of the iteration here:| element | acc | x | result | |---------|-----|---|--------| | | 0 | | | | 1 | 0 | 1 | 1 | | 2 | 1 | 2 | 3 | | 3 | 3 | 3 | 6 |And so, our final result, 6
.It's common for people who haven't used iterators a lot to use a for
loop with a list of things to build up a result. Those can be turned into fold()
s:
let mut numbers = array![1, 2, 3, 4, 5].span();
let mut result = 0;
// for loop:
for i in numbers{
result = result + (*i);
};
// fold:
let mut numbers_iter = numbers.into_iter();
let result2 = numbers_iter.fold(0, |acc, x| acc + (*x));
// they're the same
assert_eq!(result, result2);
Fully qualified path: core::iter::traits::iterator::Iterator::fold
fn fold<
B, F, +core::ops::Fn<F, (B, Self::Item)>[Output: B], +Destruct<T>, +Destruct<F>, +Destruct<B>,
>(
ref self: T, init: B, f: F,
) -> B
any
Tests if any element of the iterator matches a predicate.any()
takes a closure that returns true
or false
. It applies this closure to each element of the iterator, and if any of them return true
, then so does any()
. If they all return false
, it returns false
.any()
is short-circuiting; in other words, it will stop processing as soon as it finds a true
, given that no matter what else happens, the result will also be true
.An empty iterator returns false
. # ExamplesBasic usage:
assert!(array![1, 2, 3].into_iter().any(|x| x == 2));
assert!(!array![1, 2, 3].into_iter().any(|x| x > 5));
Fully qualified path: core::iter::traits::iterator::Iterator::any
fn any<
P,
+core::ops::Fn<P, (Self::Item,)>[Output: bool],
+Destruct<P>,
+Destruct<T>,
+Destruct<Self::Item>,
>(
ref self: T, predicate: P,
) -> bool
all
Tests if every element of the iterator matches a predicate.all()
takes a closure that returns true
or false
. It applies this closure to each element of the iterator, and if all of them return true
, then so does all()
. If any of them return false
, it returns false
.all()
is short-circuiting; in other words, it will stop processing as soon as it finds a false
, given that no matter what else happens, the result will also be false
.An empty iterator returns true
. # ExamplesBasic usage:
assert!(array![1, 2, 3].into_iter().all(|x| x > 0));
assert!(!array![1, 2, 3].into_iter().all(|x| x > 2));
Fully qualified path: core::iter::traits::iterator::Iterator::all
fn all<
P,
+core::ops::Fn<P, (Self::Item,)>[Output: bool],
+Destruct<P>,
+Destruct<T>,
+Destruct<Self::Item>,
>(
ref self: T, predicate: P,
) -> bool
find
Searches for an element of an iterator that satisfies a predicate.find()
takes a closure that returns true
or false
. It applies this closure to each element of the iterator as a snapshot, and if any of them return true
, then find()
returns Some(element)
. If they all return false
, it returns None
.find()
is short-circuiting; in other words, it will stop processing as soon as the closure returns true
. # ExamplesBasic usage:
let mut iter = array![1, 2, 3].into_iter();
assert_eq!(iter.find(|x| *x == 2), Option::Some(2));
assert_eq!(iter.find(|x| *x == 5), Option::None);
Stopping at the first true
:
let mut iter = array![1, 2, 3].into_iter();
assert_eq!(iter.find(|x| *x == 2), Option::Some(2));
// we can still use `iter`, as there are more elements.
assert_eq!(iter.next(), Option::Some(3));
Note that iter.find(f)
is equivalent to iter.filter(f).next()
.
Fully qualified path: core::iter::traits::iterator::Iterator::find
fn find<
P,
+core::ops::Fn<P, (@Self::Item,)>[Output: bool],
+Destruct<P>,
+Destruct<T>,
+Destruct<Self::Item>,
>(
ref self: T, predicate: P,
) -> Option<Self::Item>
filter
Creates an iterator which uses a closure to determine if an element should be yielded. The closure takes each element as a snapshot.Given an element the closure must return true
or false
. The returned iterator will yield only the elements for which the closure returns true
. # ExamplesBasic usage:
let a = array![0_u32, 1, 2];
let mut iter = a.into_iter().filter(|x| *x > 0);
assert_eq!(iter.next(), Option::Some(1));
assert_eq!(iter.next(), Option::Some(2));
assert_eq!(iter.next(), Option::None);
Note that iter.filter(f).next()
is equivalent to iter.find(f)
.
Fully qualified path: core::iter::traits::iterator::Iterator::filter
fn filter<
P,
+core::ops::Fn<P, (@Self::Item,)>[Output: bool],
+Destruct<P>,
+Destruct<T>,
+Destruct<Self::Item>,
>(
self: T, predicate: P,
) -> Filter<T, P>
zip
'Zips up' two iterators into a single iterator of pairs.zip()
returns a new iterator that will iterate over two other iterators, returning a tuple where the first element comes from the first iterator, and the second element comes from the second iterator.In other words, it zips two iterators together, into a single one.If either iterator returns None
, next
from the zipped iterator will return None
. If the zipped iterator has no more elements to return then each further attempt to advance it will first try to advance the first iterator at most one time and if it still yielded an item try to advance the second iterator at most one time. # ExamplesBasic usage:
let mut iter = array![1, 2, 3].into_iter().zip(array![4, 5, 6].into_iter());
assert_eq!(iter.next(), Some((1, 4)));
assert_eq!(iter.next(), Some((2, 5)));
assert_eq!(iter.next(), Some((3, 6)));
assert_eq!(iter.next(), None);
Since the argument to zip()
uses IntoIterator
, we can pass anything that can be converted into an Iterator
, not just an Iterator
itself. For example:
let mut iter = array![1, 2, 3].into_iter().zip(array![4, 5, 6]);
assert_eq!(iter.next(), Some((1, 4)));
assert_eq!(iter.next(), Some((2, 5)));
assert_eq!(iter.next(), Some((3, 6)));
assert_eq!(iter.next(), None);
enumerate
: Iterator::enumerate next
: Iterator::next
Fully qualified path: core::iter::traits::iterator::Iterator::zip
fn zip<U, impl UIntoIter: IntoIterator<U>, +Destruct<T>>(
self: T, other: U,
) -> Zip<T, UIntoIter::IntoIter>
collect
Transforms an iterator into a collection.collect()
can take anything iterable, and turn it into a relevant collection. This is one of the more powerful methods in the core library, used in a variety of contexts.The most basic pattern in which collect()
is used is to turn one collection into another. You take a collection, call iter
on it, do a bunch of transformations, and then collect()
at the end.collect()
can also create instances of types that are not typical collections.Because collect()
is so general, it can cause problems with type inference. As such, collect()
is one of the few times you'll see the syntax affectionately known as the 'turbofish': ::<>
. This helps the inference algorithm understand specifically which collection you're trying to collect into. # ExamplesBasic usage:
let doubled: Array<u32> = array![1, 2, 3].into_iter().map(|x| x * 2).collect();
assert_eq!(array![2, 4, 6], doubled);
Note that we needed the : Array<u32>
on the left-hand side.Using the 'turbofish' instead of annotating doubled
:
let doubled = array![1, 2, 3].into_iter().map(|x| x * 2).collect::<Array<u32>>();
assert_eq!(array![2, 4, 6], doubled);
Because collect()
only cares about what you're collecting into, you can still use a partial type hint, _
, with the turbofish:
let doubled = array![1, 2, 3].into_iter().map(|x| x * 2).collect::<Array<_>>();
assert_eq!(array![2, 4, 6], doubled);
Fully qualified path: core::iter::traits::iterator::Iterator::collect
fn collect<
B,
impl IntoIter: IntoIterator<T>,
impl ItemEqual: TypeEqual<IntoIter::Iterator::Item, Self::Item>,
+Destruct<IntoIter::IntoIter>,
+FromIterator<B, Self::Item>,
+Destruct<T>,
>(
self: T,
) -> B
peekable
Creates an iterator which can use the peek
method to look at the next element of the iterator. See its documentation for more information.Note that the underlying iterator is still advanced when peek
is called for the first time: In order to retrieve the next element, next
is called on the underlying iterator, hence any side effects (i.e. anything other than fetching the next value) of the next
method will occur. # ExamplesBasic usage:
let mut iter = (1..4_u8).into_iter().peekable();
// peek() lets us see one step into the future
assert_eq!(iter.peek(), Option::Some(1));
assert_eq!(iter.next(), Option::Some(1));
assert_eq!(iter.next(), Option::Some(2));
// we can peek() multiple times, the iterator won't advance
assert_eq!(iter.peek(), Option::Some(3));
assert_eq!(iter.peek(), Option::Some(3));
assert_eq!(iter.next(), Option::Some(3));
// after the iterator is finished, so is peek()
assert_eq!(iter.peek(), Option::None);
assert_eq!(iter.next(), Option::None);
Fully qualified path: core::iter::traits::iterator::Iterator::peekable
fn peekable(self: T) -> Peekable<T, Self::Item>
take
Creates an iterator that yields the first n
elements, or fewer if the underlying iterator ends sooner.take(n)
yields elements until n
elements are yielded or the end of the iterator is reached (whichever happens first). The returned iterator is a prefix of length n
if the original iterator contains at least n
elements, otherwise it contains all of the (fewer than n
) elements of the original iterator. # ExamplesBasic usage:
let mut iter = array![1, 2, 3].into_iter().take(2);
assert_eq!(iter.next(), Some(1));
assert_eq!(iter.next(), Some(2));
assert_eq!(iter.next(), None);
If less than n
elements are available, take
will limit itself to the size of the underlying iterator:
let mut iter = array![1, 2].into_iter().take(5);
assert_eq!(iter.next(), Some(1));
assert_eq!(iter.next(), Some(2));
assert_eq!(iter.next(), None);
Fully qualified path: core::iter::traits::iterator::Iterator::take
fn take(self: T, n: usize) -> Take<T>
sum
Sums the elements of an iterator.Takes each element, adds them together, and returns the result.An empty iterator returns the zero value of the type.sum()
can be used to sum any type implementing [Sum
][core::iter::Sum
], including [Option
][Option::sum
] and [Result
][Result::sum
]. # PanicsWhen calling sum()
and a primitive integer type is being returned, this method will panic if the computation overflows. # Examples
let mut iter = array![1, 2, 3].into_iter();
let sum: usize = iter.sum();
assert_eq!(sum, 6);
Fully qualified path: core::iter::traits::iterator::Iterator::sum
fn sum<+Destruct<T>, +Destruct<Self::Item>, +Sum<Self::Item>>(self: T) -> Self::Item
product
Iterates over the entire iterator, multiplying all the elementsAn empty iterator returns the one value of the type. # PanicsWhen calling product()
and a primitive integer type is being returned, this method will panic if the computation overflows. # Examples
fn factorial(n: u32) -> u32 {
(1..=n).into_iter().product()
}
assert_eq!(factorial(0), 1);
assert_eq!(factorial(1), 1);
assert_eq!(factorial(5), 120);
Fully qualified path: core::iter::traits::iterator::Iterator::product
fn product<+Destruct<T>, +Destruct<Self::Item>, +Product<Self::Item>>(self: T) -> Self::Item
chain
Takes two iterators and creates a new iterator over both in sequence.chain()
will return a new iterator which will first iterate over values from the first iterator and then over values from the second iterator.In other words, it links two iterators together, in a chain. 🔗Arguments do not have to be of the same type as long as the underlying iterated over items are. # ExamplesBasic usage:
use core::ops::Range;
let a: Array<u8> = array![7, 8, 9];
let b: Range<u8> = 0..5;
let mut iter = a.into_iter().chain(b.into_iter());
assert_eq!(iter.next(), Option::Some(7));
assert_eq!(iter.next(), Option::Some(8));
assert_eq!(iter.next(), Option::Some(9));
assert_eq!(iter.next(), Option::Some(0));
assert_eq!(iter.next(), Option::Some(1));
assert_eq!(iter.next(), Option::Some(2));
assert_eq!(iter.next(), Option::Some(3));
assert_eq!(iter.next(), Option::Some(4));
assert_eq!(iter.next(), Option::None);
Since the argument to chain()
uses IntoIterator
, we can pass anything that can be converted into an Iterator
, not just an Iterator
itself. For example, arrays implement IntoIterator
, and so can be passed to chain()
directly:
let a = array![1, 2, 3];
let b = array![4, 5, 6];
let mut iter = a.into_iter().chain(b);
assert_eq!(iter.next(), Option::Some(1));
assert_eq!(iter.next(), Option::Some(2));
assert_eq!(iter.next(), Option::Some(3));
assert_eq!(iter.next(), Option::Some(4));
assert_eq!(iter.next(), Option::Some(5));
assert_eq!(iter.next(), Option::Some(6));
assert_eq!(iter.next(), Option::None);
Fully qualified path: core::iter::traits::iterator::Iterator::chain
fn chain<
U,
impl IntoIterU: IntoIterator<U>,
+TypeEqual<Self::Item, IntoIterU::Iterator::Item>,
+Destruct<T>,
>(
self: T, other: U,
) -> Chain<T, IntoIterU::IntoIter>
Trait types
Item
The type of the elements being iterated over.
Fully qualified path: core::iter::traits::iterator::Iterator::Item
type Item;
TypeEqual
A trait that can be used to disable implementations based on the types of the generic args. Assumes that TypeEqualImpl<T>
is the only implementation of this trait.Primarily used for optimizations by enabling type-specific implementations. Since TypeEqualImpl<T>
is the only implementation, adding -TypeEqual<T, U>
as a trait bound ensures the implementation is only available when T and U are different types.
Fully qualified path: core::metaprogramming::TypeEqual
pub trait TypeEqual<S, T>
AppendFormattedToByteArray
A trait for appending the ASCII representation of a number to an existing ByteArray
.
Fully qualified path: core::to_byte_array::AppendFormattedToByteArray
pub trait AppendFormattedToByteArray<T>
Trait functions
append_formatted_to_byte_array
Appends the ASCII representation of the value to the provided ByteArray
. # Examples
use core::to_byte_array::AppendFormattedToByteArray;
let mut buffer = "Count: ";
let num: u32 = 42;
num.append_formatted_to_byte_array(ref buffer, 10);
assert!(buffer == "Count: 42");
Fully qualified path: core::to_byte_array::AppendFormattedToByteArray::append_formatted_to_byte_array
fn append_formatted_to_byte_array(self: @T, ref byte_array: ByteArray, base: NonZero<T>)
FormatAsByteArray
A trait for formatting values into their ASCII string representation in a ByteArray
.
Fully qualified path: core::to_byte_array::FormatAsByteArray
pub trait FormatAsByteArray<T>
Trait functions
format_as_byte_array
Returns a new ByteArray
containing the ASCII representation of the value. # Examples
use core::to_byte_array::FormatAsByteArray;
let num: u32 = 42;
let formatted = num.format_as_byte_array(16);
assert!(formatted, "2a");
Fully qualified path: core::to_byte_array::FormatAsByteArray::format_as_byte_array
fn format_as_byte_array(self: @T, base: NonZero<T>) -> ByteArray
Impls
CircuitElementDrop
Fully qualified path: core::circuit::CircuitElementDrop
pub impl CircuitElementDrop<T> of Drop<CircuitElement<T>>;
CircuitElementCopy
Fully qualified path: core::circuit::CircuitElementCopy
pub impl CircuitElementCopy<T> of Copy<CircuitElement<T>>;
DestructFailureGuarantee
Fully qualified path: core::circuit::DestructFailureGuarantee
pub impl DestructFailureGuarantee of Destruct<CircuitFailureGuarantee>
Impl functions
destruct
Fully qualified path: core::circuit::DestructFailureGuarantee::destruct
fn destruct(self: CircuitFailureGuarantee) nopanic
SpanIndex
Fully qualified path: core::array::SpanIndex
pub impl SpanIndex<T> of IndexView<Span<T>, usize, @T>
Impl functions
index
Returns a snapshot of the element at the given index. # Examples
let span: @Span<u8> = @array![1, 2, 3].span();
let element: @u8 = span[0];
assert!(element == @1);
Fully qualified path: core::array::SpanIndex::index
fn index(self: @Span<T>, index: usize) -> @T
DestructOption
Fully qualified path: core::option::DestructOption
pub impl DestructOption<T, +Destruct<T>, -Drop<Option<T>>> of Destruct<Option<T>>
Impl functions
destruct
Fully qualified path: core::option::DestructOption::destruct
fn destruct(self: Option<T>) nopanic
EcStateImpl
Fully qualified path: core::ec::EcStateImpl
pub impl EcStateImpl of EcStateTrait
Impl functions
init
Initializes an EC computation with the zero point. # Examples
let mut state = EcStateTrait::init();
Fully qualified path: core::ec::EcStateImpl::init
fn init() -> EcState nopanic
add
Adds a point to the computation. # Argumentsp
- The non-zero point to add
Fully qualified path: core::ec::EcStateImpl::add
fn add(ref self: EcState, p: NonZeroEcPoint) nopanic
sub
Subtracts a point to the computation. # Argumentsp
- The non-zero point to subtract
Fully qualified path: core::ec::EcStateImpl::sub
fn sub(ref self: EcState, p: NonZeroEcPoint)
add_mul
Adds the product p * scalar
to the state. # Argumentsscalar
- The scalar to multiply the point by * p
- The non-zero point to multiply and add
Fully qualified path: core::ec::EcStateImpl::add_mul
fn add_mul(ref self: EcState, scalar: felt252, p: NonZeroEcPoint) nopanic
finalize_nz
Finalizes the EC computation and returns the result as a non-zero point. # ReturnsOption<NonZeroEcPoint>
- The resulting point, or None if the result is the zero point # PanicsPanics if the result is the point at infinity.
Fully qualified path: core::ec::EcStateImpl::finalize_nz
fn finalize_nz(self: EcState) -> Option<NonZeroEcPoint> nopanic
finalize
Finalizes the EC computation and returns the result.Returns the zero point if the computation results in the point at infinity.
Fully qualified path: core::ec::EcStateImpl::finalize
fn finalize(self: EcState) -> EcPoint
EcPointImpl
Fully qualified path: core::ec::EcPointImpl
pub impl EcPointImpl of EcPointTrait
Impl functions
new
Creates a new EC point from its (x, y) coordinates. # Argumentsx
- The x-coordinate of the point * y
- The y-coordinate of the point # ReturnsReturns None
if the point (x, y) is not on the curve. # Examples
let point = EcPointTrait::new(
x: 336742005567258698661916498343089167447076063081786685068305785816009957563,
y: 1706004133033694959518200210163451614294041810778629639790706933324248611779,
).unwrap();
Fully qualified path: core::ec::EcPointImpl::new
fn new(x: felt252, y: felt252) -> Option<EcPoint>
new_nz
Creates a new NonZero EC point from its (x, y) coordinates.
Fully qualified path: core::ec::EcPointImpl::new_nz
fn new_nz(x: felt252, y: felt252) -> Option<NonZeroEcPoint>
new_from_x
Creates a new EC point from its x coordinate. # Argumentsx
- The x-coordinate of the point # ReturnsReturns None
if no point with the given x-coordinate exists on the curve. # PanicsPanics if x
is 0, as this would be the point at infinity. # Examples
let valid = EcPointTrait::new_from_x(1);
assert!(valid.is_some());
let invalid = EcPointTrait::new_from_x(0);
assert!(invalid.is_none());
Fully qualified path: core::ec::EcPointImpl::new_from_x
fn new_from_x(x: felt252) -> Option<EcPoint>
new_nz_from_x
Creates a new NonZero EC point from its x coordinate.
Fully qualified path: core::ec::EcPointImpl::new_nz_from_x
fn new_nz_from_x(x: felt252) -> Option<NonZeroEcPoint>
coordinates
Returns the coordinates of the EC point. # ReturnsA tuple containing the (x, y) coordinates of the point. # PanicsPanics if the point is the point at infinity. # Examples
let point_nz = EcPointTrait::new_nz_from_x(1).unwrap();
let (x, _y) = point_nz.coordinates();
assert!(x == 1);
Fully qualified path: core::ec::EcPointImpl::coordinates
fn coordinates(self: NonZeroEcPoint) -> (felt252, felt252)
x
Returns the x coordinate of the EC point. # PanicsPanics if the point is the point at infinity. # Examples
let point_nz = EcPointTrait::new_nz_from_x(1).unwrap();
let x = point_nz.x();
assert!(x == 1);
Fully qualified path: core::ec::EcPointImpl::x
fn x(self: NonZeroEcPoint) -> felt252
y
Returns the y coordinate of the EC point. # PanicsPanics if the point is the point at infinity. # Examples
let gen_point =
EcPointTrait::new_nz_from_x(0x1ef15c18599971b7beced415a40f0c7deacfd9b0d1819e03d723d8bc943cfca).unwrap();
let y = gen_point.y();
assert!(y == 0x5668060aa49730b7be4801df46ec62de53ecd11abe43a32873000c36e8dc1f);
Fully qualified path: core::ec::EcPointImpl::y
fn y(self: NonZeroEcPoint) -> felt252
mul
Computes the product of an EC point by the given scalar. # Argumentsscalar
- The scalar to multiply the point by # ReturnsThe resulting point after scalar multiplication.
Fully qualified path: core::ec::EcPointImpl::mul
fn mul(self: EcPoint, scalar: felt252) -> EcPoint
PedersenImpl
A trait for creating a new Pedersen hash state.
Fully qualified path: core::pedersen::PedersenImpl
pub impl PedersenImpl of PedersenTrait
Impl functions
new
Creates a new Pedersen hash state with the given base value. # Examples
use core::pedersen::PedersenTrait;
let mut state = PedersenTrait::new(0);
assert!(state.state == 0);
Fully qualified path: core::pedersen::PedersenImpl::new
fn new(base: felt252) -> HashState
PoseidonImpl
A trait for creating a new Poseidon hash state.
Fully qualified path: core::poseidon::PoseidonImpl
pub impl PoseidonImpl of PoseidonTrait
Impl functions
new
Creates an initial state with all fields set to 0. # Examples
use core::poseidon::PoseidonTrait;
let mut state = PoseidonTrait::new();
Fully qualified path: core::poseidon::PoseidonImpl::new
fn new() -> HashState
SubPointersDeref
This makes the sub-pointers members directly accessible from a pointer to the parent struct.
Fully qualified path: core::starknet::storage::SubPointersDeref
pub impl SubPointersDeref<T, +SubPointers<T>> of core::ops::Deref<StoragePointer<T>>
Impl functions
deref
Fully qualified path: core::starknet::storage::SubPointersDeref::deref
fn deref(self: StoragePointer<T>) -> Self::Target
Impl types
Target
Fully qualified path: core::starknet::storage::SubPointersDeref::Target
type Target = SubPointers::<T>::SubPointersType;
SubPointersMutDeref
This makes the sub-pointers members directly accessible from a pointer to the parent struct.
Fully qualified path: core::starknet::storage::SubPointersMutDeref
pub impl SubPointersMutDeref<T, +SubPointersMut<T>> of core::ops::Deref<StoragePointer<Mutable<T>>>
Impl functions
deref
Fully qualified path: core::starknet::storage::SubPointersMutDeref::deref
fn deref(self: StoragePointer<Mutable<T>>) -> Self::Target
Impl types
Target
Fully qualified path: core::starknet::storage::SubPointersMutDeref::Target
type Target = SubPointersMut::<T>::SubPointersType;
StorableStoragePointerReadAccess
Simple implementation of StoragePointerReadAccess
for any type that implements Store
for any offset.
Fully qualified path: core::starknet::storage::StorableStoragePointerReadAccess
pub impl StorableStoragePointerReadAccess<
T, +starknet::Store<T>,
> of StoragePointerReadAccess<StoragePointer<T>>
Impl functions
read
Fully qualified path: core::starknet::storage::StorableStoragePointerReadAccess::read
fn read(self: @StoragePointer<T>) -> T
Impl types
Value
Fully qualified path: core::starknet::storage::StorableStoragePointerReadAccess::Value
type Value = T;
StorageNodeDeref
This makes the storage node members directly accessible from a path to the parent struct.
Fully qualified path: core::starknet::storage::StorageNodeDeref
pub impl StorageNodeDeref<T, +StorageNode<T>> of core::ops::Deref<StoragePath<T>>
Impl functions
deref
Fully qualified path: core::starknet::storage::StorageNodeDeref::deref
fn deref(self: StoragePath<T>) -> Self::Target
Impl types
Target
Fully qualified path: core::starknet::storage::StorageNodeDeref::Target
type Target = StorageNode::<T>::NodeType;
StorageNodeMutDeref
This makes the storage node members directly accessible from a path to the parent struct.
Fully qualified path: core::starknet::storage::StorageNodeMutDeref
pub impl StorageNodeMutDeref<T, +StorageNodeMut<T>> of core::ops::Deref<StoragePath<Mutable<T>>>
Impl functions
deref
Fully qualified path: core::starknet::storage::StorageNodeMutDeref::deref
fn deref(self: StoragePath<Mutable<T>>) -> Self::Target
Impl types
Target
Fully qualified path: core::starknet::storage::StorageNodeMutDeref::Target
type Target = StorageNodeMut::<T>::NodeType;
Bytes31Impl
A trait for accessing a specific byte of a bytes31
type.
Fully qualified path: core::bytes_31::Bytes31Impl
pub impl Bytes31Impl of Bytes31Trait
Impl functions
at
Returns the byte at the given index (LSB's index is 0).Assumes that index < BYTES_IN_BYTES31
. If the assumption is not met, the behavior is undefined. # Examples
let bytes: bytes31 = 1_u8.into();
assert!(bytes.at(0) == 1);
Fully qualified path: core::bytes_31::Bytes31Impl::at
fn at(self: @bytes31, index: usize) -> u8
ByteArrayImpl
Functions associated with the ByteArray
type.
Fully qualified path: core::byte_array::ByteArrayImpl
pub impl ByteArrayImpl of ByteArrayTrait
Impl functions
append_word
Appends a single word of len
bytes to the end of the ByteArray
.This function assumes that: 1. word
could be validly converted to a bytes31
which has no more than len
bytes of data. 2. len <= BYTES_IN_BYTES31.If these assumptions are not met, it can corrupt the ByteArray
. Thus, this should be a private function. We could add masking/assertions but it would be more expensive. # Examples
let mut ba = "";
ba.append_word('word', 4);
assert!(ba == "word");
Fully qualified path: core::byte_array::ByteArrayImpl::append_word
fn append_word(ref self: ByteArray, word: felt252, len: usize)
append
Appends a ByteArray
to the end of another ByteArray
. # Examples
let mut ba: ByteArray = "1";
ba.append(@"2");
assert!(ba == "12");
Fully qualified path: core::byte_array::ByteArrayImpl::append
fn append(ref self: ByteArray, other: @ByteArray)
concat
Concatenates two ByteArray
and returns the result.The content of left
is cloned in a new memory segment. # Examples
let ba = "1";
let other_ba = "2";
let result = ByteArrayTrait::concat(@ba, @other_ba);
assert!(result == "12");
Fully qualified path: core::byte_array::ByteArrayImpl::concat
fn concat(left: @ByteArray, right: @ByteArray) -> ByteArray
append_byte
Appends a single byte to the end of the ByteArray
. # Examples
let mut ba = "";
ba.append_byte(0);
assert!(ba == "0");
Fully qualified path: core::byte_array::ByteArrayImpl::append_byte
fn append_byte(ref self: ByteArray, byte: u8)
len
Returns the length of the ByteArray
. # Examples
let ba: ByteArray = "byte array";
let len = ba.len();
assert!(len == 10);
Fully qualified path: core::byte_array::ByteArrayImpl::len
fn len(self: @ByteArray) -> usize
at
Returns an option of the byte at the given index of self
or None
if the index is out of bounds. # Examples
let ba: ByteArray = "byte array";
let byte = ba.at(0).unwrap();
assert!(byte == 98);
Fully qualified path: core::byte_array::ByteArrayImpl::at
fn at(self: @ByteArray, index: usize) -> Option<u8>
rev
Returns a ByteArray
with the reverse order of self
. # Examples
let ba: ByteArray = "123";
let rev_ba = ba.rev();
assert!(rev_ba == "321");
Fully qualified path: core::byte_array::ByteArrayImpl::rev
fn rev(self: @ByteArray) -> ByteArray
append_word_rev
Appends the reverse of the given word to the end of self
.This function assumes that: 1. len < 31 2. word is validly convertible to bytes31 of length len
. # Examples
let mut ba: ByteArray = "";
ba.append_word_rev('123', 3);
assert!(ba == "321");
Fully qualified path: core::byte_array::ByteArrayImpl::append_word_rev
fn append_word_rev(ref self: ByteArray, word: felt252, len: usize)
append_word_fits_into_pending
Appends a single word of len
bytes to the end of the ByteArray
, assuming there is enough space in the pending word (self.pending_word_len + len < BYTES_IN_BYTES31
).word
is of type felt252
but actually represents a bytes31
. It is represented as a felt252
to improve performance of building the ByteArray
.
Fully qualified path: core::byte_array::ByteArrayImpl::append_word_fits_into_pending
fn append_word_fits_into_pending(ref self: ByteArray, word: felt252, len: usize)
append_split_index_lt_16
Appends a single word to the end of self
, given that 0 < split_index < 16
.split_index
is the number of bytes left in self.pending_word
after this function. This is the index of the split (LSB's index is 0).Note: this function doesn't update the new pending length of self
. It's the caller's responsibility.
Fully qualified path: core::byte_array::ByteArrayImpl::append_split_index_lt_16
fn append_split_index_lt_16(ref self: ByteArray, word: felt252, split_index: usize)
append_split_index_16
Appends a single word to the end of self
, given that the index of splitting word
is exactly 16.split_index
is the number of bytes left in self.pending_word
after this function. This is the index of the split (LSB's index is 0).Note: this function doesn't update the new pending length of self
. It's the caller's responsibility.
Fully qualified path: core::byte_array::ByteArrayImpl::append_split_index_16
fn append_split_index_16(ref self: ByteArray, word: felt252)
append_split_index_gt_16
Appends a single word to the end of self
, given that the index of splitting word
is > 16.split_index
is the number of bytes left in self.pending_word
after this function. This is the index of the split (LSB's index is 0).Note: this function doesn't update the new pending length of self
. It's the caller's responsibility.
Fully qualified path: core::byte_array::ByteArrayImpl::append_split_index_gt_16
fn append_split_index_gt_16(ref self: ByteArray, word: felt252, split_index: usize)
append_split
A helper function to append a remainder to self
, by: 1. completing self.pending_word
to a full word using complete_full_word
, assuming it's validly convertible to a bytes31
of length exactly BYTES_IN_BYTES31 - self.pending_word_len
. 2. Setting self.pending_word
to new_pending
.Note: this function doesn't update the new pending length of self
. It's the caller's responsibility.
Fully qualified path: core::byte_array::ByteArrayImpl::append_split
fn append_split(ref self: ByteArray, complete_full_word: felt252, new_pending: felt252)
Extern types
RangeCheck
General purpose implicits.
Fully qualified path: core::RangeCheck
pub extern type RangeCheck
SegmentArena
Fully qualified path: core::SegmentArena
pub extern type SegmentArena
felt252
felt252
is the basic field element used in Cairo.It corresponds to an integer in the range 0 ≤ x < P where P is a very large prime number currently equal to 2^251 + 17⋅2^192 + 1.Any operation that uses felt252
will be computed modulo P.
Fully qualified path: core::felt252
pub extern type felt252
RangeCheck96
Range check builtin for 96-bit operations.
Fully qualified path: core::circuit::RangeCheck96
pub extern type RangeCheck96
AddMod
Builtin for modular addition operations.
Fully qualified path: core::circuit::AddMod
pub extern type AddMod
MulMod
Builtin for modular multiplication operations.
Fully qualified path: core::circuit::MulMod
pub extern type MulMod
CircuitModulus
A type that can be used as a circuit modulus (a u384 that is not zero or one).The modulus defines the finite field over which the circuit operates. It must be: - A 384-bit number (represented as four 96-bit limbs) - Not zero or one - Typically a prime number for cryptographic applications
Fully qualified path: core::circuit::CircuitModulus
pub extern type CircuitModulus
Circuit
A type that creates a circuit from a tuple of outputs.This type represents a complete circuit instance, constructed from its output gates. The type parameter Outputs
defines the structure of the circuit's outputs.
Fully qualified path: core::circuit::Circuit
pub extern type Circuit<Outputs>
CircuitInput
Defines an input for a circuit.Represents an input signal in the circuit, indexed by N
. Each input must be assigned a value before circuit evaluation.
Fully qualified path: core::circuit::CircuitInput
#[phantom]
pub extern type CircuitInput<const N: usize>
Box
A Box
is a type that points to a wrapped value. It allows for cheap moving around of the value, as its size is small, and may wrap a large size.
Fully qualified path: core::box::Box
pub extern type Box<T>
Nullable
A type that can either be null or contain a boxed value.
Fully qualified path: core::nullable::Nullable
pub extern type Nullable<T>
Array
A collection of elements of the same type contiguous in memory.
Fully qualified path: core::array::Array
pub extern type Array<T>
Felt252Dict
A dictionary that maps felt252
keys to a value of any type.
Fully qualified path: core::dict::Felt252Dict
pub extern type Felt252Dict<T>
SquashedFelt252Dict
A dictionary in a squashed state. It cannot be mutated anymore.
Fully qualified path: core::dict::SquashedFelt252Dict
pub extern type SquashedFelt252Dict<T>
Felt252DictEntry
An intermediate type that is returned after calling the entry
method that consumes ownership of the dictionary. This ensures that the dictionary cannot be mutated until the entry is finalized, which restores ownership of the dictionary.
Fully qualified path: core::dict::Felt252DictEntry
pub extern type Felt252DictEntry<T>
EcOp
Fully qualified path: core::ec::EcOp
pub extern type EcOp
EcPoint
A point on the STARK curve.Points can be created using EcPointTrait::new
or EcPointTrait::new_from_x
. The zero point represents the point at infinity.
Fully qualified path: core::ec::EcPoint
pub extern type EcPoint
EcState
Elliptic curve state.Use this to perform multiple point operations efficiently. Initialize with EcStateTrait::init
, add points with EcStateTrait::add
or EcStateTrait::add_mul
, and finalize with EcStateTrait::finalize
.
Fully qualified path: core::ec::EcState
pub extern type EcState
u128
The 128-bit unsigned integer type.
Fully qualified path: core::integer::u128
pub extern type u128
U128MulGuarantee
A type that contains 4 u128s (a, b, c, d) and guarantees that a * b = 2**128 * c + d
.The guarantee is verified by u128_mul_guarantee_verify
, which is the only way to destruct this type. This way, one can trust that the guarantee holds although it has not yet been verified.
Fully qualified path: core::integer::U128MulGuarantee
pub extern type U128MulGuarantee
Bitwise
Fully qualified path: core::integer::Bitwise
pub extern type Bitwise
u8
The 8-bit unsigned integer type.
Fully qualified path: core::integer::u8
pub extern type u8
u16
The 16-bit unsigned integer type.
Fully qualified path: core::integer::u16
pub extern type u16
u32
The 32-bit unsigned integer type.
Fully qualified path: core::integer::u32
pub extern type u32
u64
The 64-bit unsigned integer type.
Fully qualified path: core::integer::u64
pub extern type u64
i8
The 8-bit signed integer type.
Fully qualified path: core::integer::i8
pub extern type i8
i16
The 16-bit signed integer type.
Fully qualified path: core::integer::i16
pub extern type i16
i32
The 32-bit signed integer type.
Fully qualified path: core::integer::i32
pub extern type i32
i64
The 64-bit signed integer type.
Fully qualified path: core::integer::i64
pub extern type i64
i128
The 128-bit signed integer type.
Fully qualified path: core::integer::i128
pub extern type i128
BuiltinCosts
Type representing the table of the costs of the different builtin usages.
Fully qualified path: core::gas::BuiltinCosts
#[cfg(not(gas: "disabled"))]
pub extern type BuiltinCosts
GasBuiltin
The gas builtin. This type is used to handle gas in the Cairo code. Contains the amount of gas available for the current run.
Fully qualified path: core::gas::GasBuiltin
pub extern type GasBuiltin
Pedersen
Fully qualified path: core::pedersen::Pedersen
pub extern type Pedersen
Poseidon
Fully qualified path: core::poseidon::Poseidon
pub extern type Poseidon
System
Fully qualified path: core::starknet::System
pub extern type System
StorageAddress
Represents the address of a storage value in a Starknet contract. The value range of this type is [0, 2**251)
.
Fully qualified path: core::starknet::storage_access::StorageAddress
pub extern type StorageAddress
ContractAddress
Represents a Starknet contract address. The value range of this type is [0, 2**251)
.
Fully qualified path: core::starknet::contract_address::ContractAddress
pub extern type ContractAddress
ClassHash
Represents a Starknet contract class hash. The value range of this type is [0, 2**251)
.
Fully qualified path: core::starknet::class_hash::ClassHash
pub extern type ClassHash
StorageAddress
Represents the address of a storage value in a Starknet contract. The value range of this type is [0, 2**251)
.
Fully qualified path: core::starknet::storage_access::StorageAddress
pub extern type StorageAddress
StorageBaseAddress
Represents a base storage address that can be combined with offsets. The value range of this type is [0, 2**251 - 256)
.
Fully qualified path: core::starknet::storage_access::StorageBaseAddress
pub extern type StorageBaseAddress
ContractAddress
Represents a Starknet contract address. The value range of this type is [0, 2**251)
.
Fully qualified path: core::starknet::contract_address::ContractAddress
pub extern type ContractAddress
Secp256k1Point
A point on the secp256k1 curve.
Fully qualified path: core::starknet::secp256k1::Secp256k1Point
pub extern type Secp256k1Point
Secp256r1Point
Represents a point on the secp256r1 elliptic curve.
Fully qualified path: core::starknet::secp256r1::Secp256r1Point
pub extern type Secp256r1Point
ClassHash
Represents a Starknet contract class hash. The value range of this type is [0, 2**251)
.
Fully qualified path: core::starknet::class_hash::ClassHash
pub extern type ClassHash
NonZero
A wrapper type for non-zero values of type T.This type guarantees that the wrapped value is never zero.
Fully qualified path: core::zeroable::NonZero
pub extern type NonZero<T>
bytes31
Represents a 31-byte fixed-size byte type.
Fully qualified path: core::bytes_31::bytes31
pub extern type bytes31
Extern functions
felt252_div
Performs division on felt252
values in Cairo's finite field. Unlike regular integer division, felt252
division returns a field element n that satisfies the equation: n * rhs ≡ lhs (mod P), where P is the felt252
prime. # Examples
use core::felt252_div;
// Division with 0 remainder works the same way as integer division.
assert!(felt252_div(4, 2) == 2);
// Division with non 0 remainder returns a field element n where n * 3 ≡ 4 (mod P)
assert!(felt252_div(4, 3) ==
1206167596222043737899107594365023368541035738443865566657697352045290673495);
Fully qualified path: core::felt252_div
pub extern fn felt252_div(lhs: felt252, rhs: NonZero<felt252>) -> felt252 nopanic;
blake2s_compress
The blake2s compress function, which takes a state, a byte count, and a message, and returns a new state. byte_count
should be the total number of bytes hashed after hashing the current msg
.
Fully qualified path: core::blake::blake2s_compress
pub extern fn blake2s_compress(
state: Blake2sState, byte_count: u32, msg: Blake2sInput,
) -> Blake2sState nopanic;
blake2s_finalize
Similar to blake2s_compress
, but used for the final block of the message.
Fully qualified path: core::blake::blake2s_finalize
pub extern fn blake2s_finalize(
state: Blake2sState, byte_count: u32, msg: Blake2sInput,
) -> Blake2sState nopanic;
null
Fully qualified path: core::nullable::null
pub extern fn null<T>() -> Nullable<T> nopanic;
match_nullable
Fully qualified path: core::nullable::match_nullable
pub extern fn match_nullable<T>(value: Nullable<T>) -> FromNullableResult<T> nopanic;
ec_point_unwrap
Unwraps a non-zero point into its (x, y) coordinates.
Fully qualified path: core::ec::ec_point_unwrap
pub extern fn ec_point_unwrap(p: NonZeroEcPoint) -> (felt252, felt252) nopanic;
u128_overflowing_add
Fully qualified path: core::integer::u128_overflowing_add
pub extern fn u128_overflowing_add(
lhs: u128, rhs: u128,
) -> Result<u128, u128> implicits(RangeCheck) nopanic;
u128_overflowing_sub
Fully qualified path: core::integer::u128_overflowing_sub
pub extern fn u128_overflowing_sub(
lhs: u128, rhs: u128,
) -> Result<u128, u128> implicits(RangeCheck) nopanic;
u128_sqrt
Fully qualified path: core::integer::u128_sqrt
pub extern fn u128_sqrt(value: u128) -> u64 implicits(RangeCheck) nopanic;
u128_safe_divmod
Fully qualified path: core::integer::u128_safe_divmod
pub extern fn u128_safe_divmod(
lhs: u128, rhs: NonZero<u128>,
) -> (u128, u128) implicits(RangeCheck) nopanic;
u128_byte_reverse
Fully qualified path: core::integer::u128_byte_reverse
pub extern fn u128_byte_reverse(input: u128) -> u128 implicits(Bitwise) nopanic;
u8_overflowing_add
Fully qualified path: core::integer::u8_overflowing_add
pub extern fn u8_overflowing_add(lhs: u8, rhs: u8) -> Result<u8, u8> implicits(RangeCheck) nopanic;
u8_overflowing_sub
Fully qualified path: core::integer::u8_overflowing_sub
pub extern fn u8_overflowing_sub(lhs: u8, rhs: u8) -> Result<u8, u8> implicits(RangeCheck) nopanic;
u8_wide_mul
Fully qualified path: core::integer::u8_wide_mul
pub extern fn u8_wide_mul(lhs: u8, rhs: u8) -> u16 implicits() nopanic;
u8_sqrt
Fully qualified path: core::integer::u8_sqrt
pub extern fn u8_sqrt(value: u8) -> u8 implicits(RangeCheck) nopanic;
u8_safe_divmod
Fully qualified path: core::integer::u8_safe_divmod
pub extern fn u8_safe_divmod(lhs: u8, rhs: NonZero<u8>) -> (u8, u8) implicits(RangeCheck) nopanic;
u16_overflowing_add
Fully qualified path: core::integer::u16_overflowing_add
pub extern fn u16_overflowing_add(
lhs: u16, rhs: u16,
) -> Result<u16, u16> implicits(RangeCheck) nopanic;
u16_overflowing_sub
Fully qualified path: core::integer::u16_overflowing_sub
pub extern fn u16_overflowing_sub(
lhs: u16, rhs: u16,
) -> Result<u16, u16> implicits(RangeCheck) nopanic;
u16_wide_mul
Fully qualified path: core::integer::u16_wide_mul
pub extern fn u16_wide_mul(lhs: u16, rhs: u16) -> u32 implicits() nopanic;
u16_sqrt
Fully qualified path: core::integer::u16_sqrt
pub extern fn u16_sqrt(value: u16) -> u8 implicits(RangeCheck) nopanic;
u16_safe_divmod
Fully qualified path: core::integer::u16_safe_divmod
pub extern fn u16_safe_divmod(
lhs: u16, rhs: NonZero<u16>,
) -> (u16, u16) implicits(RangeCheck) nopanic;
u32_overflowing_add
Fully qualified path: core::integer::u32_overflowing_add
pub extern fn u32_overflowing_add(
lhs: u32, rhs: u32,
) -> Result<u32, u32> implicits(RangeCheck) nopanic;
u32_overflowing_sub
Fully qualified path: core::integer::u32_overflowing_sub
pub extern fn u32_overflowing_sub(
lhs: u32, rhs: u32,
) -> Result<u32, u32> implicits(RangeCheck) nopanic;
u32_wide_mul
Fully qualified path: core::integer::u32_wide_mul
pub extern fn u32_wide_mul(lhs: u32, rhs: u32) -> u64 implicits() nopanic;
u32_sqrt
Fully qualified path: core::integer::u32_sqrt
pub extern fn u32_sqrt(value: u32) -> u16 implicits(RangeCheck) nopanic;
u32_safe_divmod
Fully qualified path: core::integer::u32_safe_divmod
pub extern fn u32_safe_divmod(
lhs: u32, rhs: NonZero<u32>,
) -> (u32, u32) implicits(RangeCheck) nopanic;
u64_overflowing_add
Fully qualified path: core::integer::u64_overflowing_add
pub extern fn u64_overflowing_add(
lhs: u64, rhs: u64,
) -> Result<u64, u64> implicits(RangeCheck) nopanic;
u64_overflowing_sub
Fully qualified path: core::integer::u64_overflowing_sub
pub extern fn u64_overflowing_sub(
lhs: u64, rhs: u64,
) -> Result<u64, u64> implicits(RangeCheck) nopanic;
u64_wide_mul
Fully qualified path: core::integer::u64_wide_mul
pub extern fn u64_wide_mul(lhs: u64, rhs: u64) -> u128 implicits() nopanic;
u64_sqrt
Fully qualified path: core::integer::u64_sqrt
pub extern fn u64_sqrt(value: u64) -> u32 implicits(RangeCheck) nopanic;
u64_safe_divmod
Fully qualified path: core::integer::u64_safe_divmod
pub extern fn u64_safe_divmod(
lhs: u64, rhs: NonZero<u64>,
) -> (u64, u64) implicits(RangeCheck) nopanic;
u256_sqrt
Fully qualified path: core::integer::u256_sqrt
pub extern fn u256_sqrt(a: u256) -> u128 implicits(RangeCheck) nopanic;
i8_wide_mul
Fully qualified path: core::integer::i8_wide_mul
pub extern fn i8_wide_mul(lhs: i8, rhs: i8) -> i16 implicits() nopanic;
i8_diff
If lhs
>= rhs
returns Ok(lhs - rhs)
else returns Err(2**8 + lhs - rhs)
.
Fully qualified path: core::integer::i8_diff
pub extern fn i8_diff(lhs: i8, rhs: i8) -> Result<u8, u8> implicits(RangeCheck) nopanic;
i16_wide_mul
Fully qualified path: core::integer::i16_wide_mul
pub extern fn i16_wide_mul(lhs: i16, rhs: i16) -> i32 implicits() nopanic;
i16_diff
If lhs
>= rhs
returns Ok(lhs - rhs)
else returns Err(2**16 + lhs - rhs)
.
Fully qualified path: core::integer::i16_diff
pub extern fn i16_diff(lhs: i16, rhs: i16) -> Result<u16, u16> implicits(RangeCheck) nopanic;
i32_wide_mul
Fully qualified path: core::integer::i32_wide_mul
pub extern fn i32_wide_mul(lhs: i32, rhs: i32) -> i64 implicits() nopanic;
i32_diff
If lhs
>= rhs
returns Ok(lhs - rhs)
else returns Err(2**32 + lhs - rhs)
.
Fully qualified path: core::integer::i32_diff
pub extern fn i32_diff(lhs: i32, rhs: i32) -> Result<u32, u32> implicits(RangeCheck) nopanic;
i64_wide_mul
Fully qualified path: core::integer::i64_wide_mul
pub extern fn i64_wide_mul(lhs: i64, rhs: i64) -> i128 implicits() nopanic;
i64_diff
If lhs
>= rhs
returns Ok(lhs - rhs)
else returns Err(2**64 + lhs - rhs)
.
Fully qualified path: core::integer::i64_diff
pub extern fn i64_diff(lhs: i64, rhs: i64) -> Result<u64, u64> implicits(RangeCheck) nopanic;
i128_diff
If lhs
>= rhs
returns Ok(lhs - rhs)
else returns Err(2**128 + lhs - rhs)
.
Fully qualified path: core::integer::i128_diff
pub extern fn i128_diff(lhs: i128, rhs: i128) -> Result<u128, u128> implicits(RangeCheck) nopanic;
withdraw_gas
Withdraws gas from the GasBuiltin
to handle the success case flow. Returns Some(())
if there is sufficient gas to handle the success case, otherwise returns None
. # Examples
// The success branch is the following lines, the failure branch is the `panic` caused by the
// `unwrap` call.
withdraw_gas().unwrap();
// Direct handling of `withdraw_gas`.
match withdraw_gas() {
Some(()) => success_case(),
None => cheap_not_enough_gas_case(),
}
Fully qualified path: core::gas::withdraw_gas
pub extern fn withdraw_gas() -> Option<()> implicits(RangeCheck, GasBuiltin) nopanic;
withdraw_gas_all
Same as withdraw_gas
, but directly receives BuiltinCosts
, which enables optimizations by removing the need for repeated internal calls for fetching the table of constants that may internally happen in calls to withdraw_gas
. Should be used with caution.
Fully qualified path: core::gas::withdraw_gas_all
pub extern fn withdraw_gas_all(
costs: BuiltinCosts,
) -> Option<()> implicits(RangeCheck, GasBuiltin) nopanic;
redeposit_gas
Returns unused gas into the gas builtin.Useful for cases where different branches take different amounts of gas, but gas withdrawal is the same for both.
Fully qualified path: core::gas::redeposit_gas
pub extern fn redeposit_gas() implicits(GasBuiltin) nopanic;
get_builtin_costs
Returns the BuiltinCosts
table to be used in withdraw_gas_all
.
Fully qualified path: core::gas::get_builtin_costs
pub extern fn get_builtin_costs() -> BuiltinCosts nopanic;
panic
Triggers an immediate panic with the provided data and terminates execution. # Examples
use core::panics::panic;
panic(array!['An error occurred']);
Fully qualified path: core::panics::panic
pub extern fn panic(data: Array<felt252>) -> crate::never;
pedersen
Fully qualified path: core::pedersen::pedersen
pub extern fn pedersen(a: felt252, b: felt252) -> felt252 implicits(Pedersen) nopanic;
hades_permutation
Fully qualified path: core::poseidon::hades_permutation
pub extern fn hades_permutation(
s0: felt252, s1: felt252, s2: felt252,
) -> (felt252, felt252, felt252) implicits(Poseidon) nopanic;
contract_address_const
Returns a ContractAddress
given a felt252
value. # Examples
use starknet::contract_address::contract_address_const;
let contract_address = contract_address_const::<0x0>();
Fully qualified path: core::starknet::contract_address::contract_address_const
pub extern fn contract_address_const<const address: felt252>() -> ContractAddress nopanic;
storage_base_address_const
Returns a StorageBaseAddress
given a constant felt252
value.The value is validated to be in the range [0, 2**251 - 256)
at compile time. # Examples
use starknet::storage_access::storage_base_address_const;
let base_address = storage_base_address_const::<0>();
Fully qualified path: core::starknet::storage_access::storage_base_address_const
pub extern fn storage_base_address_const<const address: felt252>() -> StorageBaseAddress nopanic;
storage_base_address_from_felt252
Returns a StorageBaseAddress
given a felt252
value.Wraps around the value if it is not in the range [0, 2**251 - 256)
.
Fully qualified path: core::starknet::storage_access::storage_base_address_from_felt252
pub extern fn storage_base_address_from_felt252(
addr: felt252,
) -> StorageBaseAddress implicits(RangeCheck) nopanic;
storage_address_from_base_and_offset
Sums the base address and the offset to return a storage address.
Fully qualified path: core::starknet::storage_access::storage_address_from_base_and_offset
pub extern fn storage_address_from_base_and_offset(
base: StorageBaseAddress, offset: u8,
) -> StorageAddress nopanic;
storage_address_from_base
Converts a StorageBaseAddress
into a StorageAddress
.This should be used through the high-level Into
trait.
Fully qualified path: core::starknet::storage_access::storage_address_from_base
pub extern fn storage_address_from_base(base: StorageBaseAddress) -> StorageAddress nopanic;
call_contract_syscall
Calls a given contract. # Argumentsaddress
- The address of the called contract. * entry_point_selector
- A selector for a function within that contract. * calldata
- Call arguments.
Fully qualified path: core::starknet::syscalls::call_contract_syscall
pub extern fn call_contract_syscall(
address: ContractAddress, entry_point_selector: felt252, calldata: Span<felt252>,
) -> SyscallResult<Span<felt252>> implicits(GasBuiltin, System) nopanic;
deploy_syscall
Deploys a new instance of a previously declared class. # Argumentsclass_hash
- The class hash of the contract to be deployed. * contract_address_salt
- The salt, an arbitrary value provided by the deployer, used in the computation of the contract's address. * calldata
- Call arguments for the constructor. * deploy_from_zero
- Deploy the contract from the zero address. # ReturnsThe address of the deployed contract. * The serialized return value of the constructor.
Fully qualified path: core::starknet::syscalls::deploy_syscall
pub extern fn deploy_syscall(
class_hash: ClassHash,
contract_address_salt: felt252,
calldata: Span<felt252>,
deploy_from_zero: bool,
) -> SyscallResult<(ContractAddress, Span<felt252>)> implicits(GasBuiltin, System) nopanic;
emit_event_syscall
Emits an event. # Argumentskeys
- The keys of the event. * data
- The data of the event.
Fully qualified path: core::starknet::syscalls::emit_event_syscall
pub extern fn emit_event_syscall(
keys: Span<felt252>, data: Span<felt252>,
) -> SyscallResult<()> implicits(GasBuiltin, System) nopanic;
get_block_hash_syscall
Returns the hash of the block with the given number. # Argumentsblock_number
- The number of the queried block. # ReturnsThe hash of the block with the given number.
Fully qualified path: core::starknet::syscalls::get_block_hash_syscall
pub extern fn get_block_hash_syscall(
block_number: u64,
) -> SyscallResult<felt252> implicits(GasBuiltin, System) nopanic;
get_execution_info_syscall
Gets information about the currently executing block and the transactions in the block. For a complete description of this information, see [Execution information
](Execution information
).When an account’s __validate__
, __validate_deploy__
, or __validate_declare__
function calls get_execution_info
, the return values for block_timestamp
and block_number
are modified as follows: * block_timestamp
returns the hour, rounded down to the nearest hour. * block_number
returns the block number, rounded down to the nearest multiple of 100. # ReturnsA struct that contains information about the currently executing function, transaction, and block.
Fully qualified path: core::starknet::syscalls::get_execution_info_syscall
pub extern fn get_execution_info_syscall() -> SyscallResult<
Box<starknet::info::ExecutionInfo>,
> implicits(GasBuiltin, System) nopanic;
get_execution_info_v2_syscall
Gets information about the current execution, version 2. This syscall should not be called directly. Instead, use starknet::info::get_execution_info
. # ReturnsA box containing the current V2 execution information.
Fully qualified path: core::starknet::syscalls::get_execution_info_v2_syscall
pub extern fn get_execution_info_v2_syscall() -> SyscallResult<
Box<starknet::info::v2::ExecutionInfo>,
> implicits(GasBuiltin, System) nopanic;
library_call_syscall
Calls the requested function in any previously declared class. # Argumentsclass_hash
- The hash of the class to be used. * function_selector
- A selector for a function within that class. * calldata
- Call arguments.
Fully qualified path: core::starknet::syscalls::library_call_syscall
pub extern fn library_call_syscall(
class_hash: ClassHash, function_selector: felt252, calldata: Span<felt252>,
) -> SyscallResult<Span<felt252>> implicits(GasBuiltin, System) nopanic;
send_message_to_l1_syscall
Sends a message to L1. # Argumentsto_address
- The recipient's L1 address. * payload
- The content of the message.
Fully qualified path: core::starknet::syscalls::send_message_to_l1_syscall
pub extern fn send_message_to_l1_syscall(
to_address: felt252, payload: Span<felt252>,
) -> SyscallResult<()> implicits(GasBuiltin, System) nopanic;
storage_read_syscall
Gets the value of a key in the storage of the calling contract. # Argumentsaddress_domain
- The domain of the address. Only address_domain
0 is currently supported, in the future it will enable access to address spaces with different data availability guarantees. * address
- The address of the storage key to read.
Fully qualified path: core::starknet::syscalls::storage_read_syscall
pub extern fn storage_read_syscall(
address_domain: u32, address: StorageAddress,
) -> SyscallResult<felt252> implicits(GasBuiltin, System) nopanic;
storage_write_syscall
Sets the value of a key in the storage of the calling contract. # Argumentsaddress_domain
- The domain of the address. Only address_domain
0 is currently supported, in the future it will enable access to address spaces with different data availability guarantees. * address
- The address of the storage key to write. * value
- The value to write to the key.
Fully qualified path: core::starknet::syscalls::storage_write_syscall
pub extern fn storage_write_syscall(
address_domain: u32, address: StorageAddress, value: felt252,
) -> SyscallResult<()> implicits(GasBuiltin, System) nopanic;
replace_class_syscall
Replaces the class hash of the current contract, instantly modifying its entrypoints.The new class becomes effective only after the current function call completes. The remaining code in the current function will continue executing from the old class. The new class will be used: * In subsequent transactions * If the contract is called via call_contract
syscall later in the same transaction # Argumentsclass_hash
- The class hash that should replace the current one.
Fully qualified path: core::starknet::syscalls::replace_class_syscall
pub extern fn replace_class_syscall(
class_hash: ClassHash,
) -> SyscallResult<()> implicits(GasBuiltin, System) nopanic;
get_class_hash_at_syscall
Gets the class hash of the contract at the given address. # Argumentscontract_address
- The address of the deployed contract. # ReturnsThe class hash of the contract's originating code.
Fully qualified path: core::starknet::syscalls::get_class_hash_at_syscall
pub extern fn get_class_hash_at_syscall(
contract_address: ContractAddress,
) -> SyscallResult<ClassHash> implicits(GasBuiltin, System) nopanic;
keccak_syscall
Computes the keccak of the input.The input must be a multiple of 1088 bits (== 17 u64 words) * The input must be pre-padded following the Keccak padding rule (pad10*1): 1. Add a '1' bit 2. Add zero or more '0' bits 3. Add a final '1' bit The total length after padding must be a multiple of 1088 bits # Argumentsinput
- Array of 64-bit words (little endian) to be hashed. # ReturnsThe keccak hash as a little-endian u256
Fully qualified path: core::starknet::syscalls::keccak_syscall
pub extern fn keccak_syscall(
input: Span<u64>,
) -> SyscallResult<u256> implicits(GasBuiltin, System) nopanic;
sha256_process_block_syscall
Computes the next SHA-256 state of the input with the given state. # Argumentsstate
- The current SHA-256 state. * input
- The input provided to compute the next SHA-256 state. # ReturnsThe next SHA-256 state of the input with the givens state.The system call does not add any padding and the input needs to be a multiple of 512 bits (== 16 u32 word).
Fully qualified path: core::starknet::syscalls::sha256_process_block_syscall
pub extern fn sha256_process_block_syscall(
state: core::sha256::Sha256StateHandle, input: Box<[u32; 16]>,
) -> SyscallResult<core::sha256::Sha256StateHandle> implicits(GasBuiltin, System) nopanic;
contract_address_const
Returns a ContractAddress
given a felt252
value. # Examples
use starknet::contract_address::contract_address_const;
let contract_address = contract_address_const::<0x0>();
Fully qualified path: core::starknet::contract_address::contract_address_const
pub extern fn contract_address_const<const address: felt252>() -> ContractAddress nopanic;
class_hash_const
Returns a ClassHash
given a felt252
value. # Examples
use starknet::class_hash::class_hash_const;
let class_hash = class_hash_const::<0x123>();
Fully qualified path: core::starknet::class_hash::class_hash_const
pub extern fn class_hash_const<const address: felt252>() -> ClassHash nopanic;
cheatcode
A general cheatcode function used to simplify implementation of Starknet testing functions.This is the base function used by testing utilities to interact with the test environment. External users can implement custom cheatcodes by injecting a custom CairoHintProcessor
in the runner. # Argumentsselector
- The cheatcode identifier. input
- Input parameters for the cheatcode. # ReturnsA span containing the cheatcode's output
Fully qualified path: core::starknet::testing::cheatcode
pub extern fn cheatcode<const selector: felt252>(
input: Span<felt252>,
) -> Span<felt252> implicits() nopanic;
revoke_ap_tracking
Fully qualified path: core::internal::revoke_ap_tracking
pub extern fn revoke_ap_tracking() implicits() nopanic;
require_implicit
Function to enforce that Implicit
is used by a function calling it. Note: This extern function is not mapped to a Sierra function, and all usages of it are removed during compilation.
Fully qualified path: core::internal::require_implicit
pub extern fn require_implicit<Implicit>() implicits(Implicit) nopanic;
get_available_gas
Returns the amount of gas available in the GasBuiltin
.Useful for asserting that a certain amount of gas was consumed. Note: The actual gas consumption observed by calls to get_available_gas
is only exact immediately before calls to withdraw_gas
. # Examples
use core::testing::get_available_gas;
fn gas_heavy_function() {
// ... some gas-intensive code
}
fn test_gas_consumption() {
let gas_before = get_available_gas();
// Making sure `gas_before` is exact.
core::gas::withdraw_gas().unwrap();
gas_heavy_function();
let gas_after = get_available_gas();
// Making sure `gas_after` is exact
core::gas::withdraw_gas().unwrap();
assert!(gas_after - gas_before < 100_000);
}
Fully qualified path: core::testing::get_available_gas
pub extern fn get_available_gas() -> u128 implicits(GasBuiltin) nopanic;
get_unspent_gas
Returns the amount of gas available in the GasBuiltin
, as well as the amount of gas unused in the local wallet.Useful for asserting that a certain amount of gas used. Note: This function call costs exactly 2300
gas, so this may be ignored in calculations. # Examples
use core::testing::get_unspent_gas;
fn gas_heavy_function() {
// ... some gas-intensive code
}
fn test_gas_consumption() {
let gas_before = get_unspent_gas();
gas_heavy_function();
let gas_after = get_unspent_gas();
assert!(gas_after - gas_before < 100_000);
}
Fully qualified path: core::testing::get_unspent_gas
pub extern fn get_unspent_gas() -> u128 implicits(GasBuiltin) nopanic;