Starknet 백서

Starknet

원문

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

ontract instance is a deployed contract corresponding to a class. You can upgrade a deployed contract to a newer version by calling the `replace_class_syscall` function. By using this function, you can update the class hash associated with a deployed contract, effectively upgrading its implementation. However, this will not modify the contract's storage, so all the data stored in the contract will remain the same. To illustrate this concept, let's consider an example with two contracts: `UpgradeableContract_V0`, and `UpgradeableContract_V1`. Start by deploying `UpgradeableContract_V0` as the initial version. Next, send a transaction that invokes the `upgrade` function, with the class hash of `UpgradeableContract_V1` as parameter to upgrade the class hash of the deployed contract to the `UpgradeableContract_V1` one. Then, call the `version` method on the contract to see that the contract was upgraded to the V1 version. ```rust theme={null} use starknet::class_hash::ClassHash; #[starknet::interface] pub trait IUpgradeableContract<TContractState> { fn upgrade(ref self: TContractState, impl_hash: ClassHash); fn version(self: @TContractState) -> u8; } #[starknet::contract] pub mod UpgradeableContract_V0 { use starknet::class_hash::ClassHash; use core::num::traits::Zero; #[storage] struct Storage {} #[event] #[derive(Copy, Drop, Debug, PartialEq, starknet::Event)] pub enum Event { Upgraded: Upgraded, } #[derive(Copy, Drop, Debug, PartialEq, starknet::Event)] pub struct Upgraded { pub implementation: ClassHash, } #[abi(embed_v0)] impl UpgradeableContract of super::IUpgradeableContract<ContractState> { fn upgrade(ref self: ContractState, impl_hash: ClassHash) { assert(impl_hash.is_non_zero(), "Class hash cannot be zero"); starknet::syscalls::replace_class_syscall(impl_hash).unwrap(); self.emit(Event::Upgraded(Upgraded { implementation: impl_hash })) } fn version(self: @ContractState) -> u8 { 0 } } } ``` ```rust theme={null} use starknet::class_hash::ClassHash; #[starknet::interface] pub trait IUpgradeableContract<TContractState> { fn upgrade(ref self: TContractState, impl_hash: ClassHash); fn version(self: @TContractState) -> u8; } #[starknet::contract] pub mod UpgradeableContract_V1 { use starknet::class_hash::ClassHash; use core::num::traits::Zero; #[storage] struct Storage {} #[event] #[derive(Drop, starknet::Event)] enum Event { Upgraded: Upgraded, } #[derive(Drop, starknet::Event)] struct Upgraded { implementation: ClassHash, } #[abi(embed_v0)] impl UpgradeableContract of super::IUpgradeableContract<ContractState> { fn upgrade(ref self: ContractState, impl_hash: ClassHash) { assert(impl_hash.is_non_zero(), "Class hash cannot be zero"); starknet::syscalls::replace_class_syscall(impl_hash).unwrap(); self.emit(Event::Upgraded(Upgraded { implementation: impl_hash })) } fn version(self: @ContractState) -> u8 { 1 } } } ``` # Calling other contracts Source: https://docs.starknet.io/build/starknet-by-example/basic/calling-other-contracts In Starknet, contracts can interact with each other through contract calls. The recommended way to make these calls is using the dispatcher pattern, which provides type safety and better error handling. ## Understanding Dispatchers A dispatcher is an automatically generated struct that handles the serialization and deserialization of contract calls. To use dispatchers: 1. Define the target contract's interface as a trait with `#[starknet::interface]` (`IContract`) 2. Import the generated dispatcher types (`IContractDispatcher` and `IContractDispatcherTrait`) 3. Create a dispatcher instance with the target contract's address Let's look at a practical example where one contract (`Caller`) interacts with another (`Callee`). The `Callee` contract stores a value that can be set and retrieved: ```rust theme={null} #[starknet::interface] trait ICallee<TContractState> { fn set_value(ref self: TContractState, value: u128); fn get_value(self: @TContractState) -> u128; } #[starknet::contract] mod Callee { use starknet::storage::{StoragePointerReadAccess, StoragePointerWriteAccess}; #[storage] struct Storage { value: u128, } #[abi(embed_v0)] impl Callee of super::ICallee<ContractState> { fn set_value(ref self: ContractState, value: u128) { self.value.write(value); } fn get_value(self: @ContractState) -> u128 { self.value.read() } } } ``` The `Caller` contract demonstrates how to use the dispatcher to interact with `Callee`: ```rust theme={null} #[starknet::interface] trait ICaller<TContractState> { fn call_callee_set_value(ref self: TContractState, callee_address: ContractAddress, value: u128); fn call_callee_get_value(self: @TContractState, callee_address: ContractAddress) -> u128; } #[starknet::contract] mod Caller { use starknet::storage::StoragePointerReadAccess; use super::ICaller; #[storage] struct Storage {} #[abi(embed_v0)] impl Caller of super::ICaller<ContractState> { fn call_callee_set_value(ref self: ContractState, callee_address: ContractAddress, value: u128) { // Create a dispatcher for the callee contract let callee_dispatcher = ICalleeDispatcher { contract_address: callee_address }; // Call the callee contract's set_value function callee_dispatcher.set_value(value); } fn call_callee_get_value(self: @ContractState, callee_address: ContractAddress) -> u128 { // Create a dispatcher for the callee contract let callee_dispatcher = ICalleeDispatcher { contract_address: callee_address }; // Call the callee contract's get_value function callee_dispatcher.get_value() } } } ``` ### Key Points: * The `#[starknet::interface]` attribute automatically generates the dispatcher types * Dispatchers handle all the low-level details of contract interaction * Contract calls are type-safe and checked at compile time * Each contract maintains its own storage and state For more details about dispatchers, check out the [Cairo Book](https://book.cairo-lang.org/ch102-02-interacting-with-another-contract.html). <Note> While you can use the low-level `call_contract_syscall` directly, it's not recommended as it: * Requires manual serialization/deserialization * Lacks compile-time type checking * Is more easy to make mistakes </Note> # Component contract storage collisions Source: https://docs.starknet.io/build/starknet-by-example/basic/components/collisions Components can declare their own storage variables. When a contract uses a component, the component storage is merged with the contract storage. The storage layout is only determined by the variables names, so variables with the same name will collide. <Note> In a future release, the `#[substorage(v1)]` will determine the storage layout based on the component as well, so collisions will be avoided. </Note> A good practice is to prefix the component storage variables with the component name, as shown in the [Switchable component example](./intro). #### Example Here's an example of a collision on the `switchable_value` storage variable of the `Switchable` component. Interface: ```rust theme={null} #[starknet::interface] pub trait ISwitchCollision<TContractState> { fn set(ref self: TContractState, value: bool); fn get(ref self: TContractState) -> bool; } ``` Here's the storage of the contract: ```rust theme={null} #[storage] #[allow(starknet::colliding_storage_paths)] struct Storage { switchable_value: bool, #[substorage(v0)] switch: switchable_component::Storage, } ``` Both the contract and the component have a `switchable_value` storage variable, so they collide: ```rust theme={null} #[test] fn test_collision() { let (mut contract, mut contract_iswitch) = deploy(); assert_eq!(contract.get(), false); assert_eq!(contract_iswitch.is_on(), false); contract_iswitch.switch(); assert_eq!(contract_iswitch.is_on(), true); assert_eq!(contract.get(), true); // `collision` between component storage 'value' and contract storage 'value' assert_eq!(contract.get(), contract_iswitch.is_on()); contract.set(false); assert_eq!(contract.get(), contract_iswitch.is_on()); } ``` # Component dependencies Source: https://docs.starknet.io/build/starknet-by-example/basic/components/dependencies A component with a dependency on a trait `T` can be used in a contract as long as the contract implements the trait `T`. We will use a new `Countable` component as an example: ```rust theme={null} #[starknet::interface] pub trait ICountable<TContractState> { fn get(self: @TContractState) -> u32; fn increment(ref self: TContractState); } #[starknet::component] pub mod countable_component { use starknet::storage::{StoragePointerReadAccess, StoragePointerWriteAccess}; #[storage] pub struct Storage { countable_value: u32, } #[embeddable_as(Countable)] impl CountableImpl< TContractState, +HasComponent<TContractState>, > of super::ICountable<ComponentState<TContractState>> { fn get(self: @ComponentState<TContractState>) -> u32 { self.countable_value.read() } fn increment(ref self: ComponentState<TContractState>) { self.countable_value.write(self.countable_value.read() + 1); } } } ``` We want to add a way to enable or disable the counter, in a way that calling `increment` on a disabled counter will not increment it. But we don't want to add this switch logic to the `Countable` component itself. Instead, we add the trait `Switchable` as a dependency to the `Countable` component. #### Implementation of the trait in the contract First, we import the `ISwitchable` trait defined in chapter ["Components How-To"](./intro): ```rust theme={null} #[starknet::interface] pub trait ISwitchable<TContractState> { fn is_on(self: @TContractState) -> bool; fn switch(ref self: TContractState); } ``` Then we can modify the implementation of the `Countable` component to depend on the `ISwitchable` trait: ```rust theme={null} #[starknet::component] pub mod countable_component { use starknet::storage::{StoragePointerReadAccess, StoragePointerWriteAccess}; use components::countable::ICountable; use components::switchable::ISwitchable; #[storage] pub struct Storage { countable_value: u32, } #[embeddable_as(Countable)] impl CountableImpl< TContractState, +HasComponent<TContractState>, +ISwitchable<TContractState>, > of ICountable<ComponentState<TContractState>> { fn get(self: @ComponentState<TContractState>) -> u32 { self.countable_value.read() } fn increment(ref self: ComponentState<TContractState>) { if (self.get_contract().is_on()) { self.countable_value.write(self.countable_value.read() + 1); } } } } ``` A contract that uses the `Countable` component must implement the `ISwitchable` trait: ```rust theme={null} #[starknet::contract] mod MockContract { use super::countable_component; use components::switchable::ISwitchable; component!(path: countable_component, storage: counter, event: CountableEvent); #[storage] struct Storage { #[substorage(v0)] counter: countable_component::Storage, switch: bool, } #[event] #[derive(Drop, starknet::Event)] enum Event { CountableEvent: countable_component::Event, } #[abi(embed_v0)] impl CountableImpl = countable_component::Countable<ContractState>; #[abi(embed_v0)] impl Switchable of ISwitchable<ContractState> { fn switch(ref self: ContractState) {} fn is_on(self: @ContractState) -> bool { true } } } ``` #### Implementation of the trait in another component In the previous example, we implemented the `ISwitchable` trait in the contract. We already implemented a [`Switchable`](./intro) component that provides an implementation of the `ISwitchable` trait. By using the `Switchable` component in a contract, we can embed the implementation of the `ISwitchable` trait in the contract and resolve the dependency on the `ISwitchable` trait. ```rust theme={null} #[starknet::contract] mod CountableContract { use super::countable_component; use components::switchable::switchable_component; component!(path: countable_component, storage: counter, event: CountableEvent); component!(path: switchable_component, storage: switch, event: SwitchableEvent); #[storage] struct Storage { #[substorage(v0)] counter: countable_component::Storage, #[substorage(v0)] switch: switchable_component::Storage, } #[event] #[derive(Drop, starknet::Event)] enum Event { CountableEvent: countable_component::Event, SwitchableEvent: switchable_component::Event, } #[abi(embed_v0)] impl CountableImpl = countable_component::Countable<ContractState>; #[abi(embed_v0)] impl SwitchableImpl = switchable_component::Switchable<ContractState>; } ``` #### Dependency on other component's internal functions The previous example shows how to use the `ISwitchable` trait implementation from the `Switchable` component inside the `Countable` component by embedding the implementation in the contract. However, suppose we would like to turn off the switch after each increment. There's no `set` function in the `ISwitchable` trait, so we can't do it directly. But the `Switchable` component implements the internal function `_off` from the `SwitchableInternalTrait` that set the switch to `false`. We can't embed `SwitchableInternalImpl`, but we can add `switchable::HasComponent<TContractState>` as a dependency inside `CountableImpl`. We make the `Countable` component depend on the `Switchable` component. This will allow to do `switchable::ComponentState<TContractState>` -> `TContractState` -> `countable::ComponentState<TcontractState>` and access the internal functions of the `Switchable` component inside the `Countable` component: ```rust theme={null} #[starknet::contract] mod CountableContract { use super::countable_component; use components::switchable::switchable_component; component!(path: countable_component, storage: counter, event: CountableEvent); component!(path: switchable_component, storage: switch, event: SwitchableEvent); #[storage] struct Storage { #[substorage(v0)] counter: countable_component::Storage, #[substorage(v0)] switch: switchable_component::Storage, } #[event] #[derive(Drop, starknet::Event)] enum Event { CountableEvent: countable_component::Event, SwitchableEvent: switchable_component::Event, } #[abi(embed_v0)] impl CountableImpl = countable_component::Countable<ContractState>; #[abi(embed_v0)] impl SwitchableImpl = switchable_component::Switchable<ContractState>; impl SwitchableInternalImpl = switchable_component::SwitchableInternalImpl<ContractState>; } ``` The `CountableContract` contract remains the same as in the previous example, only the implementation of the `Countable` component is different. # Introduction to components Source: https://docs.starknet.io/build/starknet-by-example/basic/components/intro Components are like modular addons that can be snapped into contracts to add reusable logic, storage, and events. They are used to separate the core logic from common functionalities, simplifying the contract's code and making it easier to read and maintain. It also reduces the risk of bugs and vulnerabilities by using well-tested components. Key characteristics: * Modularity: Easily pluggable into multiple contracts. * Reusable Logic: Encapsulates specific functionalities. * Not Standalone: Cannot be declared or deployed independently. ## How to create a component The following example shows a simple `Switchable` component that can be used to add a switch that can be either on or off. It contains a storage variable `switchable_value`, a function `switch` and an event `Switch`. <Note> It is a good practice to prefix the component storage variables with the component name to [avoid collisions](./collisions). </Note> ```rust theme={null} #[starknet::interface] pub trait ISwitchable<TContractState> { fn is_on(self: @TContractState) -> bool; fn switch(ref self: TContractState); } #[starknet::component] pub mod switchable_component { use starknet::storage::{StoragePointerReadAccess, StoragePointerWriteAccess}; #[storage] pub struct Storage { switchable_value: bool, } #[derive(Drop, Debug, PartialEq, starknet::Event)] pub struct SwitchEvent {} #[event] #[derive(Drop, Debug, PartialEq, starknet::Event)] pub enum Event { SwitchEvent: SwitchEvent, } #[embeddable_as(Switchable)] impl SwitchableImpl< TContractState, +HasComponent<TContractState>, > of super::ISwitchable<ComponentState<TContractState>> { fn is_on(self: @ComponentState<TContractState>) -> bool { self.switchable_value.read() } fn switch(ref self: ComponentState<TContractState>) { self.switchable_value.write(!self.switchable_value.read()); self.emit(Event::SwitchEvent(SwitchEvent {})); } } #[generate_trait] pub impl SwitchableInternalImpl< TContractState, +HasComponent<TContractState>, > of SwitchableInternalTrait<TContractState> { fn _off(ref self: ComponentState<TContractState>) { self.switchable_value.write(false); } } } ``` A component is really similar to a contract and can also have: * An interface defining entrypoints (`ISwitchableComponent<TContractState>`) * A Storage struct * Events * Internal functions It doesn't have a constructor, but you can create an `_init` internal function and call it from the contract's constructor. In the previous example, the `_off` function will be used this way. <Note> It's currently not possible to use the same component multiple times in the same contract. This is a known limitation that may be lifted in the future. For now, you can view components as implementations of specific interfaces or features (`Ownable`, `Upgradeable`, ... \~`able`). This is why we called the component in the above example `Switchable`, and not `Switch`; the contract *is switchable*, it does not *have a switch*. </Note> ## How to use a component Now that we have a component, we can use it in a contract. The following contract incorporates the `Switchable` component: ```rust theme={null} #[starknet::contract] pub mod SwitchContract { use super::switchable_component; component!(path: switchable_component, storage: switch, event: SwitchableEvent); #[abi(embed_v0)] impl SwitchableImpl = switchable_component::Switchable<ContractState>; #[storage] struct Storage { #[substorage(v0)] switch: switchable_component::Storage, } #[event] #[derive(Drop, Debug, PartialEq, starknet::Event)] pub enum Event { SwitchableEvent: switchable_component::Event, } // You can optionally use the internal implementation of the component as well impl SwitchableInternalImpl = switchable_component::SwitchableInternalImpl<ContractState>; #[constructor] fn constructor(ref self: ContractState) { // Internal function call self.switch._off(); } } ``` ## How to test a component In order to effectively test a component, you need to test it in the context of a contract. A common practice is to declare a `Mock` contract that has the only purpose of testing the component. To test the `Switchable` component, we can use the previous `SwitchableContract`: ```rust theme={null} #[cfg(test)] mod test { use super::{ISwitchableDispatcher, ISwitchableDispatcherTrait}; use snforge_std::{ ContractClassTrait, DeclareResultTrait, declare, spy_events, EventSpyAssertionsTrait, }; use super::SwitchContract; // Used as a mock contract use super::switchable_component; fn deploy() -> ISwitchableDispatcher { let contract = declare("SwitchContract").unwrap().contract_class(); let (contract_address, _) = contract.deploy(@array![]).unwrap(); ISwitchableDispatcher { contract_address } } #[test] fn test_constructor() { let switchable = deploy(); assert_eq!(switchable.is_on(), false); } #[test] fn test_switch() { let switchable = deploy(); let mut spy = spy_events(); switchable.switch(); assert_eq!(switchable.is_on(), true); spy .assert_emitted( @array![ ( switchable.contract_address, SwitchContract::Event::SwitchableEvent( switchable_component::Event::SwitchEvent( switchable_component::SwitchEve
프로젝트로 돌아가기