bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 73쪽 중 26쪽
nt {},
),
),
),
],
);
}
#[test]
fn test_multiple_switches() {
let switchable = deploy();
switchable.switch();
assert_eq!(switchable.is_on(), true);
switchable.switch();
assert_eq!(switchable.is_on(), false);
switchable.switch();
assert_eq!(switchable.is_on(), true);
}
}
```
## Deep dive into components
You can find more in-depth information about components in [The Cairo book - Components](https://book.cairo-lang.org/ch16-02-00-composability-and-components.html).
# The Ownable component
Source: https://docs.starknet.io/build/starknet-by-example/basic/components/ownable
The following `Ownable` component is a simple component that allows the contract to set an owner and provides an `_assert_is_owner` function that can be used to ensure that the caller is the owner.
It can also be used to renounce ownership of a contract, meaning that no one will be able to satisfy the `_assert_is_owner` function.
```rust theme={null}
use starknet::ContractAddress;
#[starknet::interface]
pub trait IOwnable<TContractState> {
fn owner(self: @TContractState) -> ContractAddress;
fn transfer_ownership(ref self: TContractState, new: ContractAddress);
fn renounce_ownership(ref self: TContractState);
}
pub mod Errors {
pub const UNAUTHORIZED: felt252 = "Not owner";
pub const ZERO_ADDRESS_OWNER: felt252 = "Owner cannot be zero";
pub const ZERO_ADDRESS_CALLER: felt252 = "Caller cannot be zero";
}
#[starknet::component]
pub mod ownable_component {
use super::Errors;
use starknet::{ContractAddress, get_caller_address};
use core::num::traits::Zero;
use starknet::storage::{StoragePointerReadAccess, StoragePointerWriteAccess};
#[storage]
pub struct Storage {
ownable_owner: ContractAddress,
}
#[derive(Drop, Debug, PartialEq, starknet::Event)]
pub struct OwnershipTransferredEvent {
pub previous: ContractAddress,
pub new: ContractAddress,
}
#[derive(Drop, Debug, PartialEq, starknet::Event)]
pub struct OwnershipRenouncedEvent {
pub previous: ContractAddress,
}
#[event]
#[derive(Drop, Debug, PartialEq, starknet::Event)]
pub enum Event {
OwnershipTransferredEvent: OwnershipTransferredEvent,
OwnershipRenouncedEvent: OwnershipRenouncedEvent,
}
#[embeddable_as(Ownable)]
pub impl OwnableImpl<
TContractState, +HasComponent<TContractState>,
> of super::IOwnable<ComponentState<TContractState>> {
fn owner(self: @ComponentState<TContractState>) -> ContractAddress {
self.ownable_owner.read()
}
fn transfer_ownership(ref self: ComponentState<TContractState>, new: ContractAddress) {
self._assert_only_owner();
self._transfer_ownership(new);
}
fn renounce_ownership(ref self: ComponentState<TContractState>) {
self._assert_only_owner();
self._renounce_ownership();
}
}
#[generate_trait]
pub impl OwnableInternalImpl<
TContractState, +HasComponent<TContractState>,
> of OwnableInternalTrait<TContractState> {
fn _assert_only_owner(self: @ComponentState<TContractState>) {
let caller = get_caller_address();
assert(caller.is_non_zero(), Errors::ZERO_ADDRESS_CALLER);
assert(caller == self.ownable_owner.read(), Errors::UNAUTHORIZED);
}
fn _init(ref self: ComponentState<TContractState>, owner: ContractAddress) {
assert(owner.is_non_zero(), Errors::ZERO_ADDRESS_OWNER);
self.ownable_owner.write(owner);
}
fn _transfer_ownership(ref self: ComponentState<TContractState>, new: ContractAddress) {
assert(new.is_non_zero(), Errors::ZERO_ADDRESS_OWNER);
let previous = self.ownable_owner.read();
self.ownable_owner.write(new);
self
.emit(
Event::OwnershipTransferredEvent(OwnershipTransferredEvent { previous, new }),
);
}
fn _renounce_ownership(ref self: ComponentState<TContractState>) {
let previous = self.ownable_owner.read();
self.ownable_owner.write(Zero::zero());
self.emit(Event::OwnershipRenouncedEvent(OwnershipRenouncedEvent { previous }));
}
}
}
```
A mock contract that uses the `Ownable` component:
```rust theme={null}
#[starknet::contract]
pub mod OwnedContract {
use super::{ownable_component, ownable_component::OwnableInternalTrait};
component!(path: ownable_component, storage: ownable, event: OwnableEvent);
#[abi(embed_v0)]
impl OwnableImpl = ownable_component::Ownable<ContractState>;
#[storage]
struct Storage {
#[substorage(v0)]
ownable: ownable_component::Storage,
}
#[constructor]
fn constructor(ref self: ContractState) {
self.ownable._init(starknet::get_caller_address());
}
#[event]
#[derive(Drop, Debug, PartialEq, starknet::Event)]
pub enum Event {
OwnableEvent: ownable_component::Event,
}
}
```
# Constructor
Source: https://docs.starknet.io/build/starknet-by-example/basic/constructor
A constructor is a special function that initializes a contract's state during deployment. It has several key characteristics:
* Runs exactly once when the contract is deployed
* Must be annotated with `#[constructor]`
* Up to one constructor per contract
* Function is conventionally named `constructor`
Here's an example that shows how to initialize storage variables during contract deployment:
```rust theme={null}
#[starknet::interface]
trait IConstructorExample<TContractState> {
fn get_a(self: @TContractState) -> u128;
fn get_b(self: @TContractState) -> u8;
fn get_c(self: @TContractState) -> u256;
}
#[starknet::contract]
mod ConstructorExample {
use starknet::storage::{StoragePointerReadAccess, StoragePointerWriteAccess};
#[storage]
struct Storage {
a: u128,
b: u8,
c: u256,
}
#[constructor]
fn constructor(ref self: ContractState, a: u128, b: u8, c: u256) {
// Initialize storage variables with constructor parameters
self.a.write(a);
self.b.write(b);
self.c.write(c);
}
#[abi(embed_v0)]
impl ConstructorExample of super::IConstructorExample<ContractState> {
fn get_a(self: @ContractState) -> u128 {
self.a.read()
}
fn get_b(self: @ContractState) -> u8 {
self.b.read()
}
fn get_c(self: @ContractState) -> u256 {
self.c.read()
}
}
}
```
In this example:
* The constructor takes three parameters: `a`, `b`, and `c`
* Each parameter corresponds to a storage variable of the same name, but you can specify any argument variable name
* The values are written to storage using the `write()` method. You need to import the `StoragePointerWriteAccess` trait to be able to write to a specific storage pointer
<Tip>
Constructors are ideal for:
* Setting initial contract state
* Storing deployment-time parameters
* Initializing access control (e.g., setting an owner)
</Tip>
<Warning>
**Constructor values cannot be changed after deployment unless you specifically implement functions to modify them.**
</Warning>
# Simple counter
Source: https://docs.starknet.io/build/starknet-by-example/basic/counter
We now understand how to create a contract with state variables and functions. Let's create a simple counter contract that increments and decrements a counter.
Here's how it works:
* The contract has a state variable `counter` that is initialized to `0`.
* When a user calls the `increment` entrypoint, the contract increments `counter` by `1`.
* When a user calls the `decrement`, the contract decrements `counter` by `1`.
```rust theme={null}
#[starknet::interface]
trait ISimpleCounter<TContractState> {
fn get_current_count(self: @TContractState) -> u128;
fn increment(ref self: TContractState);
fn decrement(ref self: TContractState);
}
#[starknet::contract]
mod SimpleCounter {
use starknet::storage::{StoragePointerReadAccess, StoragePointerWriteAccess};
#[storage]
struct Storage {
// Counter variable
counter: u128,
}
#[constructor]
fn constructor(ref self: ContractState, init_value: u128) {
// Store initial value
self.counter.write(init_value);
}
#[abi(embed_v0)]
impl SimpleCounter of super::ISimpleCounter<ContractState> {
fn get_current_count(self: @ContractState) -> u128 {
return self.counter.read();
}
fn increment(ref self: ContractState) {
// Store counter value + 1
let counter = self.counter.read() + 1;
self.counter.write(counter);
}
fn decrement(ref self: ContractState) {
// Store counter value - 1
let counter = self.counter.read() - 1;
self.counter.write(counter);
}
}
}
```
# Custom types in entrypoints
Source: https://docs.starknet.io/build/starknet-by-example/basic/custom-types-in-entrypoints
When using custom types in Starknet contract entrypoints, you need to handle serialization and deserialization of data. This is because:
1. Input parameters are sent to entrypoints as arrays of `felt252`
2. Return values must be converted back to arrays of `felt252`
3. Custom types need to be converted between these formats automatically
## Using the Serde Trait
The `Serde` trait provides the necessary serialization and deserialization capabilities for your custom types. For most simple types, you can derive this trait automatically:
```rust theme={null}
#[derive(Drop, starknet::Serde)]
struct Person {
name: felt252,
age: u8,
is_active: bool,
}
#[starknet::interface]
trait ICustomTypeEntrypoints<TContractState> {
fn set_person(ref self: TContractState, person: Person);
fn get_person(self: @TContractState) -> Person;
}
#[starknet::contract]
mod CustomTypeEntrypoints {
use starknet::storage::{StoragePointerReadAccess, StoragePointerWriteAccess};
#[storage]
struct Storage {
person: Person,
}
#[abi(embed_v0)]
impl CustomTypeEntrypoints of super::ICustomTypeEntrypoints<ContractState> {
fn set_person(ref self: ContractState, person: Person) {
// The Serde trait automatically handles serialization of the Person struct
self.person.write(person);
}
fn get_person(self: @ContractState) -> Person {
// The Serde trait automatically handles deserialization of the Person struct
self.person.read()
}
}
}
```
<Note>
For some complex types, you might need to implement the `Serde` trait manually. This gives you control over how your type is serialized and deserialized.
The `Serde` trait is distinct from the `Store` trait - `Serde` is for passing data in and out of entrypoints, while `Store` is for persisting data in contract storage.
</Note>
# Documentation
Source: https://docs.starknet.io/build/starknet-by-example/basic/documentation
It's important to take the time to document your code. It will help developers and users to understand the contract and its functionalities.
In Cairo, you can add comments with `//`.
### Best Practices
Since Cairo 1, the community has adopted a [Rust-like documentation style](https://doc.rust-lang.org/rust-by-example/meta/doc.html).
### Contract Interface
In smart contracts, you will often have a trait that defines the contract's interface (with `#[starknet::interface]`).
This is the perfect place to include detailed documentation explaining the purpose and functionality of the contract entry points. You can follow this template:
```rust theme={null}
#[starknet::interface]
trait IContract<TContractState> {
/// High-level description of the function
///
/// # Arguments
///
/// * `arg_1` - Description of the argument
/// * `arg_n` - ...
///
/// # Returns
///
/// High-level description of the return value
fn do_something(ref self: TContractState, arg_1: T_arg_1) -> T_return;
}
```
Keep in mind that this should not describe the implementation details of the function, but rather the high-level purpose and functionality of the contract from the perspective of a user.
### Implementation Details
When writing the contract logic, you can add comments to describe the technical implementation details of the functions.
Avoid over-commenting: Comments should provide additional value and clarity.
# Error handling
Source: https://docs.starknet.io/build/starknet-by-example/basic/errors
Cairo provides robust error handling mechanisms for smart contracts. When an error occurs during contract execution, the transaction is immediately reverted and all state changes are undone.
## Basic Error Functions
Cairo offers two main functions for error handling:
### 1. `assert`
* Used for condition validation (similar to Solidity's `require`)
* Stops execution if the condition is false
* Supports two formats:
```rust theme={null}
assert(condition, 'error message'); // Basic assertion
assert!(condition, "formatted error: {}", x); // Formatted string error
```
### 2. `panic`
* Used for immediate execution halt (similar to Solidity's `revert`)
* Best for complex conditions or internal errors
* Supports multiple formats:
```rust theme={null}
panic_with_felt252('error message'); // Basic panic
panic!("formatted error: value={}", value); // Formatted string error
```
<Warning>
While Cairo provides assertion macros like `assert_eq!` and `assert_ne!`, these are **only for testing**. In contract code, always use the standard `assert` function.
</Warning>
## Simple Example
Here's a basic example demonstrating both error handling approaches:
```rust theme={null}
#[starknet::interface]
trait ISimpleErrors<TContractState> {
fn check_positive(self: @TContractState, value: u128) -> bool;
fn set_value(ref self: TContractState, value: u128);
}
#[starknet::contract]
mod SimpleErrors {
use starknet::storage::{StoragePointerReadAccess, StoragePointerWriteAccess};
#[storage]
struct Storage {
value: u128,
}
#[abi(embed_v0)]
impl SimpleErrors of super::ISimpleErrors<ContractState> {
fn check_positive(self: @ContractState, value: u128) -> bool {
// Using assert for validation
assert(value > 0, 'Value must be positive');
true
}
fn set_value(ref self: ContractState, value: u128) {
// Using panic for immediate halt
if value == 0 {
panic_with_felt252('Value cannot be zero');
}
self.value.write(value);
}
}
}
```
## Custom Error Codes
For better organization and consistency, you can define error messages in a dedicated module:
```rust theme={null}
mod Errors {
const INSUFFICIENT_BALANCE: felt252 = "Insufficient balance";
const INVALID_AMOUNT: felt252 = "Invalid amount";
const ACCESS_DENIED: felt252 = "Access denied";
}
#[starknet::interface]
trait ICustomErrors<TContractState> {
fn withdraw(ref self: TContractState, amount: u128);
}
#[starknet::contract]
mod CustomErrors {
use starknet::storage::{StoragePointerReadAccess, StoragePointerWriteAccess};
use super::Errors;
#[storage]
struct Storage {
balance: u128,
}
#[abi(embed_v0)]
impl CustomErrors of super::ICustomErrors<ContractState> {
fn withdraw(ref self: ContractState, amount: u128) {
// Using custom error constants
assert(amount > 0, Errors::INVALID_AMOUNT);
assert(self.balance.read() >= amount, Errors::INSUFFICIENT_BALANCE);
let new_balance = self.balance.read() - amount;
self.balance.write(new_balance);
}
}
}
```
## Real-World Example: Vault Contract
Here's a practical example showing error handling in a vault contract that manages deposits and withdrawals:
```rust theme={null}
mod Errors {
const INSUFFICIENT_BALANCE: felt252 = "Insufficient balance";
const INVALID_AMOUNT: felt252 = "Invalid amount";
const ACCESS_DENIED: felt252 = "Access denied";
}
#[starknet::interface]
trait IVaultErrors<TContractState> {
fn deposit(ref self: TContractState, amount: u128);
fn withdraw(ref self: TContractState, amount: u128);
fn get_balance(self: @TContractState) -> u128;
}
#[starknet::contract]
mod VaultErrors {
use starknet::storage::{StoragePointerReadAccess, StoragePointerWriteAccess};
use super::Errors;
#[storage]
struct Storage {
balance: u128,
owner: ContractAddress,
}
#[constructor]
fn constructor(ref self: ContractState, owner: ContractAddress) {
self.owner.write(owner);
}
#[abi(embed_v0)]
impl VaultErrors of super::IVaultErrors<ContractState> {
fn deposit(ref self: ContractState, amount: u128) {
assert(amount > 0, Errors::INVALID_AMOUNT);
let current_balance = self.balance.read();
self.balance.write(current_balance + amount);
}
fn withdraw(ref self: ContractState, amount: u128) {
assert(amount > 0, Errors::INVALID_AMOUNT);
let current_balance = self.balance.read();
if current_balance < amount {
panic_with_felt252(Errors::INSUFFICIENT_BALANCE);
}
self.balance.write(current_balance - amount);
}
fn get_balance(self: @ContractState) -> u128 {
self.balance.read()
}
}
}
```
In this example:
1. Custom errors are defined in a separate module
2. The `withdraw` function demonstrates both `assert` and `panic` approaches
3. Balance checks protect against underflow conditions
# Events
Source: https://docs.starknet.io/build/starknet-by-example/basic/events
Events in Cairo smart contracts allow you to emit and record data on the Starknet blockchain. They are essential for tracking important state changes and providing transparency to users and other contracts. Events are also useful when building interfaces, to be notified about important state changes.
To use events in your contract:
1. Create event structs that derive the `starknet::Event` trait
2. Define an `Event` enum in the contract, annotated with `#[event]`, where each variant is linked to an event struct
3. Emit events with the `emit` function
You can make events searchable by adding the `#[key]` attribute to specific fields, which indexes them for efficient querying later.
Events variant names and structs are recommended to be named consistently, even if it create some redundancy when emitting events.
Here's a practical example of a contract that emits events when incrementing a counter:
```rust theme={null}
#[starknet::interface]
trait ICounterEvents<TContractState> {
fn increment(ref self: TContractState);
fn get_count(self: @TContractState) -> u128;
}
// Event structs defined outside the contract for better organization
#[derive(Drop, starknet::Event)]
enum CounterEvent {
Incremented: Incremented,
Reset: Reset,
}
#[derive(Drop, starknet::Event)]
struct Incremented {
#[key]
user: ContractAddress,
new_count: u128,
timestamp: u64,
}
#[derive(Drop, starknet::Event)]
struct Reset {
#[key]
user: ContractAddress,
old_count: u128,
timestamp: u64,
}
#[starknet::contract]
mod CounterEvents {
use starknet::storage::{StoragePointerReadAccess, StoragePointerWriteAccess};
use super::{ICounterEvents, CounterEvent, Incremented, Reset};
#[storage]
struct Storage {
count: u128,
}
#[event]
#[derive(Drop, starknet::Event)]
enum Event {
Incremented: Incremented,
Reset: Reset,
}
#[abi(embed_v0)]
impl CounterEvents of super::ICounterEvents<ContractState> {
fn increment(ref self: ContractState) {
let current_count = self.count.read();
let new_count = current_count + 1;
self.count.write(new_count);
// Emit the Incremented event
self.emit(CounterEvent::Incremented(Incremented {
user: starknet::get_caller_address(),
new_count,
timestamp: starknet::get_block_timestamp(),
}));
}
fn get_count(self: @ContractState) -> u128 {
self.count.read()
}
}
// Internal function to reset counter
fn reset_counter(ref self: ContractState) {
let old_count = self.count.read();
self.count.write(0);
// Emit the Reset event
self.emit(CounterEvent::Reset(Reset {
user: starknet::get_caller_address(),
old_count,
timestamp: starknet::get_block_timestamp(),
}));
}
}
```
<Note>
For better code organization, especially in larger contracts, you can define event structs outside of the contract module, as shown in the example here.
While this allows you to group related events in separate modules or files, remember that you must still include all event variants in the contract's `Event` enum.
</Note>
# Mappings
Source: https://docs.starknet.io/build/starknet-by-example/basic/mappings
Maps are a fundamental key-value data structure in Cairo smart contracts that allow you to store and retrieve values using unique keys. The `Map` type in `starknet::storage` is specifically designed for contract storage for this purpose.
Here's a simple example that demonstrates how to use a `Map`:
```rust theme={null}
#[starknet::interface]
trait IMappings<TContractState> {
fn set_value(ref self: TContractState, key: u32, value: u128);
fn get_value(self: @TContractState, key: u3프로젝트로 돌아가기