bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 73쪽 중 22쪽
e(owner, self.balances.read(owner) - 1);
self.owners.write(token_id, Zero::zero());
self.approvals.write(token_id, Zero::zero());
self.emit(Transfer { from: owner, to: Zero::zero(), token_id });
}
fn _require_owned(self: @ContractState, token_id: u256) -> ContractAddress {
let owner = self.owners.read(token_id);
assert(!owner.is_zero(), Errors::INVALID_TOKEN_ID);
owner
}
fn _is_approved_or_owner(
self: @ContractState, owner: ContractAddress, spender: ContractAddress, token_id: u256,
) -> bool {
!spender.is_zero()
&& (owner == spender
|| self.is_approved_for_all(owner, spender)
|| spender == self.get_approved(token_id))
}
fn _check_on_erc721_received(
self: @ContractState,
from: ContractAddress,
to: ContractAddress,
token_id: u256,
data: Span<felt252>,
) -> bool {
let src5_dispatcher = ISRC5Dispatcher { contract_address: to };
if src5_dispatcher.supports_interface(IERC721_RECEIVER_ID) {
IERC721ReceiverDispatcher { contract_address: to }
.on_erc721_received(
get_caller_address(), from, token_id, data,
) == IERC721_RECEIVER_ID
} else {
src5_dispatcher.supports_interface(openzeppelin_account::interface::ISRC6_ID)
}
}
}
}
```
There are other implementations, such as the [Open Zeppelin](https://docs.openzeppelin.com/contracts-cairo/erc721) one.
# Factory pattern
Source: https://docs.starknet.io/build/starknet-by-example/applications/factory
The factory pattern is a well known pattern in object oriented programming. It provides an abstraction on how to instantiate a class.
In the case of smart contracts, we can use this pattern by defining a factory contract that has the sole responsibility of creating and managing other contracts.
## Class hash and contract instance
In Starknet, there's a separation between contract's classes and instances. A contract class serves as a blueprint, defined by the underlying Cairo bytecode, contract's entrypoints, ABI and Sierra program hash. The contract class is identified by a class hash. When you want to add a new class to the network, you first need to declare it.
When deploying a contract, you need to specify the class hash of the contract you want to deploy. Each instance of a contract has their own storage regardless of the class hash.
Using the factory pattern, we can deploy multiple instances of the same contract class and handle upgrades easily.
## Minimal example
Here's a minimal example of a factory contract that deploys the `SimpleCounter` contract:
```rust theme={null}
#[starknet::interface]
trait IFactory<TContractState> {
fn create_counter(ref self: TContractState) -> ContractAddress;
fn create_counter_at(ref self: TContractState, salt: felt252) -> ContractAddress;
fn update_counter_class_hash(ref self: TContractState, new_class_hash: ClassHash);
}
#[starknet::contract]
mod Factory {
use starknet::{
contract_address_const,
class_hash_const,
get_caller_address,
ContractAddress,
ClassHash,
};
#[storage]
struct Storage {
counter_class_hash: ClassHash,
}
#[constructor]
fn constructor(ref self: ContractState, counter_class_hash: ClassHash) {
self.counter_class_hash.write(counter_class_hash);
}
#[abi(embed_v0)]
impl Factory of super::IFactory<ContractState> {
fn create_counter(ref self: ContractState) -> ContractAddress {
let salt = starknet::contract_address_const::<0x123>();
self.create_counter_at(salt)
}
fn create_counter_at(ref self: ContractState, salt: felt252) -> ContractAddress {
let counter_class_hash = self.counter_class_hash.read();
let constructor_calldata = array![];
let (contract_address, _) = starknet::deploy_contract_syscall(
counter_class_hash,
constructor_calldata.span(),
salt,
false,
).unwrap();
contract_address
}
fn update_counter_class_hash(ref self: ContractState, new_class_hash: ClassHash) {
self.counter_class_hash.write(new_class_hash);
}
}
}
```
This factory can be used to deploy multiple instances of the `SimpleCounter` contract by calling the `create_counter` and `create_counter_at` functions.
The `SimpleCounter` class hash is stored inside the factory, and can be upgraded with the `update_counter_class_hash` function which allows to reuse the same factory contract when the `SimpleCounter` contract is upgraded.
<Note>
This minimal example lacks several useful features such as access control, tracking of deployed contracts, events etc.
</Note>
# L1 ↔ L2 token bridge
Source: https://docs.starknet.io/build/starknet-by-example/applications/l1-l2-token-bridge
In Starknet, it is possible to interact with Ethereum by using the L1 ↔ L2 messaging system.
In this example, we will demonstrate the usage of this messaging system to send and receive messages from L1 to L2 for a token bridge.
It will require creating two contracts, one on Starknet and one on Ethereum, that will communicate cross-chain, and notify each other
how many tokens to mint and who to assign them to. We will also create very simple mock token implementations that will simply emit
appropriate events on burning and minting. This will allow us to verify that the cross-chain communication actually succeeded.
First, we create the `TokenBridge` contract on Starknet:
```rust theme={null}
use starknet::{ContractAddress, EthAddress};
/// Represents any time of token that can be minted/burned
/// In a real contract this would probably be an ERC20 contract,
/// but here it's represented as a generic token for simplicity.
#[starknet::interface]
pub trait IMintableToken<TContractState> {
fn mint(ref self: TContractState, account: ContractAddress, amount: u256);
fn burn(ref self: TContractState, account: ContractAddress, amount: u256);
}
#[starknet::interface]
pub trait ITokenBridge<TContractState> {
fn bridge_to_l1(ref self: TContractState, l1_recipient: EthAddress, amount: u256);
fn set_l1_bridge(ref self: TContractState, l1_bridge_address: EthAddress);
fn set_token(ref self: TContractState, l2_token_address: ContractAddress);
fn governor(self: @TContractState) -> ContractAddress;
fn l1_bridge(self: @TContractState) -> felt252;
fn l2_token(self: @TContractState) -> ContractAddress;
}
#[starknet::contract]
pub mod TokenBridge {
use core::num::traits::Zero;
use starknet::{ContractAddress, EthAddress, get_caller_address, syscalls, SyscallResultTrait};
use starknet::storage::{StoragePointerReadAccess, StoragePointerWriteAccess};
use super::{IMintableTokenDispatcher, IMintableTokenDispatcherTrait};
#[storage]
pub struct Storage {
// The address of the L2 governor of this contract. Only the governor can set the other
// storage variables.
pub governor: ContractAddress,
// The L1 bridge address. Zero when unset.
pub l1_bridge: felt252,
// The L2 token contract address. Zero when unset.
pub l2_token: ContractAddress,
}
#[event]
#[derive(Drop, starknet::Event)]
pub enum Event {
WithdrawInitiated: WithdrawInitiated,
DepositHandled: DepositHandled,
L1BridgeSet: L1BridgeSet,
L2TokenSet: L2TokenSet,
}
// An event that is emitted when bridge_to_l1 is called.
// * l1_recipient is the l1 recipient address.
// * amount is the amount to withdraw.
// * caller_address is the address from which the call was made.
#[derive(Drop, starknet::Event)]
pub struct WithdrawInitiated {
pub l1_recipient: EthAddress,
pub amount: u256,
pub caller_address: ContractAddress,
}
// An event that is emitted when handle_deposit is called.
// * account is the recipient address.
// * amount is the amount to deposit.
#[derive(Drop, starknet::Event)]
pub struct DepositHandled {
pub account: ContractAddress,
pub amount: u256,
}
// An event that is emitted when set_l1_bridge is called.
// * l1_bridge_address is the new l1 bridge address.
#[derive(Drop, starknet::Event)]
struct L1BridgeSet {
l1_bridge_address: EthAddress,
}
// An event that is emitted when set_token is called.
// * l2_token_address is the new l2 token address.
#[derive(Drop, starknet::Event)]
struct L2TokenSet {
l2_token_address: ContractAddress,
}
pub mod Errors {
pub const EXPECTED_FROM_BRIDGE_ONLY: felt252 = "Expected from bridge only";
pub const INVALID_ADDRESS: felt252 = "Invalid address";
pub const INVALID_AMOUNT: felt252 = "Invalid amount";
pub const UNAUTHORIZED: felt252 = "Unauthorized";
pub const TOKEN_NOT_SET: felt252 = "Token not set";
pub const L1_BRIDGE_NOT_SET: felt252 = "L1 bridge address not set";
}
#[constructor]
fn constructor(ref self: ContractState, governor: ContractAddress) {
assert(governor.is_non_zero(), Errors::INVALID_ADDRESS);
self.governor.write(governor);
}
#[abi(embed_v0)]
impl TokenBridge of super::ITokenBridge<ContractState> {
/// Initiates a withdrawal of tokens on the L1 contract.
fn bridge_to_l1(ref self: ContractState, l1_recipient: EthAddress, amount: u256) {
assert(l1_recipient.is_non_zero(), Errors::INVALID_ADDRESS);
assert(amount.is_non_zero(), Errors::INVALID_AMOUNT);
self._assert_l1_bridge_set();
self._assert_token_set();
// burn tokens on L2
let caller_address = get_caller_address();
IMintableTokenDispatcher { contract_address: self.l2_token.read() }
.burn(caller_address, amount);
// Send the message to L1 to mint tokens there.
let mut payload: Array<felt252> = array![
l1_recipient.into(), amount.low.into(), amount.high.into(),
];
syscalls::send_message_to_l1_syscall(self.l1_bridge.read(), payload.span())
.unwrap_syscall();
self.emit(WithdrawInitiated { l1_recipient, amount, caller_address });
}
fn set_l1_bridge(ref self: ContractState, l1_bridge_address: EthAddress) {
self._assert_only_governor();
assert(l1_bridge_address.is_non_zero(), Errors::INVALID_ADDRESS);
self.l1_bridge.write(l1_bridge_address.into());
self.emit(L1BridgeSet { l1_bridge_address });
}
fn set_token(ref self: ContractState, l2_token_address: ContractAddress) {
self._assert_only_governor();
assert(l2_token_address.is_non_zero(), Errors::INVALID_ADDRESS);
self.l2_token.write(l2_token_address);
self.emit(L2TokenSet { l2_token_address });
}
// Getters
fn governor(self: @ContractState) -> ContractAddress {
self.governor.read()
}
fn l1_bridge(self: @ContractState) -> felt252 {
self.l1_bridge.read()
}
fn l2_token(self: @ContractState) -> ContractAddress {
self.l2_token.read()
}
}
#[generate_trait]
impl Internal of InternalTrait {
fn _assert_only_governor(self: @ContractState) {
assert(get_caller_address() == self.governor.read(), Errors::UNAUTHORIZED);
}
fn _assert_token_set(self: @ContractState) {
assert(self.l2_token.read().is_non_zero(), Errors::TOKEN_NOT_SET);
}
fn _assert_l1_bridge_set(self: @ContractState) {
assert(self.l1_bridge.read().is_non_zero(), Errors::L1_BRIDGE_NOT_SET);
}
}
#[l1_handler]
pub fn handle_deposit(
ref self: ContractState, from_address: felt252, account: ContractAddress, amount: u256,
) {
assert(from_address == self.l1_bridge.read(), Errors::EXPECTED_FROM_BRIDGE_ONLY);
assert(account.is_non_zero(), Errors::INVALID_ADDRESS);
assert(amount.is_non_zero(), Errors::INVALID_AMOUNT);
self._assert_token_set();
// Call mint on l2_token contract.
IMintableTokenDispatcher { contract_address: self.l2_token.read() }.mint(account, amount);
self.emit(Event::DepositHandled(DepositHandled { account, amount }));
}
}
```
The `IMintableToken` interface represents any mintable/burnable token, and will allow our contract to perform these operations without
regard for the actual token it's working with.
Let's immediately create the mock token implementation that we'll use with the contract:
```rust theme={null}
// [!include ~/listings/applications/l1_l2_token_bridge/src/mintable_token_mock.cairo]
```
Next, we'll implement the mock token on the Ethereum side, which behaves more or less the same as its Starknet counterpart.
Let's just quickly define the interfaces we'll need:
```solidity theme={null}
// [!include ~/listings/applications/l1_l2_token_bridge/solidity/src/IMintableTokenEvents.sol]
```
```solidity theme={null}
// [!include ~/listings/applications/l1_l2_token_bridge/solidity/src/IMintableToken.sol]
```
Now we can create a mock token implementation:
```solidity theme={null}
// [!include ~/listings/applications/l1_l2_token_bridge/solidity/src/MintableTokenMock.sol]
```
Finally, we will implement the `TokenBridge` contract on Ethereum:
```solidity theme={null}
// [!include ~/listings/applications/l1_l2_token_bridge/solidity/src/TokenBridge.sol]
```
> Note: Bridging tokens from Ethereum to Starknet usually takes a couple of minutes, and the `#[l1_handler]` function is automatically
> invoked by the Sequencer, minting tokens to our Starknet wallet address. On the other hand, for bridging transactions to be
> successfully sent from Starknet to Ethereum can take a couple of hours, and will require us to *manually consume the withdrawal* in
> order for the tokens to be sent to our Ethereum wallet address.
# Merkle tree contract
Source: https://docs.starknet.io/build/starknet-by-example/applications/merkle-tree
A Merkle tree, also known as a hash tree, is a data structure used in cryptography and computer science to verify data integrity and consistency. It is a binary tree where each leaf node represents the cryptographic hash of some data (a transaction for example), and each non-leaf node represents the cryptographic hash of its child nodes. This hierarchical structure allows efficient and secure verification of the data integrity.
Here's a quick summary of how it operates and what functionalities it supports:
### How it works:
1. Leaves Creation:
* Some data is hashed to create a leaf node.
2. Intermediate Nodes Creation:
* Pairwise hashes of the leaf nodes are combined and hashed again to create parent nodes.
* This process continues until only one hash remains, known as the Merkle root.
3. Merkle Root:
* The final hash at the top of the tree, representing the entire dataset.
* Changing any single data block will change its corresponding leaf node, which will propagate up the tree, altering the Merkle root.
### Key Features:
1. Efficient Verification:
* Only a small subset of the tree (the Merkle proof) is needed to verify the inclusion of a particular data block, reducing the amount of data that must be processed.
2. Data Integrity:
* The Merkle root ensures the integrity of all the underlying data blocks.
* Any alteration in the data will result in a different root hash.
### Examples of use cases:
1. Fundamental use case: Ethereum blockchain integrity
* Cryptocurrencies like Ethereum use Merkle trees to efficiently verify and maintain transaction integrity within blocks.
* Each transaction in a block is hashed to form leaf nodes, and these hashes are recursively combined to form a single Merkle root, summarizing all transactions.
* The Merkle root is stored in the block header, which is hashed to generate the block's unique identifier.
* <u>Guaranteed Integrity:</u> Any change to a transaction alters the Merkle root, block header, and block hash, making it easy for nodes to detect tampering.
* <u>Transaction verification:</u> Nodes can verify specific transactions via Merkle proofs without downloading the entire block.
2. Whitelist inclusion
* Merkle trees allow efficient whitelist verification without storing the full list on-chain, reducing storage costs.
* The Merkle root of the whitelist is stored on-chain, while the full list remains off-chain.
* To verify if an address is on the whitelist, a user provides a Merkle proof and the address. The Merkle root is recalculated using the provided data and compared to the stored on-chain root. If they match, the address is included; if not, it's excluded.
3. Decentralized Identity Verification
* Merkle trees can be used in decentralized identity systems to verify credentials.
* Off-chain data: a user's credentials.
* On-chain data: the Merkle root representing the credentials.
### Visual example
The above diagram represents a merkle tree.\
Each leaf node is the hash of some data.\
Each other node is the hash of the combination of both children nodes.
If we were to `verify{:md}` the `hash 6{:md}`, the merkle proof would need to contain the `hash 5{:md}`, `hash 12{:md}`and `hash 13{:md}`:
1. The `hash 5{:md}` would be combined with the `hash 6{:md}` to re-compute the `hash 11{:md}`.
2. The newly computed `hash 11{:md}` in step 1 would be combined with `hash 12{:md}` to re-compute `hash 14{:md}`.
3. The `hash 13{:md}` would be combined with the newly computed `hash 14{:md}` in step 2 to re-compute the merkle root.
4. We can then compare the computed resultant merkle root with the one provided to the `verify{:md}` function.
### Code
The following implementation is the Cairo adaptation of the [Solidity by Example - Merkle Tree contract](https://solidity-by-example.org/app/merkle-tree/).
```rust theme={null}
#[generate_trait]
pub impl ByteArrayHashTraitImpl of ByteArrayHashTrait {
fn hash(self: @ByteArray) -> felt252 {
let mut serialized_byte_arr: Array<felt252> = ArrayTrait::new();
self.serialize(ref serialized_byte_arr);
core::poseidon::poseidon_hash_span(serialized_byte_arr.span())
}
}
#[starknet::interface]
pub trait IMerkleTree<TContractState> {
fn build_tree(ref self: TContractState, data: Array<ByteArray>) -> Array<felt252>;
fn get_root(self: @TContractState) -> felt252;
// function to verify if leaf node exists in the merkle tree
fn verify(
self: @TContractState, proof: Array<felt252>, root: felt252, leaf: felt252, index: usize,
) -> bool;
}
mod errors {
pub const NOT_POW_2: felt252 = "Data length is not a power of 2";
pub const NOT_PRESENT: felt252 = "No element in merkle tree";
}
#[starknet::contract]
pub mod MerkleTree {
use core::poseidon::PoseidonTrait;
use core::hash::{HashStateTrait, HashStateExTrait};
use starknet::storage::{
StoragePointerWriteAccess, StoragePointerReadAccess, Vec, MutableVecTrait, VecTrait,
};
use super::ByteArrayHashTrait;
#[storage]
struct Storage {
pub hashes: Vec<felt252>,
}
#[derive(Drop, Serde, Copy)]
struct Vec2 {
x: u32,
y: u32,
}
#[abi(embed_v0)]
impl IMerkleTreeImpl of super::IMerkleTree<ContractState> {
fn build_tree(ref self: ContractState, mut data: Array<ByteArray>) -> Array<felt252> {
let data_len = data.len();
assert(data_len > 0 && (data_len & (data_len - 1)) == 0, super::errors::NOT_POW_2);
let mut _hashes: Array<felt252> = ArrayTrait::new();
// first, hash every leaf
for value in data {
_hashes.append(value.hash());
};
// then, hash all levels above leaves
let mut current_nodes_lvl_len = data_len;
let mut hashes_offset = 0;
while current_nodes_lvl_len > 0 {
let mut i = 0;
while i < current_nodes_lvl_len - 1 {
let left_elem = *_hashes.at(hashes_offset + i);
let right_elem = *_hashes.at(hashes_offset + i + 1);
let hash = PoseidonTrait::new().update_with((left_elem, right_elem)).finalize();
_hashes.append(hash);
i += 2;
};
hashes_offset += current_nodes_lvl_len;
current_nodes_lvl_len /= 2;
};
// write to the contract state (useful for the get_root function)
for hash in _hashes.span() {
self.hashes.append().write(*hash);
};
_hashes
}
fn get_root(self: @ContractState) -> felt252 {
let merkle_tree_length = self.hashes.len();
assert(merkle_tree_length > 0, super::errors::NOT_PRESENT);
self.hashes.at(merkle_tree_length - 1).read()
}
fn verify(
self: @ContractState,
mut proof: Array<felt252>,
root: felt252,
leaf: felt252,
mut index: usize,
) -> bool {
let mut current_hash = leaf;
while let Option::Some(value) = proof.pop_front() {
current_hash =
if index % 2 == 0 {
PoseidonTrait::new().update_with((current_hash, value)).finalize()
} else {
PoseidonTrait::new().update_with((value, current_hash)).finalize()
};
index /= 2;
};
current_hash == root
}
}
}
```
# NFT Dutch auction
Source: https://docs.starknet.io/build/starknet-by-example/applications/nft-dutch-auction
This is the Cairo adaptation (with some modifications) of the [Solidity by example NFT Dutch Auc프로젝트로 돌아가기