creator();
assert(!self.canceled.read(), Errors::CANCELED);
assert(!self.claimed.read(), Errors::CLAIMED);
self.canceled.write(true);
self._refund_all(reason.clone());
self.emit(Event::Canceled(Canceled { reason }));
}
/// Sends the funds to the campaign creator.
/// It leaves the pledge data intact as a testament to campaign success
fn claim(ref self: ContractState) {
self._assert_only_creator();
assert(self._is_started(), Errors::NOT_STARTED);
assert(self._is_ended(), Errors::STILL_ACTIVE);
assert(!self.claimed.read(), Errors::CLAIMED);
assert(self._is_goal_reached(), Errors::GOAL_NOT_REACHED);
// no need to check if canceled; if it was, then the goal wouldn't have been reached
let this = get_contract_address();
let token = self.token.read();
let amount = token.balance_of(this);
assert(amount > 0, Errors::ZERO_PLEDGES);
self.claimed.write(true);
let owner = get_caller_address();
let success = token.transfer(owner, amount);
assert(success, Errors::TRANSFER_FAILED);
self.emit(Event::Claimed(Claimed { amount }));
}
fn get_details(self: @ContractState) -> Details {
Details {
canceled: self.canceled.read(),
claimed: self.claimed.read(),
creator: self.creator.read(),
description: self.description.read(),
end_time: self.end_time.read(),
goal: self.goal.read(),
start_time: self.start_time.read(),
title: self.title.read(),
token: self.token.read().contract_address,
total_pledges: self.pledges.get_total(),
}
}
fn get_pledge(self: @ContractState, pledger: ContractAddress) -> u256 {
self.pledges.get(pledger)
}
fn get_pledgers(self: @ContractState) -> Array<ContractAddress> {
self.pledges.array()
}
fn pledge(ref self: ContractState, amount: u256) {
assert(self._is_started(), Errors::NOT_STARTED);
assert(!self._is_ended(), Errors::ENDED);
assert(!self.canceled.read(), Errors::CANCELED);
assert(amount > 0, Errors::ZERO_DONATION);
let pledger = get_caller_address();
let this = get_contract_address();
let success = self.token.read().transfer_from(pledger, this, amount);
assert(success, Errors::TRANSFER_FAILED);
self.pledges.add(pledger, amount);
self.emit(Event::PledgeMade(PledgeMade { pledger, amount }));
}
fn refund(ref self: ContractState, pledger: ContractAddress, reason: ByteArray) {
self._assert_only_creator();
assert(self._is_started(), Errors::NOT_STARTED);
assert(!self.claimed.read(), Errors::CLAIMED);
assert(!self.canceled.read(), Errors::CANCELED);
assert(pledger.is_non_zero(), Errors::ZERO_ADDRESS_PLEDGER);
assert(self.pledges.get(pledger) != 0, Errors::NOTHING_TO_REFUND);
let amount = self._refund(pledger);
self.emit(Event::Refunded(Refunded { pledger, amount, reason }))
}
fn unpledge(ref self: ContractState, reason: ByteArray) {
assert(self._is_started(), Errors::NOT_STARTED);
assert(!self._is_goal_reached(), Errors::PLEDGES_LOCKED);
assert(self.pledges.get(get_caller_address()) != 0, Errors::NOTHING_TO_UNPLEDGE);
let pledger = get_caller_address();
let amount = self._refund(pledger);
self.emit(Event::Unpledged(Unpledged { pledger, amount, reason }));
}
fn upgrade(ref self: ContractState, impl_hash: ClassHash, new_end_time: Option<u64>) {
self.ownable._assert_only_owner();
assert(impl_hash.is_non_zero(), Errors::CLASS_HASH_ZERO);
// only active campaigns have pledges to refund and an end time to update
if self._is_started() {
if let Option::Some(end_time) = new_end_time {
assert(end_time >= get_block_timestamp(), Errors::END_BEFORE_NOW);
assert(
end_time <= get_block_timestamp() + NINETY_DAYS,
Errors::END_BIGGER_THAN_MAX,
);
self.end_time.write(end_time);
};
self._refund_all("contract upgraded");
}
starknet::syscalls::replace_class_syscall(impl_hash).unwrap();
self.emit(Event::Upgraded(Upgraded { implementation: impl_hash }));
}
}
#[generate_trait]
impl CampaignInternalImpl of CampaignInternalTrait {
fn _assert_only_creator(self: @ContractState) {
let caller = get_caller_address();
assert(caller.is_non_zero(), Errors::ZERO_ADDRESS_CALLER);
assert(caller == self.creator.read(), Errors::NOT_CREATOR);
}
fn _is_ended(self: @ContractState) -> bool {
get_block_timestamp() >= self.end_time.read()
}
fn _is_goal_reached(self: @ContractState) -> bool {
self.pledges.get_total() >= self.goal.read()
}
fn _is_started(self: @ContractState) -> bool {
get_block_timestamp() >= self.start_time.read()
}
#[inline(always)]
fn _refund(ref self: ContractState, pledger: ContractAddress) -> u256 {
let amount = self.pledges.remove(pledger);
let success = self.token.read().transfer(pledger, amount);
assert(success, Errors::TRANSFER_FAILED);
amount
}
fn _refund_all(ref self: ContractState, reason: ByteArray) {
let mut pledges = self.pledges.array();
while let Option::Some(pledger) = pledges.pop_front() {
self._refund(pledger);
};
self.emit(Event::RefundedAll(RefundedAll { reason }));
}
}
}
```
# ERC20 token
Source: https://docs.starknet.io/build/starknet-by-example/applications/erc20
Contracts that follow the [ERC20 Standard](https://eips.ethereum.org/EIPS/eip-20) are called ERC20 tokens. They are used to represent fungible assets.
To create an ERC20 contract, it must implement the following interface:
```rust theme={null}
use starknet::ContractAddress;
#[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,
);
}
```
In Starknet, function names should be written in *snake\_case*. This is not the case in Solidity, where function names are written in *camelCase*.
The Starknet ERC20 interface is therefore slightly different from the Solidity ERC20 interface.
Here's an implementation of the ERC20 interface in Cairo:
```rust theme={null}
#[starknet::contract]
pub mod erc20 {
use core::num::traits::Zero;
use starknet::get_caller_address;
use starknet::contract_address_const;
use starknet::ContractAddress;
use starknet::storage::{
Map, StorageMapReadAccess, StorageMapWriteAccess, StoragePointerReadAccess,
StoragePointerWriteAccess,
};
#[storage]
struct Storage {
name: felt252,
symbol: felt252,
decimals: u8,
total_supply: felt252,
balances: Map::<ContractAddress, felt252>,
allowances: Map::<(ContractAddress, ContractAddress), felt252>,
}
#[event]
#[derive(Copy, Drop, Debug, PartialEq, starknet::Event)]
pub enum Event {
Transfer: Transfer,
Approval: Approval,
}
#[derive(Copy, Drop, Debug, PartialEq, starknet::Event)]
pub struct Transfer {
pub from: ContractAddress,
pub to: ContractAddress,
pub value: felt252,
}
#[derive(Copy, Drop, Debug, PartialEq, starknet::Event)]
pub struct Approval {
pub owner: ContractAddress,
pub spender: ContractAddress,
pub value: felt252,
}
mod Errors {
pub const APPROVE_FROM_ZERO: felt252 = "ERC20: approve from 0";
pub const APPROVE_TO_ZERO: felt252 = "ERC20: approve to 0";
pub const TRANSFER_FROM_ZERO: felt252 = "ERC20: transfer from 0";
pub const TRANSFER_TO_ZERO: felt252 = "ERC20: transfer to 0";
pub const BURN_FROM_ZERO: felt252 = "ERC20: burn from 0";
pub const MINT_TO_ZERO: felt252 = "ERC20: mint to 0";
}
#[constructor]
fn constructor(
ref self: ContractState,
recipient: ContractAddress,
name: felt252,
decimals: u8,
initial_supply: felt252,
symbol: felt252,
) {
self.name.write(name);
self.symbol.write(symbol);
self.decimals.write(decimals);
self.mint(recipient, initial_supply);
}
#[abi(embed_v0)]
impl IERC20Impl of super::IERC20<ContractState> {
fn get_name(self: @ContractState) -> felt252 {
self.name.read()
}
fn get_symbol(self: @ContractState) -> felt252 {
self.symbol.read()
}
fn get_decimals(self: @ContractState) -> u8 {
self.decimals.read()
}
fn get_total_supply(self: @ContractState) -> felt252 {
self.total_supply.read()
}
fn balance_of(self: @ContractState, account: ContractAddress) -> felt252 {
self.balances.read(account)
}
fn allowance(
self: @ContractState, owner: ContractAddress, spender: ContractAddress,
) -> felt252 {
self.allowances.read((owner, spender))
}
fn transfer(ref self: ContractState, recipient: ContractAddress, amount: felt252) {
let sender = get_caller_address();
self._transfer(sender, recipient, amount);
}
fn transfer_from(
ref self: ContractState,
sender: ContractAddress,
recipient: ContractAddress,
amount: felt252,
) {
let caller = get_caller_address();
self.spend_allowance(sender, caller, amount);
self._transfer(sender, recipient, amount);
}
fn approve(ref self: ContractState, spender: ContractAddress, amount: felt252) {
let caller = get_caller_address();
self.approve_helper(caller, spender, amount);
}
fn increase_allowance(
ref self: ContractState, spender: ContractAddress, added_value: felt252,
) {
let caller = get_caller_address();
self
.approve_helper(
caller, spender, self.allowances.read((caller, spender)) + added_value,
);
}
fn decrease_allowance(
ref self: ContractState, spender: ContractAddress, subtracted_value: felt252,
) {
let caller = get_caller_address();
self
.approve_helper(
caller, spender, self.allowances.read((caller, spender)) - subtracted_value,
);
}
}
#[generate_trait]
impl InternalImpl of InternalTrait {
fn _transfer(
ref self: ContractState,
sender: ContractAddress,
recipient: ContractAddress,
amount: felt252,
) {
assert(sender.is_non_zero(), Errors::TRANSFER_FROM_ZERO);
assert(recipient.is_non_zero(), Errors::TRANSFER_TO_ZERO);
self.balances.write(sender, self.balances.read(sender) - amount);
self.balances.write(recipient, self.balances.read(recipient) + amount);
self.emit(Transfer { from: sender, to: recipient, value: amount });
}
fn spend_allowance(
ref self: ContractState,
owner: ContractAddress,
spender: ContractAddress,
amount: felt252,
) {
let allowance = self.allowances.read((owner, spender));
self.allowances.write((owner, spender), allowance - amount);
}
fn approve_helper(
ref self: ContractState,
owner: ContractAddress,
spender: ContractAddress,
amount: felt252,
) {
assert(spender.is_non_zero(), Errors::APPROVE_TO_ZERO);
self.allowances.write((owner, spender), amount);
self.emit(Approval { owner, spender, value: amount });
}
fn mint(ref self: ContractState, recipient: ContractAddress, amount: felt252) {
assert(recipient.is_non_zero(), Errors::MINT_TO_ZERO);
let supply = self.total_supply.read() + amount;
self.total_supply.write(supply);
let balance = self.balances.read(recipient) + amount;
self.balances.write(recipient, balance);
self
.emit(
Event::Transfer(
Transfer {
from: contract_address_const::<0>(), to: recipient, value: amount,
},
),
);
}
}
}
```
There's several other implementations, such as the [Open Zeppelin](https://docs.openzeppelin.com/contracts-cairo/erc20) or the [Cairo By Example](https://cairo-by-example.com/examples/erc20/) ones.
# ERC721 token
Source: https://docs.starknet.io/build/starknet-by-example/applications/erc721
Contracts that follow the [ERC721 Standard](https://eips.ethereum.org/EIPS/eip-721) are called ERC721 tokens. They are used to represent non-fungible assets.
<Note>
For a deeper understanding of the ERC721 interface specifications and its functionality, we highly recommend reading the EIP in detail.
</Note>
To create an ERC721 contract, it must implement the following interface:
```rust theme={null}
use starknet::ContractAddress;
#[starknet::interface]
pub trait IERC721<TContractState> {
fn balance_of(self: @TContractState, owner: ContractAddress) -> u256;
fn owner_of(self: @TContractState, token_id: u256) -> ContractAddress;
// The function `safe_transfer_from(address _from, address _to, uint256 _tokenId)`
// is not included because the same behavior can be achieved by calling
// `safe_transfer_from(from, to, tokenId, data)` with an empty `data`
// parameter. This approach reduces redundancy in the contract's interface.
fn safe_transfer_from(
ref self: TContractState,
from: ContractAddress,
to: ContractAddress,
token_id: u256,
data: Span<felt252>,
);
fn transfer_from(
ref self: TContractState, from: ContractAddress, to: ContractAddress, token_id: u256,
);
fn approve(ref self: TContractState, approved: ContractAddress, token_id: u256);
fn set_approval_for_all(ref self: TContractState, operator: ContractAddress, approved: bool);
fn get_approved(self: @TContractState, token_id: u256) -> ContractAddress;
fn is_approved_for_all(
self: @TContractState, owner: ContractAddress, operator: ContractAddress,
) -> bool;
}
#[starknet::interface]
pub trait IERC721Mintable<TContractState> {
fn mint(ref self: TContractState, to: ContractAddress, token_id: u256);
}
#[starknet::interface]
pub trait IERC721Burnable<TContractState> {
fn burn(ref self: TContractState, token_id: u256);
}
pub const IERC721_RECEIVER_ID: felt252 =
0x3a0dff5f70d80458ad14ae37bb182a728e3c8cdda0402a5daa86620bdf910bc;
#[starknet::interface]
pub trait IERC721Receiver<TContractState> {
fn on_erc721_received(
self: @TContractState,
operator: ContractAddress,
from: ContractAddress,
token_id: u256,
data: Span<felt252>,
) -> felt252;
}
// The `IERC721Metadata` and `IERC721Enumerable` interfaces are included here
// as optional extensions to the ERC721 standard. While they provide additional
// functionality (such as token metadata and enumeration), they are not
// implemented in this example. Including these interfaces demonstrates how they
// can be integrated and serves as a starting point for developers who wish to
// extend the functionality.
#[starknet::interface]
pub trait IERC721Metadata<TContractState> {
fn name(self: @TContractState) -> ByteArray;
fn symbol(self: @TContractState) -> ByteArray;
fn token_uri(self: @TContractState, token_id: u256) -> ByteArray;
}
#[starknet::interface]
pub trait IERC721Enumerable<TContractState> {
fn total_supply(self: @TContractState) -> u256;
fn token_by_index(self: @TContractState, index: u256) -> u256;
fn token_of_owner_by_index(self: @TContractState, owner: ContractAddress, index: u256) -> u256;
}
```
Because function names in Starknet should be written in *snake\_case*, the Starknet ERC721 interface is slightly different from the Solidity ERC721 interface which uses *camelCase*.
Here's an implementation of the ERC721 interface in Cairo:
```rust theme={null}
#[starknet::contract]
pub mod ERC721 {
use core::num::traits::Zero;
use starknet::get_caller_address;
use starknet::ContractAddress;
use starknet::storage::{Map, StorageMapReadAccess, StorageMapWriteAccess};
use openzeppelin_introspection::interface::{ISRC5Dispatcher, ISRC5DispatcherTrait};
use erc721::interfaces::{
IERC721, IERC721ReceiverDispatcher, IERC721ReceiverDispatcherTrait, IERC721_RECEIVER_ID,
IERC721Mintable, IERC721Burnable,
};
#[storage]
pub struct Storage {
pub owners: Map<u256, ContractAddress>,
pub balances: Map<ContractAddress, u256>,
pub approvals: Map<u256, ContractAddress>,
pub operator_approvals: Map<(ContractAddress, ContractAddress), bool>,
}
#[event]
#[derive(Drop, starknet::Event)]
pub enum Event {
Transfer: Transfer,
Approval: Approval,
ApprovalForAll: ApprovalForAll,
}
#[derive(Drop, starknet::Event)]
pub struct Transfer {
pub from: ContractAddress,
pub to: ContractAddress,
pub token_id: u256,
}
#[derive(Drop, starknet::Event)]
pub struct Approval {
pub owner: ContractAddress,
pub approved: ContractAddress,
pub token_id: u256,
}
#[derive(Drop, starknet::Event)]
pub struct ApprovalForAll {
pub owner: ContractAddress,
pub operator: ContractAddress,
pub approved: bool,
}
pub mod Errors {
pub const INVALID_TOKEN_ID: felt252 = "ERC721: invalid token ID";
pub const INVALID_ACCOUNT: felt252 = "ERC721: invalid account";
pub const INVALID_OPERATOR: felt252 = "ERC721: invalid operator";
pub const UNAUTHORIZED: felt252 = "ERC721: unauthorized caller";
pub const INVALID_RECEIVER: felt252 = "ERC721: invalid receiver";
pub const INVALID_SENDER: felt252 = "ERC721: invalid sender";
pub const SAFE_TRANSFER_FAILED: felt252 = "ERC721: safe transfer failed";
pub const ALREADY_MINTED: felt252 = "ERC721: token already minted";
}
#[abi(embed_v0)]
impl ERC721 of IERC721<ContractState> {
fn owner_of(self: @ContractState, token_id: u256) -> ContractAddress {
self._require_owned(token_id)
}
fn balance_of(self: @ContractState, owner: ContractAddress) -> u256 {
assert(!owner.is_zero(), Errors::INVALID_ACCOUNT);
self.balances.read(owner)
}
fn set_approval_for_all(
ref self: ContractState, operator: ContractAddress, approved: bool,
) {
assert(!operator.is_zero(), Errors::INVALID_OPERATOR);
let owner = get_caller_address();
self.operator_approvals.write((owner, operator), approved);
self.emit(ApprovalForAll { owner, operator, approved });
}
fn approve(ref self: ContractState, approved: ContractAddress, token_id: u256) {
let owner = self._require_owned(token_id);
let caller = get_caller_address();
assert(
caller == owner || self.is_approved_for_all(owner, caller), Errors::UNAUTHORIZED,
);
self.approvals.write(token_id, approved);
self.emit(Approval { owner, approved, token_id });
}
fn get_approved(self: @ContractState, token_id: u256) -> ContractAddress {
self._require_owned(token_id);
self.approvals.read(token_id)
}
fn transfer_from(
ref self: ContractState, from: ContractAddress, to: ContractAddress, token_id: u256,
) {
let previous_owner = self._require_owned(token_id);
assert(from == previous_owner, Errors::INVALID_SENDER);
assert(!to.is_zero(), Errors::INVALID_RECEIVER);
assert(
self._is_approved_or_owner(from, get_caller_address(), token_id),
Errors::UNAUTHORIZED,
);
self.balances.write(from, self.balances.read(from) - 1);
self.balances.write(to, self.balances.read(to) + 1);
self.owners.write(token_id, to);
self.approvals.write(token_id, Zero::zero());
self.emit(Transfer { from, to, token_id });
}
fn safe_transfer_from(
ref self: ContractState,
from: ContractAddress,
to: ContractAddress,
token_id: u256,
data: Span<felt252>,
) {
Self::transfer_from(ref self, from, to, token_id);
assert(
self._check_on_erc721_received(from, to, token_id, data),
Errors::SAFE_TRANSFER_FAILED,
);
}
fn is_approved_for_all(
self: @ContractState, owner: ContractAddress, operator: ContractAddress,
) -> bool {
self.operator_approvals.read((owner, operator))
}
}
#[abi(embed_v0)]
pub impl ERC721Burnable of IERC721Burnable<ContractState> {
fn burn(ref self: ContractState, token_id: u256) {
self._burn(token_id)
}
}
#[abi(embed_v0)]
pub impl ERC721Mintable of IERC721Mintable<ContractState> {
fn mint(ref self: ContractState, to: ContractAddress, token_id: u256) {
self._mint(to, token_id)
}
}
#[generate_trait]
pub impl InternalImpl of InternalTrait {
fn _mint(ref self: ContractState, to: ContractAddress, token_id: u256) {
assert(!to.is_zero(), Errors::INVALID_RECEIVER);
assert(self.owners.read(token_id).is_zero(), Errors::ALREADY_MINTED);
self.balances.write(to, self.balances.read(to) + 1);
self.owners.write(token_id, to);
self.emit(Transfer { from: Zero::zero(), to, token_id });
}
fn _burn(ref self: ContractState, token_id: u256) {
let owner = self._require_owned(token_id);
self.balances.writ프로젝트로 돌아가기