### Struct Documentation with Example Usage Source: https://github.com/starkware-libs/cairo/blob/main/crates/cairo-lang-doc/src/tests/test-data/basic.txt Documents a struct with fields and provides an example usage in a code block. ```rust /// Point struct representing a point in a 2D space. /// Example usage: /// ``` /// fn new_Point() { /// Point {x: 12, y: 14} /// } /// ``` /// [Point::bang] #[derive(Drop)] #[derive(Copy)] struct Point { /// X coordinate. pub x: u32, /// Y coordinate. y: u32, } ``` -------------------------------- ### Panic Examples Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/panic.adoc Illustrative examples of how to use the `panic` function in different scenarios. ```APIDOC ## Examples ### Basic Panic ```cairo fn will_panic() { panic(array!['error message']); } ``` ### Conditional Panic ```cairo fn conditional_panic(x: u32) { if x == 0 { panic(array!['x cannot be zero']); } } ``` ``` -------------------------------- ### Install asciidoctor on Ubuntu Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/readme.md Installs the `asciidoctor` tool on Ubuntu using apt-get. This is required for converting AsciiDoc files to HTML. ```bash sudo apt-get install asciidoctor ``` -------------------------------- ### Minimal Cairo Program Example Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/appendices/pages/full-grammar.adoc A basic example of a complete Cairo program, demonstrating function definition, variable declaration, struct definition, and implementation. ```cairo // Function definition fn main() -> felt252 { let x: felt252 = 42; x + 1 } // Struct definition struct Point { x: felt252, y: felt252, } // Implementation impl PointImpl of PointTrait { fn new(x: felt252, y: felt252) -> Point { Point { x, y } } } ``` -------------------------------- ### Fibonacci Function Example in Cairo Source: https://github.com/starkware-libs/cairo/blob/main/crates/cairo-lang-runner/README.md This example demonstrates a recursive Fibonacci calculation in Cairo. It assumes the `main` function is the entry point for execution. ```cairo // Calculates fib... fn main() -> u128 { fib(1_u128, 1_u128, 100_u128) } fn fib(a: u128, b: u128, n: u128) -> u128 { if n == 0 { a } else { fib(b, a + b, n - 1_u128) } } ``` -------------------------------- ### Set up Rust Toolchain Source: https://github.com/starkware-libs/cairo/blob/main/README.md Ensure you have the stable Rust toolchain installed and updated. This is a prerequisite for compiling and running Cairo. ```bash rustup override set stable && rustup update ``` -------------------------------- ### Install Rust Nightly Toolchain Source: https://github.com/starkware-libs/cairo/blob/main/docs/CONTRIBUTING.md The `rustfmt` configuration for Cairo requires a nightly Rust toolchain. Install a specific nightly version using `rustup`. ```sh rustup install nightly-2026-05-04 ``` -------------------------------- ### Examples of Cairo Paths Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/path.adoc Demonstrates basic path structures in Cairo, including single and multi-segment paths. ```cairo x; x::y::z; ``` -------------------------------- ### Rust String Initialization Example Source: https://github.com/starkware-libs/cairo/blob/main/crates/cairo-lang-doc/src/tests/test-data/submodule.txt An example of initializing a String in Rust, often used in testing contexts. This snippet is for testing purposes only. ```rust let a = String::from("This also works fine"); ``` -------------------------------- ### Example of a function that will panic in Cairo Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/panic.adoc This example demonstrates a simple function that unconditionally calls `panic` with a string message. ```cairo fn will_panic() { panic(array!['error message']); } ``` -------------------------------- ### Examples of Function Calls Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/function-calls.adoc Demonstrates various ways to call functions, including calls with named arguments, positional arguments, and no arguments. ```cairo cmp::max(a: 5, b: 1) ``` ```cairo get_info() ``` ```cairo increment(ref a.b) ``` -------------------------------- ### Install asciidoctor-pdf on Ubuntu Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/readme.md Installs `asciidoctor-pdf` on Ubuntu using RubyGems, as it may not be available via apt-get. This is required for converting AsciiDoc files to PDF. ```bash sudo apt-get install ruby ruby-dev sudo gem install asciidoctor-pdf ``` -------------------------------- ### Struct Definition with Code Example Source: https://github.com/starkware-libs/cairo/blob/main/crates/cairo-lang-doc/src/tests/test-data/basic.txt Shows a struct definition and an example of its usage within a code block in the documentation. Links within code blocks are not tokenized. ```cairo struct Circle {} fn new_circle() { // [Circle] <- this should not tokenize as a link (neither be resolved), we're inside code block. } ``` -------------------------------- ### Variable and Array Assignment Examples Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/assignment-statement.adoc Illustrates how to assign new values to mutable variables and arrays in Cairo. ```cairo let mut x = 5; x = 10; // Assigns 10 to x let mut arr = array![1, 2, 3]; arr = array![4, 5, 6]; // Assigns a new array to arr ``` -------------------------------- ### Compact Struct Example (No Padding) Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/type-layout.adoc Demonstrates Cairo's lack of padding and alignment in struct layouts, where fields are packed tightly. ```cairo struct Compact { a: u8, b: u8, } ``` -------------------------------- ### Define a Struct with Attributes and Example Usage Source: https://github.com/starkware-libs/cairo/blob/main/crates/cairo-lang-doc/src/tests/test-data/basic.txt Defines a `Point` struct with `Drop` and `Copy` attributes, including public and private fields. An example usage block demonstrates how to instantiate the struct. ```cairo struct Point { pub x: u32, y: u32, } ``` ```cairo fn new_Point() { Point {x: 12, y: 14} } ``` -------------------------------- ### Boolean Operations Example Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/boolean-types.adoc Demonstrates logical, bitwise, and comparison operations on boolean variables. Use `assert` to verify conditions. ```cairo fn main() { let x: bool = true; let y = false; // Logical operations let z1 = x && y; // false let z2 = x || y; // true let z3 = !x; // false // Bitwise operations let z4 = x & y; // false let z5 = x | y; // true // Comparisons assert(x == true, 'x is true'); assert(x != y, 'x and y differ'); } ``` -------------------------------- ### Option Chaining Example Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/error-propagation-operator.adoc Shows how the `?` operator can be used to chain operations that return `Option`. If any operation returns `None`, the function exits early. ```cairo fn get_first_char(s: @ByteArray) -> Option { s.at(0) } fn process() -> Option { let s: ByteArray = "hello"; let first = get_first_char(@s)?; Option::Some(first) } fn process_empty() -> Option { let s: ByteArray = ""; let first = get_first_char(@s)?; Option::Some(first) } ``` -------------------------------- ### All Struct Expression Examples Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/struct-expressions.adoc Demonstrates various ways to create struct instances, including basic instantiation, field init shorthand, functional updates, and fields in different orders. ```cairo #[derive(Drop, Copy)] struct Rectangle { width: u32, height: u32, } fn examples() { // Basic instantiation let rect1 = Rectangle { width: 30, height: 50 }; // Field init shorthand let width = 40; let height = 60; let rect2 = Rectangle { width, height }; // Functional update let rect3 = Rectangle { width: 100, ..rect1 }; // height copied from rect1 // Fields in different order let rect4 = Rectangle { height: 20, width: 10 }; } ``` -------------------------------- ### Install asciidoctor-pdf on macOS Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/readme.md Installs the `asciidoctor-pdf` converter on macOS using Homebrew. This is needed for generating PDF documents from AsciiDoc files. ```bash brew install asciidoctor-pdf ``` -------------------------------- ### Method Call Examples Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/functions.adoc Illustrates how to call methods on a struct instance using dot notation. Shows calls to `increment` (using a mutable reference) and `get_value` (using a snapshot). ```cairo let mut counter = Counter { value: 0 }; counter.increment(); // Calls increment with ref self let value = counter.get_value(); // Calls get_value with snapshot ``` -------------------------------- ### Import Cycle Example in Cairo Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/use.adoc Demonstrates a potential import cycle scenario where modules try to import items from each other, which the Cairo compiler will flag as an error. ```cairo mod foo { use super::bar; } use foo::bar; ``` -------------------------------- ### Install asciidoctor on macOS Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/readme.md Installs the `asciidoctor` tool on macOS using Homebrew. This is required for converting AsciiDoc files to HTML. ```bash brew install asciidoctor ``` -------------------------------- ### Arithmetic Negation Panic Example Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/negation-operators.adoc Shows how negating the minimum value of a signed integer type results in a panic due to underflow. ```cairo fn will_panic() { let min: i8 = Bounded::::MIN; let result = -min; // Panics: i8_neg Underflow } ``` -------------------------------- ### Cairo Documentation Example for map Function Source: https://github.com/starkware-libs/cairo/blob/main/crates/cairo-lang-doc/src/tests/test-data/comment_markers.txt Illustrates the usage of the `map` function with `Option`. It shows how to apply a transformation to a contained value or handle `None`. ```cairo let maybe_some_string: Option = 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 = None; assert!(x.map(|s: ByteArray| s.len()) == None); ``` -------------------------------- ### Enum Variant Documentation Source: https://github.com/starkware-libs/cairo/blob/main/crates/cairo-lang-doc/src/tests/test-data/basic.txt Demonstrates how enum variants are documented. The 'Yes' and 'No' variants are simple examples. ```cairo Yes ``` ```cairo No ``` -------------------------------- ### Function Signature and Body Example Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/functions.adoc Illustrates a function signature with generic parameters and a function body. The signature defines the function's interface, while the body contains the executable code. ```cairo fn inc_n(x: T) -> T { x + N } ``` -------------------------------- ### Immutable Memory Example Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/type-layout.adoc Demonstrates Cairo's immutable memory. Reassigning a variable creates a new binding rather than mutating the original memory cell. ```cairo let mut x = 10; x = 20; // Creates new binding, doesn't mutate original cell ``` -------------------------------- ### Enum Type Compatibility Example Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/enum-types.adoc Illustrates that different generic instantiations of the same enum type are incompatible. ```cairo enum Container { Value: T, Empty, } let x: Container = Container::Value(1_u32); let y: Container = Container::Value(2); // x and y have different types: Container vs Container ``` -------------------------------- ### Associativity Examples in Cairo Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/operator-precedence.adoc Demonstrates left-to-right associativity for operators of the same precedence group, such as subtraction and division. ```cairo let x = 20 - 5 - 3; // Parsed as (20 - 5) - 3 let y = 8 / 2 / 2; // Parsed as (8 / 2) / 2 ``` -------------------------------- ### Run Cargo Tests Source: https://github.com/starkware-libs/cairo/blob/main/README.md Verify that your Rust installation is correct by running the project's tests from the root directory. ```bash cargo test ``` -------------------------------- ### Named Generic Arguments Example Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/generics.adoc Demonstrates the use of named generic arguments, allowing for flexibility in the order of specifying generic parameters during function or type instantiation. ```cairo let x = foo::(5); let x = foo::(5); ``` -------------------------------- ### Basic Cairo Variable Declaration Source: https://github.com/starkware-libs/cairo/blob/main/crates/cairo-lang-doc/src/tests/test-data/submodule.txt A simple example demonstrating variable declaration in Cairo. This snippet is for testing purposes only. ```cairo let a = 5; ``` -------------------------------- ### Concrete Paths in Expressions Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/path.adoc Shows examples of concrete paths used in function calls and enum variant expressions. ```cairo foo::bar::() // Function call expression Option::::Some(true) // Enum variant expression ``` -------------------------------- ### Cairo Structs and Member Access Example Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/member-access-expressions.adoc Demonstrates basic, expression-based, and nested member access on struct instances. Ensure the struct fields are correctly defined before access. ```cairo struct Point { x: felt252, y: felt252, } struct Line { start: Point, end: Point, } fn example() -> felt252 { let p = Point { x: 10, y: 20 }; // Basic member access let x_val: felt252 = p.x; // Member access in expressions let sum: felt252 = p.x + p.y; // Nested struct member access let line = Line { start: Point { x: 0, y: 0 }, end: Point { x: 10, y: 10 } }; let end_x: felt252 = line.end.x; sum } ``` -------------------------------- ### Move Semantics Example (Non-Compiling) Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_semantics/pages/linear-types.adoc Demonstrates how passing a value to a function moves it, making it unusable afterward. This code will not compile because `a` is used twice. ```cairo struct A {} fn main() { let a = A {}; foo(a); // value is passed by value once here. foo(a); // error: Value was previously moved. } ``` -------------------------------- ### Basic Cairo Variable Declaration Source: https://github.com/starkware-libs/cairo/blob/main/crates/cairo-lang-doc/src/tests/test-data/submodule.txt Demonstrates a simple variable declaration in Cairo. This is a basic example for testing purposes. ```cairo let a = 5; ``` -------------------------------- ### Struct Layout Example Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/type-layout.adoc Structs are laid out sequentially in memory without padding or alignment. The total size is the sum of all field sizes. ```cairo struct Point { x: u128, y: u128, } // Total size: 2 struct Mixed { a: u8, b: bool, c: u256, } // Total size: 4 ``` -------------------------------- ### Operator Precedence Examples in Cairo Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/operator-precedence.adoc Illustrates how arithmetic, unary, and postfix operators are evaluated based on their precedence. Use parentheses to override default precedence. ```cairo // Arithmetic binds tighter than comparison and logical operators. let a = 2 + 3 * 4 == 14 && true; // ((2 + (3 * 4)) == 14) && true // Prefix unary operators bind tighter than arithmetic operators. let b = -x * 2; // (-x) * 2 // Postfix operators bind tighter than arithmetic operators. let c = arr[0] + 1; // (arr[0]) + 1 // Use parentheses to override default precedence. let d = (2 + 3) * 4; ``` -------------------------------- ### Felt252 Modular Arithmetic Example Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/felt252-type.adoc Illustrates how adding 1 to the maximum felt252 value results in 0 due to modular arithmetic. ```cairo fn main() { // Maximum value of felt252 (P - 1) let max: felt252 = 3618502788666131213697322783095070105623107215331596699973092056135872020480; let one: felt252 = 1; // Adding 1 wraps to 0 assert(max + one == 0, 'P == 0 (mod P)'); } ``` -------------------------------- ### Felt252Dict for Key-Value Storage Source: https://context7.com/starkware-libs/cairo/llms.txt Demonstrates `Felt252Dict` for mapping `felt252` keys to values. Shows usage of `insert`, `get`, `entry`, and `finalize` for both copy and non-copy types. ```cairo use core::dict::Felt252Dict; fn demo_dict() { let mut dict: Felt252Dict = Default::default(); dict.insert(0, 10); dict.insert(1, 20); assert!(dict.get(0) == 10); assert!(dict.get(1) == 20); // Update via entry/finalize (works for non-Copy types too) let (entry, _old_val) = dict.entry(0); dict = entry.finalize(99); assert!(dict.get(0) == 99); } ``` -------------------------------- ### Cairo Type and Impl Inference Examples Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/inference.adoc Demonstrates type inference for variables and generic arguments, as well as impl inference for trait method calls. ```cairo let x = 1_u8; let y = Option<_>::Some(x); let u: u32 = Into::::into(x); let u: u32 = x.into(); ``` -------------------------------- ### Concrete Paths in Trait Expressions Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/path.adoc Provides examples of concrete paths used within trait implementations and generic trait bounds. ```cairo impl MyImpl of MyTrait { // trait expression after `of` keyword ... } fn foo>() { ... } // trait expression after `:` in an impl generic argument ``` -------------------------------- ### Tuple Layout Example Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/type-layout.adoc Tuples are laid out sequentially in memory, similar to structs, with no padding. The total size is the sum of the sizes of its elements. ```cairo let t: (u128, bool, u256) = (10, true, 256); // Layout: [10, 1, 256_low, 256_high] // Size: 1 + 1 + 2 = 4 cells ``` -------------------------------- ### Verify Rust Installation with Cargo Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/getting_started/pages/prerequisites.adoc Navigates into the cloned Cairo directory and runs cargo tests to confirm that Rust and the Cairo project are set up correctly. ```bash cd cairo && cargo test ``` -------------------------------- ### Example of a conditional panic in Cairo Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/panic.adoc This function shows how to conditionally panic based on a runtime condition, in this case, checking if an input value is zero. ```cairo fn conditional_panic(x: u32) { if x == 0 { panic(array!['x cannot be zero']); } } ``` -------------------------------- ### Basic Function Call Syntax Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/function-calls.adoc Illustrates the general syntax for calling a function with its concrete path and arguments. Use this for standard function invocations. ```cairo (,,...) ``` -------------------------------- ### Basic impl alias example Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/impl-aliases.adoc Defines a trait and an impl, then creates an impl alias for a shorter name. `FeltPow` is an alias for `AnyAlgebraPow`. ```cairo trait Pow { fn pow(base: T, exp: u32) -> T; } impl AnyAlgebraPow> of Pow { fn pow(base: T, exp: u32) -> T { // Implementation details. base } } // Impl alias for Pow of felt252. impl FeltPow = AnyAlgebraPow; fn main() { // Call through the trait name. let x = Pow::pow(5, 3); // Call through the impl alias name. let y = FeltPow::pow(5, 3); } ``` -------------------------------- ### Define a Basic Starknet Contract Source: https://context7.com/starkware-libs/cairo/llms.txt Use `#[starknet::contract]` to mark a module as a Starknet contract. `#[storage]` defines persistent state, and `#[abi(embed_v0)]` exposes functions via the ABI. This example shows a simple counter contract. ```cairo #[starknet::interface] trait IHelloStarknet { fn increase_balance(ref self: TContractState, amount: usize); fn get_balance(self: @TContractState) -> usize; } #[starknet::contract] mod hello_starknet { use starknet::storage::{StoragePointerReadAccess, StoragePointerWriteAccess}; #[storage] struct Storage { balance: usize, } #[abi(embed_v0)] impl HelloImpl of super::IHelloStarknet { fn increase_balance(ref self: ContractState, amount: usize) { self.balance.write(self.balance.read() + amount); } fn get_balance(self: @ContractState) -> usize { self.balance.read() } } } ``` -------------------------------- ### Generate Impl from Another Impl Source: https://github.com/starkware-libs/cairo/blob/main/adrs/003_simple_trait_system.md This example shows how to generate an implementation for one trait based on an existing implementation of another trait, similar to Rust's generic trait bounds. ```cairo impl CloneFromCopy> of Clone {} ``` -------------------------------- ### Cairo Tuple Type Examples Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/tuple-types.adoc Demonstrates various ways to define tuple types in Cairo, including the unit type, 1-ary tuples, and multi-ary tuples with different data types. ```cairo () (bool,) (u32, u256) (felt252, u16, Option) ``` -------------------------------- ### Getting ByteArray Length Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/string-types.adoc The .len() method returns the number of bytes in a ByteArray. ```cairo let s: ByteArray = "byte array"; let len = s.len(); // Returns 10 ``` -------------------------------- ### If-else if chain for number classification Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/if-expressions.adoc A practical example of an `if-else if` chain to classify a number. ```cairo fn classify_number(x: i32) -> ByteArray { if x < 0 { "negative" } else if x == 0 { "zero" } else if x < 10 { "single digit" } else { "multi digit" } } ``` -------------------------------- ### Chaining impl aliases example Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/impl-aliases.adoc Demonstrates chaining impl aliases, where one alias refers to another. `ImplAlias1` and `Impl2Alias` are names for existing impls and can be used in generic parameters or trait method calls. ```cairo trait Trait1 { fn func1(value: T); } trait Trait2 { fn func2(value: T); } mod impls { impl Impl1> of super::Trait1 { fn func1(value: T) {} } // Public alias for a concrete impl of Trait1. pub impl ImplAlias1 = Impl1; impl Impl2> of super::Trait2 { fn func2(value: T) {} } // Public alias for a concrete impl of Trait2. pub impl ImplAlias2 = Impl2; } use impls::ImplAlias1; // A second-level alias that refers to an impl alias from another module. impl Impl2Alias = impls::ImplAlias2; ``` -------------------------------- ### Using System Calls Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/contracts.adoc Details how to use the `starknet::syscalls::call_contract_syscall` system call for direct contract interaction. ```APIDOC ## Using System Calls Another way to call another contract is to use the `starknet::syscalls::call_contract_syscall` system call. To directly call another contract using `starknet::syscalls::call_contract_syscall` you can do the following, but the result is the serialized return value of the function which you need to deserialize yourself. ```cairo #[starknet::interface] trait IMySecondContract { fn syscall_call_another_contract( ref self: TContractState, address: starknet::ContractAddress, selector: felt252, calldata: Array, ) -> Span; } #[starknet::contract] mod my_second_contract { use starknet::SyscallResultTrait; #[storage] struct Storage {} #[abi(embed_v0)] ``` -------------------------------- ### Cairo Test Annotations Source: https://context7.com/starkware-libs/cairo/llms.txt Examples of Cairo test annotations for basic assertions and expected panics. ```cairo // Test annotations supported by cairo-test #[test] fn test_addition() { let a: u8 = 5; let b: u8 = 10; assert_eq!(a + b, 15); } #[test] #[should_panic] fn test_division_by_zero() { let _x: u8 = 1 / 0; } ``` -------------------------------- ### Struct with Derive Attribute Source: https://github.com/starkware-libs/cairo/blob/main/crates/cairo-lang-doc/src/tests/test-data/basic.txt Example of a struct with the `Drop` derive attribute, indicating it can be dropped and will shatter. ```cairo #[derive(Drop)] struct Glass {} This glass is droppable. When it's dropped, it shatters. ``` ```cairo #[derive(Drop)] struct Cup {} This cup is droppable. When it's dropped, it shatters. ``` -------------------------------- ### Concrete Path with Generic Arguments Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/path.adoc Illustrates how to use concrete paths with explicit generic arguments and how the compiler infers them. ```cairo fn foo(a: A, b: B) { ... } fn main() { foo::(false, 3_u32); // OK foo::(false, 3_u32); // OK, B is inferred to be u32 foo::(false, 3_u32); // OK, B is inferred to be u32 foo(false, 3_u32); // OK, A, B are inferred as bool and u32 respectively } ``` -------------------------------- ### Get Length of Dynamic Array Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/array-types.adoc Retrieves the number of elements in a dynamic array. Returns `usize`. ```cairo let len = arr.len(); // usize ``` -------------------------------- ### Common Use Case: Creating Multiple References Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/snapshot-type.adoc Shows how to create multiple references to a large data structure using snapshots, enabling different parts of the program to access the same data immutably. ```cairo let data = create_large_structure(); worker1(@data); worker2(@data); ``` -------------------------------- ### Basic Starknet Contract Source: https://context7.com/starkware-libs/cairo/llms.txt Demonstrates a simple Starknet contract with state storage and ABI-exposed functions for managing a balance. ```APIDOC ## Starknet Smart Contracts — Basic Contract The `#[starknet::contract]` attribute marks a module as a Starknet contract. `#[storage]` defines persistent on-chain state, and `#[abi(embed_v0)]` exposes functions through the ABI. ```cairo #[starknet::interface] trait IHelloStarknet { fn increase_balance(ref self: TContractState, amount: usize); fn get_balance(self: @TContractState) -> usize; } #[starknet::contract] mod hello_starknet { use starknet::storage::{StoragePointerReadAccess, StoragePointerWriteAccess}; #[storage] struct Storage { balance: usize, } #[abi(embed_v0)] impl HelloImpl of super::IHelloStarknet { fn increase_balance(ref self: ContractState, amount: usize) { self.balance.write(self.balance.read() + amount); } fn get_balance(self: @ContractState) -> usize { self.balance.read() } } } // Compile: // cargo run --bin starknet-compile -- --single-file hello_starknet.cairo hello.json ``` ``` -------------------------------- ### Manual Implementation of PartialEq Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/equality-operators.adoc Illustrates how to manually implement the `PartialEq` trait for a custom struct. ```cairo #[derive(Copy, Drop)] struct Id { value: felt252 } impl IdEq of PartialEq { fn eq(lhs: @Id, rhs: @Id) -> bool { lhs.value == rhs.value } } ``` -------------------------------- ### Iterating over a Span in Cairo Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/slice-types.adoc Provides examples of iterating over a Span using for loops, manual `pop_front()` in a while loop, and the `into_iter()` method. ```cairo // For loop iteration for x in array![1, 2, 3].span() { // x is @T (snapshot of element) // Dereference with * to use the value let value = *x; } // Manual iteration let mut span = array![10, 20, 30].span(); while let Option::Some(value) = span.pop_front() { // value is @T, dereference with *value to use it } // Using iterator let mut iter = array![1, 2, 3].span().into_iter(); while let Option::Some(value) = iter.next() { // value is @T } ``` -------------------------------- ### Recursive Fibonacci in Cairo Source: https://context7.com/starkware-libs/cairo/llms.txt Example of a recursive Fibonacci function implementation in Cairo using `felt252` for arithmetic operations in the field. ```cairo // fib.cairo — recursive Fibonacci using felt252 pub fn fib(a: felt252, b: felt252, n: felt252) -> felt252 { match n { 0 => a, _ => fib(b, a + b, n - 1), } } fn main() -> felt252 { fib(1, 1, 10) // => 89 } ``` -------------------------------- ### Defining and Calling a Method in Cairo Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/method-calls.adoc Demonstrates how to define a trait with a method and implement it for a type. The method can then be called using the convenient method call syntax. ```cairo trait Display { fn display(self: T) -> Array; } impl DisplayUsize of Display { fn display(self: usize) -> Array { // Implementation details omitted for brevity // ... } } fn bar>(value: T) { // ... // Can be called as a method. let c = value.display(); // ... } ``` -------------------------------- ### Grade calculation using if-else if chain Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/if-expressions.adoc An example of using an `if-else if` chain to determine a letter grade based on a score. ```cairo fn grade(score: u32) -> ByteArray { if score >= 90 { "A" } else if score >= 80 { "B" } else if score >= 70 { "C" } else if score >= 60 { "D" } else { "F" } } ``` -------------------------------- ### Valid if without else returning unit type Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/if-expressions.adoc This example shows a valid use case where the `if` branch also returns `()`. ```cairo let x = 5; if x > 10 { do_something(); // Returns () } ``` -------------------------------- ### Document a Function with Default Implementation Source: https://github.com/starkware-libs/cairo/blob/main/crates/cairo-lang-doc/src/tests/test-data/basic.txt Provides documentation for a function `abc` which has a default implementation. Includes inner comments for detailed explanations. ```cairo Default impl of abc TraitTest function. Default impl of abc TraitTest function inner comment. ``` -------------------------------- ### Integer Overflow Behavior Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/integer-types.adoc Illustrates that integer operations in Cairo panic on overflow. This example shows an overflow with `u8` addition. ```cairo fn will_panic() { let x: u8 = 255; let y = x + 1; // Panics: u8_add Overflow } ``` -------------------------------- ### Instantiate a Struct Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/structs.adoc Instantiate a struct by providing values for all its members using the struct expression syntax. All members must be specified, but their order does not matter. ```cairo let mut tree = Tree { height: 6, number_of_leaves: 10000, }; ``` -------------------------------- ### Basic Function Definitions Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/functions.adoc Defines two simple functions: `main` for entry point and `inc` for incrementing a value. Functions are declared using the `fn` keyword. ```cairo fn main() { let x = 3; } fn inc(x: u32) -> u32 { x + 1 } ``` -------------------------------- ### Processing Sequences with Span in Cairo Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/slice-types.adoc An example function that calculates the sum of elements in a Span by repeatedly popping elements from the front. ```cairo fn sum_span(mut span: Span) -> u32 { let mut total = 0; while let Option::Some(val) = span.pop_front() { total += *val; } } ``` -------------------------------- ### Define and Use Reusable Ownable Component in Cairo Source: https://context7.com/starkware-libs/cairo/llms.txt Demonstrates creating a reusable `Ownable` component with ownership transfer functionality and embedding it into a Starknet contract. Ensure the component's storage and event definitions are correctly integrated. ```cairo use starknet::ContractAddress; // ---- Ownable component (reusable) ---- #[starknet::component] pub mod ownable { use starknet::ContractAddress; use starknet::storage::{StoragePointerReadAccess, StoragePointerWriteAccess}; #[storage] pub struct Storage { pub owner: ContractAddress, } #[embeddable_as(Transfer)] pub impl TransferImpl> of super::TransferTrait> { fn owner(self: @ComponentState) -> ContractAddress { self.owner.read() } fn transfer_ownership(ref self: ComponentState, new_owner: ContractAddress) { assert(self.owner.read() == starknet::get_caller_address(), 'Wrong owner.'); self.owner.write(new_owner); } } } // ---- Contract using the Ownable component ---- #[starknet::contract] mod my_contract { use crate::components::ownable::ownable as ownable_comp; component!(path: ownable_comp, storage: ownable, event: OwnableEvent); #[storage] struct Storage { data: u128, #[substorage(v0)] ownable: ownable_comp::Storage, } #[event] #[derive(Drop, starknet::Event)] enum Event { OwnableEvent: ownable_comp::Event, } // Embed the full Transfer interface into this contract's ABI #[abi(embed_v0)] impl Ownable = ownable_comp::TransferImpl; } ``` -------------------------------- ### Implement Contract Entry Points Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/contracts.adoc Implements the contract's external entry points by defining functions within an `impl` block marked with `#[abi(embed_v0)]`. This allows interaction with the contract's state. ```cairo #[abi(embed_v0)] impl MyContractImpl of super::IMyContract { fn set_value(ref self: ContractState, value: felt252) { self.x.write(value); } fn get_value(self: @ContractState) -> felt252 { self.x.read() } } ``` -------------------------------- ### Pattern Matching with Option Enum Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/enum-types.adoc Demonstrates how to use pattern matching to access values within an Option enum. ```cairo fn process_option(value: Option) -> u32 { match value { Option::Some(x) => x, Option::None => 0, } } ``` -------------------------------- ### Equality Comparisons with Snapshots Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/equality-operators.adoc Demonstrates that if `T: PartialEq`, comparisons on snapshots (`@T`) are automatically supported. ```cairo fn same_point(p1: @Point, p2: @Point) -> bool { p1 == p2 // uses PartialEq<@Point> derived from PartialEq } ``` -------------------------------- ### Arithmetic Negation Examples Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/negation-operators.adoc Demonstrates arithmetic negation for signed integers and `felt252`. Negation of `felt252` is performed modulo the field prime. ```cairo fn main() { let value: i32 = -42; let negated: i32 = -value; // negated = 42 let x: felt252 = 5; let neg_x: felt252 = -x; // Negation modulo the field prime } ``` -------------------------------- ### Early Function Exit with Return Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/return-expressions.adoc Illustrates how `return` statements exit a function immediately, skipping any subsequent code. This is useful for handling error conditions or specific cases early. ```cairo fn check_positive(x: i32) -> felt252 { if x < 0 { return 0; // Exit early if negative } x.into() } ``` -------------------------------- ### Cairo Line Comments Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/comments.adoc Use line comments starting with `//` for explanatory notes within your code. They extend to the end of the line. ```cairo // Test simple access. let ba: ByteArray = "AB"; let span = ba.span(); ``` -------------------------------- ### Deserialization using Span in Cairo Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/slice-types.adoc A practical example showing how a Span can be used to deserialize data, such as a Point struct, by consuming elements from the span. ```cairo fn deserialize_point(ref data: Span) -> Option { let x = (*data.pop_front()?).try_into()?; let y = (*data.pop_front()?).try_into()?; Option::Some(Point { x, y }) } ``` -------------------------------- ### Common Use Case: Working with Generic Functions Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/snapshot-type.adoc Demonstrates using snapshots in generic functions. A snapshot allows the generic function to operate on a value and use it multiple times, as shown with `println!`. ```cairo fn print_twice>(value: @T) { println!("{}", value); println!("{}", value); // Can use snapshot twice } ``` -------------------------------- ### Variable Dropping Example (Non-Compiling) Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_semantics/pages/linear-types.adoc Highlights the restriction that values may not go out of scope unless moved. This code will not compile because the `A` instance is not dropped. ```cairo #[derive(Copy)] struct A {} fn main() { A {}; // error: Value not dropped. } ``` -------------------------------- ### Function Call with Expression and Reference Arguments Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/function-calls.adoc Shows how to pass both expression and reference arguments to a function. Note the use of `ref` for reference arguments. ```cairo fn main() { let x = 3; let mut y = A { z: 5 }; foo(x, ref y.z); } ``` -------------------------------- ### Compile Starknet Contract to Sierra ContractClass Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/getting_started/pages/compiling-starknet-contracts.adoc Use this command to compile a Starknet crate into a Sierra ContractClass. Specify the input crate path and the output JSON file path. ```bash cargo run --bin starknet-compile -- /path/to/crate /path/to/output.json ``` -------------------------------- ### Bitwise NOT with Different Integer Types Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/negation-operators.adoc Provides examples of the bitwise NOT operator `~` applied to various unsigned integer types (`u8`, `u32`, `u16`). ```cairo fn bitwise_examples() { let a: u8 = 0xFF; let not_a = ~a; // 0x00 let b: u32 = 0x0000FFFF; let not_b = ~b; // 0xFFFF0000 let c: u16 = 0b1111000011110000; let not_c = ~c; // 0b0000111100001111 } ``` -------------------------------- ### Compile Starknet Contract with Specific Contract Path Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/getting_started/pages/compiling-starknet-contracts.adoc When multiple contracts are defined in a single crate, use the `--contract-path` flag to specify the exact contract to compile. ```bash cargo run --bin starknet-compile -- /path/to/crate /path/to/output.json --contract-path path::to::contract ``` -------------------------------- ### Generic Identity Function Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/generics.adoc Defines a generic function that takes any type T and returns it unchanged. This serves as a basic example of a generic function recipe. ```cairo fn foo(x: T) -> T { x } ``` -------------------------------- ### Import Items with `use` Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/namespaces.adoc Import specific items from other modules using `use`. You can import multiple items, use aliases with `as`, or import all items using a glob (`*`), though glob imports should be used carefully. ```cairo use crypto::hash::sha256; use std::array::ArrayTrait as Arr; use my_module::{item1, item2}; use my_module::*; // Glob (use carefully) ``` -------------------------------- ### Organize Related Functionality with Modules Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/module.adoc Group related code, such as adapters and traits, into separate modules. Use `pub use` to expose specific items from these modules. ```cairo mod adapters; mod traits; pub use adapters::PeekableTrait; pub use adapters::zip::zip; pub use traits::{Extend, FromIterator, IntoIterator, Iterator, Product, Sum}; ``` -------------------------------- ### Iterating Over a Range in Cairo Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/for-loop-expressions.adoc Example of using a for loop to iterate over a range of numbers. The loop variable `i` will take values from 0 up to (but not including) 5. ```cairo for i in 0..5_usize { // i takes values 0, 1, 2, 3, 4 } ``` -------------------------------- ### Call Another Contract Syscall in Cairo Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/contracts.adoc Demonstrates how to use the `call_contract_syscall` to invoke another contract. Ensure the `starknet` module is imported. ```cairo impl MySecondContractImpl of super::IMySecondContract { fn syscall_call_another_contract( ref self: ContractState, address: starknet::ContractAddress, selector: felt252, calldata: Array ) -> Span { starknet::syscalls::call_contract_syscall( :address, entry_point_selector: selector, calldata: calldata.span() ).unwrap_syscall() } } } ``` -------------------------------- ### Accessing Span Elements in Cairo Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/slice-types.adoc Shows how to access elements within a Span using indexing and the safe `get()` method, which returns an Option. ```cairo let span = array![10, 20, 30].span(); // Indexing (returns snapshot of element) let second = span[1]; // Returns @20 (panics if out of bounds) let second = span.at(1); // Returns @20 (panics if out of bounds) // Safe access with Option let opt = span.get(1); // Returns Option> match opt { Option::Some(val) => { let v = val.unbox(); // @20 }, Option::None => {}, } ``` -------------------------------- ### Slicing a Span in Cairo Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/slice-types.adoc Demonstrates creating a sub-span from an existing Span using the `slice(start, length)` method. Panics if the range is invalid. ```cairo let span = array![10, 20, 30, 40, 50].span(); let sub = span.slice(1, 3); // Returns Span containing [20, 30, 40] ``` -------------------------------- ### Main Function Signature Source: https://github.com/starkware-libs/cairo/blob/main/crates/cairo-lang-doc/src/tests/test-data/signature.txt The entry point of a Cairo program. ```cairo fn main() {} ``` -------------------------------- ### Run a Gas-Tested Cairo File Source: https://github.com/starkware-libs/cairo/blob/main/crates/cairo-lang-runner/README.md Execute a Cairo file with a specified amount of available gas. This is useful for gas testing. ```bash cargo run --bin cairo-run -- --single-file /path/to/file.cairo --available-gas 200 ``` -------------------------------- ### Example of a function returning unit type implicitly Source: https://github.com/starkware-libs/cairo/blob/main/docs/reference/src/components/cairo/modules/language_constructs/pages/unit-type.adoc This function performs an assertion and does not explicitly return a value, thus implicitly returning the unit type `()`. ```cairo pub fn assert_eq>(a: @T, b: @T, err_code: felt252) { assert(a == b, err_code); } ``` -------------------------------- ### Struct Documentation with Code Block Source: https://github.com/starkware-libs/cairo/blob/main/crates/cairo-lang-doc/src/tests/test-data/basic.txt Illustrates documentation for a struct that includes a multi-line code block. Comments and links within these blocks are ignored. ```cairo struct Square {} First line of code // Comment inside the code block, that should be ignored. [Square] <- it will be ignored as well. Second line of code ``` -------------------------------- ### Run Cairo Tests with cairo-test CLI Source: https://github.com/starkware-libs/cairo/blob/main/docs/CONTRIBUTING.md Execute Cairo tests using the `cairo-test` command-line tool. Specify the path to your Cairo project. ```sh cargo run --bin cairo-test -- ``` -------------------------------- ### Basic Cairo Test Functions Source: https://github.com/starkware-libs/cairo/blob/main/crates/cairo-lang-test-runner/README.md These are example Cairo test functions demonstrating the use of `assert`. The `#[should_panic]` attribute is used to test failing assertions. ```cairo #[test] fn test_assert_true() { // Asserts that true is true. assert(true, 'assert(true)'); } #[test] #[should_panic] fn test_assert_false() { assert(false, 'assert(false)'); } ``` -------------------------------- ### Run Cairo Bug Samples Tests with Starknet Source: https://github.com/starkware-libs/cairo/blob/main/docs/CONTRIBUTING.md Run tests for bug samples, including Starknet-specific features, using the `cairo-test` tool. ```sh cargo run --bin cairo-test -- tests/bug_samples --starknet ```