Starknet 백서

Starknet

원문

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

le - Vault](https://solidity-by-example.org/defi/vault/). Here's how it works: * When a user deposits a token, the contract calculates the amount of shares to mint. * When a user withdraws, the contract burns their shares, calculates the yield, and withdraws both the yield and the initial amount of tokens deposited. ```rust theme={null} use starknet::ContractAddress; // In order to make contract calls within our Vault, // we need to have the interface of the remote ERC20 contract defined to import the Dispatcher. #[starknet::interface] pub trait IERC20<TContractState> { fn get_name(self: @TContractState) -> felt252; fn get_symbol(self: @TContractState) -> felt252; fn get_decimals(self: @TContractState) -> u8; fn get_total_supply(self: @TContractState) -> felt252; fn balance_of(self: @TContractState, account: ContractAddress) -> felt252; fn allowance( self: @TContractState, owner: ContractAddress, spender: ContractAddress, ) -> felt252; fn transfer(ref self: TContractState, recipient: ContractAddress, amount: felt252); fn transfer_from( ref self: TContractState, sender: ContractAddress, recipient: ContractAddress, amount: felt252, ); fn approve(ref self: TContractState, spender: ContractAddress, amount: felt252); fn increase_allowance(ref self: TContractState, spender: ContractAddress, added_value: felt252); fn decrease_allowance( ref self: TContractState, spender: ContractAddress, subtracted_value: felt252, ); } #[starknet::interface] pub trait ISimpleVault<TContractState> { fn deposit(ref self: TContractState, amount: u256); fn withdraw(ref self: TContractState, shares: u256); fn user_balance_of(self: @TContractState, account: ContractAddress) -> u256; fn contract_total_supply(self: @TContractState) -> u256; } #[starknet::contract] pub mod SimpleVault { use super::{IERC20Dispatcher, IERC20DispatcherTrait}; use starknet::{ContractAddress, get_caller_address, get_contract_address}; use starknet::storage::{ Map, StorageMapReadAccess, StorageMapWriteAccess, StoragePointerReadAccess, StoragePointerWriteAccess, }; #[storage] struct Storage { token: IERC20Dispatcher, total_supply: u256, balance_of: Map<ContractAddress, u256>, } #[constructor] fn constructor(ref self: ContractState, token: ContractAddress) { self.token.write(IERC20Dispatcher { contract_address: token }); } #[generate_trait] impl PrivateFunctions of PrivateFunctionsTrait { fn _mint(ref self: ContractState, to: ContractAddress, shares: u256) { self.total_supply.write(self.total_supply.read() + shares); self.balance_of.write(to, self.balance_of.read(to) + shares); } fn _burn(ref self: ContractState, from: ContractAddress, shares: u256) { self.total_supply.write(self.total_supply.read() - shares); self.balance_of.write(from, self.balance_of.read(from) - shares); } } #[abi(embed_v0)] impl SimpleVault of super::ISimpleVault<ContractState> { fn user_balance_of(self: @ContractState, account: ContractAddress) -> u256 { self.balance_of.read(account) } fn contract_total_supply(self: @ContractState) -> u256 { self.total_supply.read() } fn deposit(ref self: ContractState, amount: u256) { // a = amount // B = balance of token before deposit // T = total supply // s = shares to mint // // (T + s) / T = (a + B) / B // // s = aT / B let caller = get_caller_address(); let this = get_contract_address(); let mut shares = 0; if self.total_supply.read() == 0 { shares = amount; } else { let balance: u256 = self.token.read().balance_of(this).try_into().unwrap(); shares = (amount * self.total_supply.read()) / balance; } PrivateFunctions::_mint(ref self, caller, shares); let amount_felt252: felt252 = amount.low.into(); self.token.read().transfer_from(caller, this, amount_felt252); } fn withdraw(ref self: ContractState, shares: u256) { // a = amount // B = balance of token before withdraw // T = total supply // s = shares to burn // // (T - s) / T = (B - a) / B // // a = sB / T let caller = get_caller_address(); let this = get_contract_address(); let balance = self.user_balance_of(this); let amount = (shares * balance) / self.total_supply.read(); PrivateFunctions::_burn(ref self, caller, shares); let amount_felt252: felt252 = amount.low.into(); self.token.read().transfer(caller, amount_felt252); } } } ``` # Staking Source: https://docs.starknet.io/build/starknet-by-example/applications/staking The following staking contract is designed to allow users to stake tokens in exchange for reward tokens over a specified duration. Here's a quick summary of how it operates and what functionalities it supports: ### Key Features: 1. Token staking and unstaking: * Users can stake an ERC20 token, specified at deployment. * Users can withdraw their staked tokens at any time. 2. Reward calculation and distribution: * The rewards are distributed as an ERC20, also specified at deployment (can be different from the staking token). * Rewards are calculated based on the duration of staking and the amount the user staked relative to the total staked amount by all users. * A user’s reward accumulates over time up until the reward period's end and can be claimed anytime by the user. 3. Dynamic reward rates: * The reward rate is determined by the total amount of reward tokens over a set period (duration). * The reward rate can be adjusted during the rewards period if new rewards are added before the current reward period finishes. * Even after a reward period finishes, a new reward duration and new rewards can be set up if desired. 4. Ownership and administration: * Only the owner of the contract can set the rewards amount and duration. <Note> The reward mechanism ensures that rewards are distributed fairly based on the amount and duration of tokens staked by each user. </Note> The following implementation is the Cairo adaptation of the [Solidity by Example - Staking Rewards contract](https://solidity-by-example.org/defi/staking-rewards/). It includes a small adaptation to keep track of the amount of total distributed reward tokens and emit an event when the remaining reward token amount reaches 0. ```rust theme={null} use starknet::ContractAddress; #[starknet::interface] pub trait IStakingContract<TContractState> { fn set_reward_amount(ref self: TContractState, amount: u256); fn set_reward_duration(ref self: TContractState, duration: u256); fn stake(ref self: TContractState, amount: u256); fn withdraw(ref self: TContractState, amount: u256); fn get_rewards(self: @TContractState, account: ContractAddress) -> u256; fn claim_rewards(ref self: TContractState); } mod Errors { pub const NULL_REWARDS: felt252 = "Reward amount must be > 0"; pub const NOT_ENOUGH_REWARDS: felt252 = "Reward amount must be > balance"; pub const NULL_AMOUNT: felt252 = "Amount must be > 0"; pub const NULL_DURATION: felt252 = "Duration must be > 0"; pub const UNFINISHED_DURATION: felt252 = "Reward duration not finished"; pub const NOT_OWNER: felt252 = "Caller is not the owner"; pub const NOT_ENOUGH_BALANCE: felt252 = "Balance too low"; } #[starknet::contract] pub mod StakingContract { use core::starknet::event::EventEmitter; use core::num::traits::Zero; use starknet::{ContractAddress, get_caller_address, get_block_timestamp, get_contract_address}; use openzeppelin_token::erc20::interface::{IERC20Dispatcher, IERC20DispatcherTrait}; use starknet::storage::{ Map, StorageMapReadAccess, StorageMapWriteAccess, StoragePointerReadAccess, StoragePointerWriteAccess, }; #[storage] struct Storage { pub staking_token: IERC20Dispatcher, pub reward_token: IERC20Dispatcher, pub owner: ContractAddress, pub reward_rate: u256, pub duration: u256, pub current_reward_per_staked_token: u256, pub finish_at: u256, // last time an operation (staking / withdrawal / rewards claimed) was registered pub last_updated_at: u256, pub last_user_reward_per_staked_token: Map::<ContractAddress, u256>, pub unclaimed_rewards: Map::<ContractAddress, u256>, pub total_distributed_rewards: u256, // total amount of staked tokens pub total_supply: u256, // amount of staked tokens per user pub balance_of: Map::<ContractAddress, u256>, } #[event] #[derive(Copy, Drop, Debug, PartialEq, starknet::Event)] pub enum Event { Deposit: Deposit, Withdrawal: Withdrawal, RewardsFinished: RewardsFinished, } #[derive(Copy, Drop, Debug, PartialEq, starknet::Event)] pub struct Deposit { pub user: ContractAddress, pub amount: u256, } #[derive(Copy, Drop, Debug, PartialEq, starknet::Event)] pub struct Withdrawal { pub user: ContractAddress, pub amount: u256, } #[derive(Copy, Drop, Debug, PartialEq, starknet::Event)] pub struct RewardsFinished { pub msg: felt252, } #[constructor] fn constructor( ref self: ContractState, staking_token_address: ContractAddress, reward_token_address: ContractAddress, ) { self.staking_token.write(IERC20Dispatcher { contract_address: staking_token_address }); self.reward_token.write(IERC20Dispatcher { contract_address: reward_token_address }); self.owner.write(get_caller_address()); } #[abi(embed_v0)] impl StakingContract of super::IStakingContract<ContractState> { fn set_reward_duration(ref self: ContractState, duration: u256) { self.only_owner(); assert(duration > 0, super::Errors::NULL_DURATION); // can only set duration if the previous duration has already finished assert( self.finish_at.read() < get_block_timestamp().into(), super::Errors::UNFINISHED_DURATION, ); self.duration.write(duration); } fn set_reward_amount(ref self: ContractState, amount: u256) { self.only_owner(); self.update_rewards(Zero::zero()); assert(amount > 0, super::Errors::NULL_REWARDS); assert(self.duration.read() > 0, super::Errors::NULL_DURATION); let block_timestamp: u256 = get_block_timestamp().into(); let rate = if self.finish_at.read() < block_timestamp { amount / self.duration.read() } else { let remaining_rewards = self.reward_rate.read() * (self.finish_at.read() - block_timestamp); (remaining_rewards + amount) / self.duration.read() }; assert( self.reward_token.read().balance_of(get_contract_address()) >= rate * self.duration.read(), super::Errors::NOT_ENOUGH_REWARDS, ); self.reward_rate.write(rate); // even if the previous reward duration has not finished, we reset the finish_at // variable self.finish_at.write(block_timestamp + self.duration.read()); self.last_updated_at.write(block_timestamp); // reset total distributed rewards self.total_distributed_rewards.write(0); } fn stake(ref self: ContractState, amount: u256) { assert(amount > 0, super::Errors::NULL_AMOUNT); let user = get_caller_address(); self.update_rewards(user); self.balance_of.write(user, self.balance_of.read(user) + amount); self.total_supply.write(self.total_supply.read() + amount); self.staking_token.read().transfer_from(user, get_contract_address(), amount); self.emit(Deposit { user, amount }); } fn withdraw(ref self: ContractState, amount: u256) { assert(amount > 0, super::Errors::NULL_AMOUNT); let user = get_caller_address(); assert( self.staking_token.read().balance_of(user) >= amount, super::Errors::NOT_ENOUGH_BALANCE, ); self.update_rewards(user); self.balance_of.write(user, self.balance_of.read(user) - amount); self.total_supply.write(self.total_supply.read() - amount); self.staking_token.read().transfer(user, amount); self.emit(Withdrawal { user, amount }); } fn get_rewards(self: @ContractState, account: ContractAddress) -> u256 { self.unclaimed_rewards.read(account) + self.compute_new_rewards(account) } fn claim_rewards(ref self: ContractState) { let user = get_caller_address(); self.update_rewards(user); let rewards = self.unclaimed_rewards.read(user); if rewards > 0 { self.unclaimed_rewards.write(user, 0); self.reward_token.read().transfer(user, rewards); } } } #[generate_trait] impl PrivateFunctions of PrivateFunctionsTrait { // call this function every time a user (including owner) performs a state-modifying action fn update_rewards(ref self: ContractState, account: ContractAddress) { self .current_reward_per_staked_token .write(self.compute_current_reward_per_staked_token()); self.last_updated_at.write(self.last_time_applicable()); if account.is_non_zero() { self.distribute_user_rewards(account); self .last_user_reward_per_staked_token .write(account, self.current_reward_per_staked_token.read()); self.send_rewards_finished_event(); } } fn distribute_user_rewards(ref self: ContractState, account: ContractAddress) { // compute earned rewards since last update for the user `account` let user_rewards = self.get_rewards(account); self.unclaimed_rewards.write(account, user_rewards); // track amount of total rewards distributed self .total_distributed_rewards .write(self.total_distributed_rewards.read() + user_rewards); } fn send_rewards_finished_event(ref self: ContractState) { // check whether we should send a RewardsFinished event if self.last_updated_at.read() == self.finish_at.read() { let total_rewards = self.reward_rate.read() * self.duration.read(); if total_rewards != 0 && self.total_distributed_rewards.read() == total_rewards { // owner should set up NEW rewards into the contract self.emit(RewardsFinished { msg: "Rewards all distributed" }); } else { // owner should set up rewards into the contract (or add duration by setting up // rewards) self.emit(RewardsFinished { msg: "Rewards not active yet" }); } } } fn compute_current_reward_per_staked_token(self: @ContractState) -> u256 { if self.total_supply.read() == 0 { self.current_reward_per_staked_token.read() } else { self.current_reward_per_staked_token.read() + self.reward_rate.read() * (self.last_time_applicable() - self.last_updated_at.read()) / self.total_supply.read() } } fn compute_new_rewards(self: @ContractState, account: ContractAddress) -> u256 { self.balance_of.read(account) * (self.current_reward_per_staked_token.read() - self.last_user_reward_per_staked_token.read(account)) } #[inline(always)] fn last_time_applicable(self: @ContractState) -> u256 { Self::min(self.finish_at.read(), get_block_timestamp().into()) } #[inline(always)] fn min(x: u256, y: u256) -> u256 { if (x <= y) { x } else { y } } fn only_owner(self: @ContractState) { let caller = get_caller_address(); assert(caller == self.owner.read(), super::Errors::NOT_OWNER); } } } ``` # TimeLock Source: https://docs.starknet.io/build/starknet-by-example/applications/timelock This is the Cairo adaptation of the [Solidity by example TimeLock](https://solidity-by-example.org/app/time-lock/). ```rust theme={null} use starknet::account::Call; #[starknet::interface] pub trait ITimeLock<TState> { fn get_tx_id(self: @TState, call: Call, timestamp: u64) -> felt252; fn queue(ref self: TState, call: Call, timestamp: u64) -> felt252; fn execute(ref self: TState, call: Call, timestamp: u64) -> Span<felt252>; fn cancel(ref self: TState, tx_id: felt252); } #[starknet::contract] pub mod TimeLock { use core::poseidon::{PoseidonTrait, poseidon_hash_span}; use core::hash::HashStateTrait; use starknet::{get_caller_address, get_block_timestamp, syscalls}; use starknet::account::Call; use components::ownable::ownable_component; use starknet::storage::{Map, StorageMapReadAccess, StorageMapWriteAccess}; component!(path: ownable_component, storage: ownable, event: OwnableEvent); // Ownable #[abi(embed_v0)] impl OwnableImpl = ownable_component::Ownable<ContractState>; impl OwnableInternalImpl = ownable_component::OwnableInternalImpl<ContractState>; #[storage] struct Storage { #[substorage(v0)] ownable: ownable_component::Storage, queued: Map::<felt252, bool>, } #[event] #[derive(Drop, starknet::Event)] pub enum Event { #[flat] OwnableEvent: ownable_component::Event, Queue: Queue, Execute: Execute, Cancel: Cancel, } #[derive(Drop, starknet::Event)] pub struct Queue { #[key] pub tx_id: felt252, pub call: Call, pub timestamp: u64, } #[derive(Drop, starknet::Event)] pub struct Execute { #[key] pub tx_id: felt252, pub call: Call, pub timestamp: u64, } #[derive(Drop, starknet::Event)] pub struct Cancel { #[key] pub tx_id: felt252, } pub const MIN_DELAY: u64 = 10; // seconds pub const MAX_DELAY: u64 = 1000; // seconds pub const GRACE_PERIOD: u64 = 1000; // seconds pub mod Errors { pub const ALREADY_QUEUED: felt252 = "TimeLock: already queued"; pub const TIMESTAMP_NOT_IN_RANGE: felt252 = "TimeLock: timestamp range"; pub const NOT_QUEUED: felt252 = "TimeLock: not queued"; pub const TIMESTAMP_NOT_PASSED: felt252 = "TimeLock: timestamp not passed"; pub const TIMESTAMP_EXPIRED: felt252 = "TimeLock: timestamp expired"; } #[constructor] fn constructor(ref self: ContractState) { self.ownable._init(get_caller_address()); } #[abi(embed_v0)] impl TimeLockImpl of super::ITimeLock<ContractState> { fn get_tx_id(self: @ContractState, call: Call, timestamp: u64) -> felt252 { PoseidonTrait::new() .update(call.to.into()) .update(call.selector.into()) .update(poseidon_hash_span(call.calldata)) .update(timestamp.into()) .finalize() } fn queue(ref self: ContractState, call: Call, timestamp: u64) -> felt252 { self.ownable._assert_only_owner(); let tx_id = self.get_tx_id(self._copy_call(@call), timestamp); assert(!self.queued.read(tx_id), Errors::ALREADY_QUEUED); // ---|------------|---------------|------- // block block + min block + max let block_timestamp = get_block_timestamp(); assert( timestamp >= block_timestamp + MIN_DELAY && timestamp <= block_timestamp + MAX_DELAY, Errors::TIMESTAMP_NOT_IN_RANGE, ); self.queued.write(tx_id, true); self.emit(Queue { tx_id, call: self._copy_call(@call), timestamp }); tx_id } fn execute(ref self: ContractState, call: Call, timestamp: u64) -> Span<felt252> { self.ownable._assert_only_owner(); let tx_id = self.get_tx_id(self._copy_call(@call), timestamp); assert(self.queued.read(tx_id), Errors::NOT_QUEUED); // ----|-------------------|------- // timestamp timestamp + grace period let block_timestamp = get_block_timestamp(); assert(block_timestamp >= timestamp, Errors::TIMESTAMP_NOT_PASSED); assert(block_timestamp <= timestamp + GRACE_PERIOD, Errors::TIMESTAMP_EXPIRED); self.queued.write(tx_id, false); let result = syscalls::call_contract_syscall(call.to, call.selector, call.calldata) .unwrap(); self.emit(Execute { tx_id, call: self._copy_call(@call), timestamp }); result } fn cancel(ref self: ContractState, tx_id: felt252) { self.ownable._assert_only_owner(); assert(self.queued.read(tx_id), Errors::NOT_QUEUED); self.queued.write(tx_id, false); self.emit(Cancel { tx_id }); } } #[generate_trait] impl InternalImpl of InternalTrait { fn _copy_call(self: @ContractState, call: @Call) -> Call { Call { to: *call.to, selector: *call.selector, calldata: *call.calldata } } } } ``` # Upgradeable contract Source: https://docs.starknet.io/build/starknet-by-example/applications/upgradeable-contract In Starknet, contracts are divided into two parts: contract classes and contract instances. This division follows a similar concept used in object-oriented programming languages, where we distinguish between the definition and implementation of objects. A contract class is the definition of a contract: it specifies how the contract behaves. It contains essential information like the Cairo byte code, hint information, entry point names, and everything that defines its semantics unambiguously. To identify different contract classes, Starknet assigns a unique identifier to each class: the class hash. A contract instance is a deployed contract that corresponds to a specific contract class. Think of it as an instance of an object in languages like Java. Each class is identified by its class hash, which is analogous to a class name in an object-oriented programming language. A c
프로젝트로 돌아가기