Starknet 백서

Starknet

원문

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

t the vector's base storage address and is automatically updated when elements are appended. #### Signature ```rust theme={null} fn len(self: T) -> u64 ``` #### Examples ```rust theme={null} use starknet::storage::{Vec, MutableVecTrait}; #[storage] struct Storage { numbers: Vec, } fn is_empty(self: @ContractState) -> bool { self.numbers.len() == 0 } ``` ### 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 #### Signature ```rust theme={null} fn append(self: T) -> StoragePathElementType>> ``` #### Examples ```rust theme={null} use starknet::storage::{Vec, MutableVecTrait, StoragePointerWriteAccess}; #[storage] struct Storage { numbers: Vec, } fn push_number(ref self: ContractState, number: u256) { self.numbers.append().write(number); } ``` ### 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 `push`, which gets an object to write to the vector, `allocate` is specifically useful when you need to prepare space for elements of unknown or dynamic size (e.g., appending another vector). #### Use Case `allocate` 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 Note The `append` function is now deprecated. Use `allocate` to achieve the same functionality with improved clarity and flexibility. #### Examples ```rust theme={null} use starknet::storage::{Vec, MutableVecTrait, StoragePointerWriteAccess}; #[storage] struct Storage { numbers: Vec>, } fn append_nested_vector(ref self: ContractState, elements: Array) { // 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) } } ``` #### Signature ```rust theme={null} fn allocate(self: T) -> StoragePathElementType>> ``` ### 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. #### Note If you need to allocate storage without writing a value (e.g., when appending another vector), consider using `allocate` instead. #### Examples ```rust theme={null} use starknet::storage::{Vec, MutableVecTrait}; #[storage] struct Storage { numbers: Vec, } fn push_number(ref self: ContractState, number: u256) { self.numbers.push(number); } ``` #### Signature ```rust theme={null} fn push, +starknet::Store>( 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. #### Signature ```rust theme={null} fn pop, +starknet::Store>(self: T) -> OptionElementType> ``` #### Examples ```rust theme={null} use starknet::storage::{Vec, MutableVecTrait}; #[storage] struct Storage { numbers: Vec, } fn pop_number(ref self: ContractState) -> Option { self.numbers.pop() } ``` ## Trait types ### ElementType #### Signature ```rust theme={null} type ElementType; ``` # core::starknet::storage::vec::Vec Source: https://docs.starknet.io/build/corelib/core-starknet-storage-vec-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. ## Signature ```rust theme={null} #[phantom] pub struct Vec {} ``` # core::starknet::storage::vec::VecIter Source: https://docs.starknet.io/build/corelib/core-starknet-storage-vec-VecIter An iterator struct over a `Vec` in storage. ## Signature ```rust theme={null} #[derive(Drop)] pub struct VecIter> { vec: T, current_index: IntRange, } ``` # core::starknet::storage::vec::VecTrait Source: https://docs.starknet.io/build/corelib/core-starknet-storage-vec-VecTrait Provides read-only access to elements in a storage [`Vec`](./core-starknet-storage-vec-Vec). This trait enables retrieving elements and checking the vector's length without modifying the underlying storage. ## Signature ```rust theme={null} pub trait VecTrait ``` ## Trait functions ### get Returns a storage path to the element at the specified index, or `None` if out of bounds. #### Signature ```rust theme={null} fn get(self: T, index: u64) -> OptionElementType>> ``` #### Examples ```rust theme={null} use starknet::storage::{Vec, VecTrait, StoragePointerReadAccess}; #[storage] struct Storage { numbers: Vec, } fn maybe_number(self: @ContractState, index: u64) -> Option { self.numbers.get(index).map(|ptr| ptr.read()) } ``` ### at Returns a storage path to access the element at the specified index. #### Panics Panics if the index is out of bounds. #### Examples ```rust theme={null} use starknet::storage::{Vec, VecTrait, StoragePointerReadAccess}; #[storage] struct Storage { numbers: Vec, } fn get_number(self: @ContractState, index: u64) -> u256 { self.numbers.at(index).read() } ``` #### Signature ```rust theme={null} fn at(self: T, index: u64) -> StoragePathElementType> ``` ### 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. #### Signature ```rust theme={null} fn len(self: T) -> u64 ``` #### Examples ```rust theme={null} use starknet::storage::{Vec, VecTrait}; #[storage] struct Storage { numbers: Vec, } fn is_empty(self: @ContractState) -> bool { self.numbers.len() == 0 } ``` ## Trait types ### ElementType #### Signature ```rust theme={null} type ElementType; ``` # core::starknet::storage_access::StorageAddress Source: https://docs.starknet.io/build/corelib/core-starknet-storage_access-StorageAddress Represents the address of a storage value in a Starknet contract. The value range of this type is `[0, 2**251)`. ## Signature ```rust theme={null} pub extern type StorageAddress; ``` # core::starknet::storage_access::StorageBaseAddress Source: https://docs.starknet.io/build/corelib/core-starknet-storage_access-StorageBaseAddress Represents a base storage address that can be combined with offsets. The value range of this type is `[0, 2**251 - 256)`. ## Signature ```rust theme={null} pub extern type StorageBaseAddress; ``` # core::starknet::storage_access::Store Source: https://docs.starknet.io/build/corelib/core-starknet-storage_access-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`](./core-starknet-storage-vec-Vec) or [`Map`](./core-starknet-storage-map-Map). ## Signature ```rust theme={null} pub trait Store ``` ## Derivation To make a type storable in contract storage, simply derive the `Store` trait: ```rust theme={null} #[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`](./core-starknet-storage_access-StorePacking) to optimize storage usage. ## Trait functions ### read Reads a value from storage at the given domain and base address. #### Arguments * `address_domain` - The storage domain (currently only 0 is supported) * `base` - The base storage address to read from #### Signature ```rust theme={null} fn read(address_domain: u32, base: StorageBaseAddress) -> Result> ``` ### write Writes a value to storage at the given domain and base address. #### Arguments * `address_domain` - The storage domain (currently only 0 is supported) * `base` - The base storage address to write to * `value` - The value to store #### Signature ```rust theme={null} fn write( address_domain: u32, base: StorageBaseAddress, value: T, ) -> Result> ``` ### read\_at\_offset Reads a value from storage at a base address plus an offset. #### Arguments * `address_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 #### Signature ```rust theme={null} fn read_at_offset( address_domain: u32, base: StorageBaseAddress, offset: u8, ) -> Result> ``` ### write\_at\_offset Writes a value to storage at a base address plus an offset. #### Arguments * `address_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 #### Signature ```rust theme={null} fn write_at_offset( address_domain: u32, base: StorageBaseAddress, offset: u8, value: T, ) -> Result> ``` ### 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. #### Signature ```rust theme={null} fn size() -> u8 ``` ### scrub Clears the storage area by writing zeroes to it. #### Arguments * `address_domain` - The storage domain * `base` - The base storage address to start clearing * `offset` - The offset from the base address where clearing should start The 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. #### Signature ```rust theme={null} fn scrub( address_domain: u32, base: StorageBaseAddress, offset: u8, ) -> Result> ``` # core::starknet::storage_access::StorePacking Source: https://docs.starknet.io/build/corelib/core-starknet-storage_access-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`. ## Signature ```rust theme={null} pub trait StorePacking ``` # Storage Optimization Each 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 Requirements To implement `StorePacking`, ensure that the `PackedT` type implements [`Store`](./core-starknet-storage_access-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. # Example Packing multiple integer fields into a single storage slot: ```rust theme={null} 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 { 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 its packed form, using a single storage slot instead of 3. When retrieved, it will automatically be unpacked back into the original type. ## Trait functions ### pack Packs a value into its optimized storage representation. #### Signature ```rust theme={null} fn pack(value: T) -> PackedT ``` ### unpack Unpacks a storage representation back into the original type. #### Signature ```rust theme={null} fn unpack(value: PackedT) -> T ``` # core::starknet::storage_access::storage_address_from_base Source: https://docs.starknet.io/build/corelib/core-starknet-storage_access-storage_address_from_base Converts a `StorageBaseAddress` into a `StorageAddress`. This should be used through the high-level `Into` trait. ## Signature ```rust theme={null} pub extern fn storage_address_from_base(base: StorageBaseAddress) -> StorageAddress nopanic; ``` # core::starknet::storage_access::storage_address_from_base_and_offset Source: https://docs.starknet.io/build/corelib/core-starknet-storage_access-storage_address_from_base_and_offset Sums the base address and the offset to return a storage address. ## Signature ```rust theme={null} pub extern fn storage_address_from_base_and_offset(base: StorageBaseAddress, offset: u8) -> StorageAddress nopanic; ``` # core::starknet::storage_access::storage_base_address_const Source: https://docs.starknet.io/build/corelib/core-starknet-storage_access-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. ## Signature ```rust theme={null} pub extern fn storage_base_address_const() -> StorageBaseAddress nopanic; ``` ## Examples ```rust theme={null} use starknet::storage_access::storage_base_address_const; let base_address = storage_base_address_const::(); ``` # core::starknet::storage_access::storage_base_address_from_felt252 Source: https://docs.starknet.io/build/corelib/core-starknet-storage_access-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)`. ## Signature ```rust theme={null} pub extern fn storage_base_address_from_felt252(addr: felt252) -> StorageBaseAddress implicits(RangeCheck) nopanic; ``` # core::starknet::syscalls::call_contract_syscall Source: https://docs.starknet.io/build/corelib/core-starknet-syscalls-call_contract_syscall Calls a given contract. ## Signature ```rust theme={null} pub extern fn call_contract_syscall(address: ContractAddress, entry_point_selector: felt252, calldata: Span) -> Result, Array> implicits(GasBuiltin, System) nopanic; ``` #### Arguments * `address` - The address of the called contract. * `entry_point_selector` - A selector for a function within that contract. * `calldata` - Call arguments. # core::starknet::syscalls::deploy_syscall Source: https://docs.starknet.io/build/corelib/core-starknet-syscalls-deploy_syscall Deploys a new instance of a previously declared class. ## Signature ```rust theme={null} pub extern fn deploy_syscall(class_hash: ClassHash, contract_address_salt: felt252, calldata: Span, deploy_from_zero: bool) -> Result), Array> implicits(GasBuiltin, System) nopanic; ``` #### Arguments * `class_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. #### Returns * The address of the deployed contract. * The serialized return value of the constructor. # core::starknet::syscalls::emit_event_syscall Source: https://docs.starknet.io/build/corelib/core-starknet-syscalls-emit_event_syscall Emits an event. ## Signature ```rust theme={null} pub extern fn emit_event_syscall(keys: Span, data: Span) -> Result> implicits(GasBuiltin, System) nopanic; ``` #### Arguments * `keys` - The keys of the event. * `data` - The data of the event. # core::starknet::syscalls::get_block_hash_syscall Source: https://docs.starknet.io/build/corelib/core-starknet-syscalls-get_block_hash_syscall Returns the hash of the block with the given number. ## Signature ```rust theme={null} pub extern fn get_block_hash_syscall(block_number: u64) -> Result> implicits(GasBuiltin, System) nopanic; ``` #### Arguments * `block_number` - The number of the queried block. #### Returns * The hash of the block with the given number. # core::starknet::syscalls::get_class_hash_at_syscall Source: https://docs.starknet.io/build/corelib/core-starknet-syscalls-get_class_hash_at_syscall Gets the class hash of the contract at the given address. ## Signature ```rust theme={null} pub extern fn get_class_hash_at_syscall(contract_address: ContractAddress) -> Result> implicits(GasBuiltin, System) nopanic; ``` #### Arguments * `contract_address` - The address of the deployed contract. #### Returns * The class hash of the contract's originating code. # core::starknet::syscalls::get_execution_info_syscall Source: https://docs.starknet.io/build/corelib/core-starknet-syscalls-get_execution_info_syscall Gets information about the currently executing block and the transactions within it. For a complete description of this information, see `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. ## Signature ```rust theme={null} pub extern fn get_execution_info_syscall() -> Result, Array> implicits(GasBuiltin, System) nopanic; ``` #### Returns * A struct that contains information about the currently executing function, transaction, and block. # core::starknet::syscalls::get_execution_info_v2_syscall Source: https://docs.starknet.io/build/corelib/core-starknet-syscalls-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`. ## Signature ```rust theme={null} pub extern fn get_execution_info_v2_syscall() -> Result, Array> implicits(GasBuiltin, System) nopanic; ``` #### Returns * A box containing the current V2 execution information. # core::starknet::syscalls::keccak_syscall Source: https://docs.starknet.io/build/corelib/core-starknet-syscalls-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 ## Signature ```rust theme={null} pub extern fn keccak_syscall(input: Span) -> Result> implicits(GasBuiltin, System) nopanic; ``` #### Arguments * `input` - Array of 64-bit words (little endian) to be hashed. #### Returns * The keccak hash as a little-endian u256 # core::starknet::syscalls::library_call_syscall Source: https://docs.starknet.io/build/corelib/co
프로젝트로 돌아가기