Starknet 백서

Starknet

원문

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 73쪽 중 27쪽

2) -> u128; } #[starknet::contract] mod Mappings { use starknet::storage::{StorageMapReadAccess, StorageMapWriteAccess}; #[storage] struct Storage { // Simple mapping from u32 to u128 values: Map<u32, u128>, } #[abi(embed_v0)] impl Mappings of super::IMappings<ContractState> { fn set_value(ref self: ContractState, key: u32, value: u128) { // Write a value to the map self.values.write(key, value); } fn get_value(self: @ContractState, key: u32) -> u128 { // Read a value from the map self.values.read(key) } } } ``` Let's break down the key components: * **Declaration**: Maps are declared using `Map<KeyType, ValueType>` syntax * **Storage**: Maps must be declared inside the contract's `Storage` struct * You need to import the `StorageMapReadAccess` and `StorageMapWriteAccess` traits from `starknet::storage` * **Operations**: * `write(key, value)`: Stores a value for a given key * `read(key)`: Retrieves the value associated with a key * Maps automatically initialize all values to zero * Keys and values must be of valid storage types, see [Storing Custom Types](./storing-custom-types) ### Composite Keys For more complex scenarios, you can use composite keys by combining multiple values: ```rust theme={null} // Example: ERC20 allowance mapping Map<(ContractAddress, ContractAddress), felt252> // (owner, spender) -> amount ``` ### Storage Layout (advanced) Under the hood, Cairo maps use a deterministic storage layout: * Each key-value pair is stored at a unique address calculated using Pedersen hashes * The address formula is: $\text{h}(...\text{h}(\text{h}(\text{sn\_keccak}(name),k_1),k_2),...,k_n)$ mod $2^{251} - 256$ * Learn more in the [Cairo Book](https://www.starknet.io/cairo-book/ch101-01-00-contract-storage.html) # Storage Source: https://docs.starknet.io/build/starknet-by-example/basic/storage ## Introduction You can define storage variables to store and retrieve data in your contract. Storage in Cairo contracts is implemented as a key-value store using a struct marked with the `#[storage]` attribute. Every contract must have exactly one storage definition, which serves as the contract's persistent state on the blockchain and is kept between contract executions. ## Storage space and pointers The contract's storage space consists of $2^{251}$ *storage slots*, where each slot: * Can store a single `felt252` value * Is initialized to 0 Storage variables are stored in storage slots using Starknet's memory model abstraction called **storage pointers**. A storage pointer is a tuple `(base_address, offset)` where: * `base_address` is the address of the first slot where the variable is stored * `offset` is the distance from the base address where the variable is stored To get the base address of a storage variable, you can use the `selector!` macro to derive it from the variable name (i.e., `selector!("variable§_name")`). ## Example ```rust theme={null} mod Contract { #[storage] struct Storage { a: u128, b: u8, c: u256, } } ``` The storage layout of this contract is: * Variable `a` (`u128`): * Base address: `selector!(`"a")\` * Uses lowest 128 bits of the slot at offset 0 * Leaves 124 bits unused * Variable `b` (`u8`): * Base address: `selector!("b")` * Uses lowest 8 bits of the slot at offset 0 * Leaves 244 bits unused * Variable `c` (`u256`): * Base address: `selector!("c")` * Too large for a single slot, uses two consecutive slots: * First slot: lower 128 bits at offset 0 * Second slot: lower 128 bits at offset 1 * Leaves 248 bits unused, 124 in each slot <Note> For more complex data structures, see [storing custom types](/build/starknet-by-example/basic/storing-custom-types). </Note> <Tip> Notice how many bits are left unused in each slot? This can make storage operations expensive. To optimize storage usage, you can pack multiple variables together. Learn more in [storage optimization](/build/starknet-by-example/advanced/store-using-packing). </Tip> # Storing custom types Source: https://docs.starknet.io/build/starknet-by-example/basic/storing-custom-types In Starknet contracts, storing custom types in contract storage requires implementing the `Store` trait. While native types (like `felt252`, `u128`, etc.) can be stored directly, custom types need this additional step to generate the necessary implementation on how to handle their storage. To make a custom type storable: 1. Derive the `starknet::Store` trait for your struct 2. Add any other necessary traits like `Drop`, `Serde`, and `Copy` 3. Define your storage variables using the custom type Here's an example showing how to store a custom `Person` struct: ```rust theme={null} #[derive(Drop, starknet::Store)] struct Person { name: felt252, age: u8, is_active: bool, } #[starknet::interface] trait ICustomTypes<TContractState> { fn set_person(ref self: TContractState, person: Person); fn get_person(self: @TContractState) -> Person; } #[starknet::contract] mod CustomTypes { use starknet::storage::{StoragePointerReadAccess, StoragePointerWriteAccess}; #[storage] struct Storage { person: Person, } #[abi(embed_v0)] impl CustomTypes of super::ICustomTypes<ContractState> { fn set_person(ref self: ContractState, person: Person) { self.person.write(person); } fn get_person(self: @ContractState) -> Person { self.person.read() } } } ``` <Note> For more complex types, you might need to implement the `Store` trait manually instead of deriving it. </Note> ## Accessing Struct Members When you derive the `Store` trait, Cairo automatically generates the necessary storage pointers for each struct member. This allows you to access and modify individual fields of your stored struct directly: ```rust theme={null} #[starknet::interface] trait ICustomTypesAccess<TContractState> { fn set_name(ref self: TContractState, name: felt252); fn get_name(self: @TContractState) -> felt252; } #[starknet::contract] mod CustomTypesAccess { use starknet::storage::{StoragePointerReadAccess, StoragePointerWriteAccess}; #[storage] struct Storage { person: Person, } #[abi(embed_v0)] impl CustomTypesAccess of super::ICustomTypesAccess<ContractState> { fn set_name(ref self: ContractState, name: felt252) { // Access individual struct member self.person.name.write(name); } fn get_name(self: @ContractState) -> felt252 { // Read individual struct member self.person.name.read() } } } ``` # Variables Source: https://docs.starknet.io/build/starknet-by-example/basic/variables Cairo contracts support three types of variables, each serving a different purpose: 1. **Local Variables** * Temporary variables within functions * Exist only during function execution * Not stored on the blockchain 2. **Storage Variables** * Defined in the contract's [Storage](/build/starknet-by-example/basic/storage) * Persist between contract executions * Stored on the blockchain 3. **Global Variables** * Provide blockchain context and information * Accessible anywhere in the contract * Read-only system variables ## Local Variables Local variables are temporary variables that exist only within their defined scope (a function or code block). Key characteristics: * Stored in memory, not on the blockchain * Used for intermediate calculations and temporary data * Available only during function execution * Help improve code readability by naming values Here's an example demonstrating local variable scope: ```rust theme={null} #[starknet::contract] mod LocalVariablesContract { #[storage] struct Storage {} pub fn do_something(value: u32) -> u32 { // This variable is local to the current block. // It can't be accessed once it goes out of scope. let increment = 10; { // The scope of a code block allows for local variable declaration // We can access variables defined in higher scopes. let sum = value + increment; sum } // We can't access the variable `sum` here, as it's out of scope. } }} ``` ## Storage Variables Storage variables provide persistent state for your contract on the blockchain. They have these properties: * Persist between contract executions * Can be read for free (no transaction needed) * Require a transaction to write to them * Must be defined in the contract's Storage struct Here's an example showing storage variable usage: ```rust theme={null} #[starknet::interface] trait IStorageVariable<TContractState> { fn set(ref self: TContractState, value: u32); fn get(self: @TContractState) -> u32; } #[starknet::contract] mod StorageVariablesContract { // You need to import these storage functions to read and write to storage variables use starknet::storage::{StoragePointerReadAccess, StoragePointerWriteAccess}; use super::IStorageVariable; // All storage variables are contained in a struct called Storage // annotated with the `#[storage]` attribute #[storage] struct Storage { // Storage variable holding a number value: u32, } #[abi(embed_v0)] impl StorageVariables of IStorageVariable<ContractState> { // Write to storage variables by sending a transaction // that calls an external function fn set(ref self: ContractState, value: u32) { self.value.write(value); } // Read from storage variables without sending transactions fn get(self: @ContractState) -> u32 { self.value.read() } } } ``` <Note> Reading is a free operation, with no transaction needed. Writing requires a transaction and costs gas. </Note> ## Global Variables Global variables provide access to blockchain context and system information. In Starknet: * Accessed through core library functions * Available anywhere in the contract * Provide critical blockchain context (e.g., caller address, block info) Example using global variables: ```rust theme={null} #[starknet::contract] pub mod GlobalVariablesContract { // import the required functions from the starknet core library use starknet::get_caller_address; #[storage] struct Storage {} pub fn foo(ref self: ContractState) { // Call the get_caller_address function to get the sender address let _caller = get_caller_address(); // ... } } ``` # Functions Source: https://docs.starknet.io/build/starknet-by-example/basic/visibility-mutability ## Function Visibility In Starknet contracts, functions can have two types of visibility: * **External Functions**: Can be called by anyone, including other contracts and users * **Internal Functions**: Can only be called by other functions within the same contract ## State Mutability Every function in a contract can either modify or just read the contract's state. This behavior is determined by how we pass the `ContractState` parameter: * **State-Modifying Functions**: Use `ref self: ContractState` * Can read and write to storage * Require a transaction to execute * Cost gas to run * **View Functions**: Use `self: @ContractState` * Can only read from storage * Can be called directly through an RPC node * Free to call (no transaction needed) <Note> Internal functions follow the same state mutability rules as external functions. The only difference is who can call them. </Note> ## Implementation ### External Functions For external functions (both state-modifying and view), you need: 1. **Interface Definition** * Defined with `#[starknet::interface]` attribute * Lists all functions that can be called externally * Functions can be called as transactions or view calls * Part of the contract's public API 2. **Interface Implementation** * Uses `#[abi(embed_v0)]` attribute * Becomes part of the contract's ABI (Application Binary Interface) * ABI defines how to interact with the contract from outside * Must implement all functions defined in the interface ### Internal Functions For internal functions, there are two options: 1. **Implementation Block** * Can use `#[generate_trait]` attribute * Recommended for functions that need `ContractState` access * Sometimes prefixed with `_` to indicate internal use 2. **Direct Contract Body** * Functions defined directly in the contract * Recommended for pure functions * Useful for helper functions and calculations ## Example Here's a complete example demonstrating these concepts: ```rust theme={null} // This trait defines the public interface of our contract // All functions declared here will be accessible externally #[starknet::interface] trait ContractInterface<TContractState> { fn set(ref self: TContractState, value: u32); fn get(self: @TContractState) -> u32; } #[starknet::contract] mod Contract { use starknet::storage::{StoragePointerReadAccess, StoragePointerWriteAccess}; use super::ContractInterface; #[storage] pub struct Storage { pub value: u32, } // External Functions Implementation // The `#[abi(embed_v0)]` attribute makes these functions callable from outside the contract // This is where we implement our public interface defined in ContractInterface #[abi(embed_v0)] pub impl ContractImpl of ContractInterface<ContractState> { // External function that can modify state // - Takes `ref self` to allow state modifications // - Calls internal `increment` function to demonstrate internal function usage fn set(ref self: ContractState, value: u32) { self.value.write(increment(value)); } // External view function (cannot modify state) // - Takes `@self` (snapshot) to prevent state modifications // - Demonstrates calling an internal function (_read_value) fn get(self: @ContractState) -> u32 { self._read_value() } } // Internal Functions Implementation // These functions can only be called from within the contract // The #[generate_trait] attribute creates a trait for these internal functions #[generate_trait] pub impl Internal of InternalTrait { // Internal view function // - Takes `@self` as it only needs to read state // - Can only be called by other functions within the contract fn _read_value(self: @ContractState) -> u32 { self.value.read() } } // Pure Internal Function // - Doesn't access contract state // - Defined directly in the contract body // - Considered good practice to keep pure functions outside impl blocks // It's also possible to use ContractState here, but it's not recommended // as it'll require to pass the state as a parameter pub fn increment(value: u32) -> u32 { value + 1 } } ``` <Note> Cairo contracts can implement multiple interfaces and have multiple internal implementation blocks. This is not only possible but recommended because it: * Keeps each implementation block focused on a single responsibility * Makes the code more maintainable and easier to test * Simplifies the implementation of standard interfaces * Allows for better organization of related functionality </Note> # Introduction to Starknet By Example Source: https://docs.starknet.io/build/starknet-by-example/index ## What is Starknet By Example? Starknet By Example provides practical examples for building smart contracts on Starknet using the Cairo programming language. <Warning> The examples in Starknet By Example are for educational purposes and have not been audited. Do not use this code in production. The authors are not liable for any damages resulting from the use of this code. </Warning> ## Who is Starknet By Example for? Starknet By Example is designed for developers with basic programming and blockchain knowledge who want to learn Starknet smart contract development using Cairo. The content is structured progressively - early chapters cover Cairo and Starknet fundamentals, while later chapters explore advanced topics and complex smart contract patterns. ## How to use Starknet By Example? Each chapter of Starknet By Exampleis self-contained and focuses on a specific Starknet feature or smart contract use case. While you can jump to any topic, we recommend following the chapters in order if you're new to Starknet. You can try out the examples instantly in the [Cairo Playground](https://www.cairo-lang.org/cairovm/). # Anonymous DeFi and open notes Source: https://docs.starknet.io/build/starknet-privacy/anonymous-defi Anonymizing contracts, Invoke, and open-note fills for swaps and lending Standard AMMs and lending vaults expose **amounts** through reserves, share mint/burn, and transfers. Starknet Privacy still lets you route value **through** those protocols while targeting **anonymity** (who is interacting, how notes chain in the pool)—not full **amount** hiding on the leg that must be filled on-chain after the fact. **Open notes** carry that tradeoff by design; see [Notes and nullifiers — Open notes](/build/starknet-privacy/notes-and-nullifiers#open-notes). The paper is authoritative for semantics: [IACR 2026/474](https://eprint.iacr.org/2026/474.pdf) §10. ## End-to-end pattern (swap or analogous DeFi) 1. **Spend** the source-token notes you are using. 2. **Create** an **open note** for the **output** token (the amount is not fixed in ciphertext until the external step completes). 3. **Withdraw** from the pool into a **helper** contract address (so the helper holds the input tokens for the next step). 4. **Invoke** the helper from the pool: the helper talks to the external protocol (AMM, lending vault, …), then returns instructions for the pool to **credit** the open note with the measured output. Steps 3–4 are why you need a small, auditable **adapter** contract: the core pool stays generic; the helper encodes “how to call Vesu / an AMM / …” and how to turn the **actual** token delta into an **open-note deposit**. ## What an anonymizing contract is responsible for In this model the **privacy pool** remains the authority that verifies proofs and updates note state. The **helper** is a separate contract that: * **Receives** tokens the pool withdrew for this leg (the pool is the orchestrator; the proof authorizes the overall flow). * **Performs** one or more calls into external DeFi (approve, deposit, swap, withdraw, …) according to that protocol’s interfaces. * **Measures** the **output** amount in a robust way (often a **balance delta** on the output token before vs after the operation), so the correct quantity is known **on-chain** even when it could not be fixed inside the ZK proof. * **Approves** the **privacy pool** to pull the output tokens it received, so the pool can complete the accounting and **fill** the open note. * **Returns** a structured description of **which open note** gets **which token** and **how much**—in the reference Cairo this is expressed as deposits such as `OpenNoteDeposit { note_id, token, amount }` for the pool to apply. Helpers are meant to be **small and reviewable**: they should not hold user funds long-term; they execute a single orchestrated step when invoked by the pool. ## Example reference shape: Vesu lending helper A **Vesu lending helper** is deployed on mainnet as a reference invoke helper. It illustrates the same **open-note + Invoke** pattern as a swap helper, but the external calls are **`deposit`** / **`withdraw`** on Vesu vToken contracts instead of a swap router. The anonymizing contract source is readable on [Voyager](https://voyager.online/contract/0x028b49bc7a48b92d06d436d90e889729d7161dfc2fef3f16b674029bf7abc336). For Vesu's own vToken interface, see [vToken deposit & withdraw](https://docs.vesu.xyz/developers/core/vtoken#deposit--withdraw). ### What the Vesu helper does To enable users to anonymously use Vesu directly from the privacy pool, the helper: 1. **Receives tokens** from the pool (e.g. USDC you want to lend). 2. **Deposits them into Vesu** and receives vault shares (vTokens) in return — or the reverse for a withdrawal. 3. **Measures how many output tokens** it actually received (a balance check before and after the Vesu call). 4. **Approves the pool** to pull those output tokens and **tells it which open note to credit** with the result. The helper is needed because the output amount is only known after the Vesu call executes on-chain — it cannot be fixed inside the ZK proof ah
프로젝트로 돌아가기