bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 73쪽 중 20쪽
);
}
}
}
```
# Constant product AMM
Source: https://docs.starknet.io/build/starknet-by-example/applications/constant-product-amm
This is the Cairo adaptation of the
[Solidity by Example - Constant Product AMM](https://solidity-by-example.org/defi/constant-product-amm/).
In this contract, we implement a simple Automated Market Maker (AMM) following
the **constant product formula**: $( x \cdot y = k )$. This formula ensures
that the product of the two token reserves ($x$ and $y$ representing the tokens
being swapper) remains constant, regardless of trades. Here, we provide
liquidity pools that allow users to trade between two tokens or add and remove
liquidity from the pool.
## Key Concepts
1. **approve() before swap or adding liquidity**:
Before interacting with the AMM (whether through swaps or adding liquidity),
the user must approve the contract to spend their tokens. This is done by
calling the `approve()` function on the ERC20 token contracts, allowing the
AMM to transfer the required tokens on behalf of the user.
2. **Constant Product Formula for Swaps**:
The swap function operates based on the constant product formula $( x \cdot
y = k )$, where $x$ and $y$ are the token reserves. When a user swaps one
token for another, the product of the reserves remains constant, which
determines how much of the other token the user will receive.
3. **Shares and Token Ratios for Liquidity**:
When adding liquidity, users provide both tokens in the ratio of the current
reserves. The number of shares (liquidity tokens) the user receives
represents their contribution to the pool. Similarly, when removing
liquidity, users receive back tokens proportional to the number of shares
they burn.
```rust theme={null}
use starknet::ContractAddress;
#[starknet::interface]
pub trait IConstantProductAmm<TContractState> {
fn swap(ref self: TContractState, token_in: ContractAddress, amount_in: u256) -> u256;
fn add_liquidity(ref self: TContractState, amount0: u256, amount1: u256) -> u256;
fn remove_liquidity(ref self: TContractState, shares: u256) -> (u256, u256);
}
#[starknet::contract]
pub mod ConstantProductAmm {
use starknet::storage::{StoragePointerReadAccess, StoragePointerWriteAccess};
use openzeppelin_token::erc20::interface::{IERC20Dispatcher, IERC20DispatcherTrait};
use starknet::{ContractAddress, get_caller_address, get_contract_address};
use starknet::storage::{Map, StorageMapReadAccess, StorageMapWriteAccess};
use core::num::traits::Sqrt;
#[storage]
struct Storage {
token0: IERC20Dispatcher,
token1: IERC20Dispatcher,
reserve0: u256,
reserve1: u256,
total_supply: u256,
balance_of: Map::<ContractAddress, u256>,
// Fee 0 - 1000 (0% - 100%, 1 decimal places)
// E.g. 3 = 0.3%
fee: u16,
}
#[constructor]
fn constructor(
ref self: ContractState, token0: ContractAddress, token1: ContractAddress, fee: u16,
) {
// assert(fee <= 1000, 'fee > 1000');
self.token0.write(IERC20Dispatcher { contract_address: token0 });
self.token1.write(IERC20Dispatcher { contract_address: token1 });
self.fee.write(fee);
}
#[generate_trait]
impl PrivateFunctions of PrivateFunctionsTrait {
fn _mint(ref self: ContractState, to: ContractAddress, amount: u256) {
self.balance_of.write(to, self.balance_of.read(to) + amount);
self.total_supply.write(self.total_supply.read() + amount);
}
fn _burn(ref self: ContractState, from: ContractAddress, amount: u256) {
self.balance_of.write(from, self.balance_of.read(from) - amount);
self.total_supply.write(self.total_supply.read() - amount);
}
fn _update(ref self: ContractState, reserve0: u256, reserve1: u256) {
self.reserve0.write(reserve0);
self.reserve1.write(reserve1);
}
#[inline(always)]
fn select_token(self: @ContractState, token: ContractAddress) -> bool {
assert(
token == self.token0.read().contract_address
|| token == self.token1.read().contract_address,
"invalid token",
);
token == self.token0.read().contract_address
}
#[inline(always)]
fn min(x: u256, y: u256) -> u256 {
if (x <= y) {
x
} else {
y
}
}
}
#[abi(embed_v0)]
impl ConstantProductAmm of super::IConstantProductAmm<ContractState> {
fn swap(ref self: ContractState, token_in: ContractAddress, amount_in: u256) -> u256 {
assert(amount_in > 0, "amount in = 0");
let is_token0: bool = self.select_token(token_in);
let (token0, token1): (IERC20Dispatcher, IERC20Dispatcher) = (
self.token0.read(), self.token1.read(),
);
let (reserve0, reserve1): (u256, u256) = (self.reserve0.read(), self.reserve1.read());
let (
token_in, token_out, reserve_in, reserve_out,
): (IERC20Dispatcher, IERC20Dispatcher, u256, u256) =
if (is_token0) {
(token0, token1, reserve0, reserve1)
} else {
(token1, token0, reserve1, reserve0)
};
let caller = get_caller_address();
let this = get_contract_address();
token_in.transfer_from(caller, this, amount_in);
// How much dy for dx?
// xy = k
// (x + dx)(y - dy) = k
// y - dy = k / (x + dx)
// y - k / (x + dx) = dy
// y - xy / (x + dx) = dy
// (yx + ydx - xy) / (x + dx) = dy
// ydx / (x + dx) = dy
let amount_in_with_fee = (amount_in * (1000 - self.fee.read().into()) / 1000);
let amount_out = (reserve_out * amount_in_with_fee) / (reserve_in + amount_in_with_fee);
token_out.transfer(caller, amount_out);
self._update(self.token0.read().balance_of(this), self.token1.read().balance_of(this));
amount_out
}
fn add_liquidity(ref self: ContractState, amount0: u256, amount1: u256) -> u256 {
let caller = get_caller_address();
let this = get_contract_address();
let (token0, token1): (IERC20Dispatcher, IERC20Dispatcher) = (
self.token0.read(), self.token1.read(),
);
token0.transfer_from(caller, this, amount0);
token1.transfer_from(caller, this, amount1);
// How much dx, dy to add?
//
// xy = k
// (x + dx)(y + dy) = k'
//
// No price change, before and after adding liquidity
// x / y = (x + dx) / (y + dy)
//
// x(y + dy) = y(x + dx)
// x * dy = y * dx
//
// x / y = dx / dy
// dy = y / x * dx
let (reserve0, reserve1): (u256, u256) = (self.reserve0.read(), self.reserve1.read());
if (reserve0 > 0 || reserve1 > 0) {
assert(reserve0 * amount1 == reserve1 * amount0, "x / y != dx / dy");
}
// How many shares to mint?
//
// f(x, y) = value of liquidity
// We will define f(x, y) = sqrt(xy)
//
// L0 = f(x, y)
// L1 = f(x + dx, y + dy)
// T = total shares
// s = shares to mint
//
// Total shares should increase proportional to increase in liquidity
// L1 / L0 = (T + s) / T
//
// L1 * T = L0 * (T + s)
//
// (L1 - L0) * T / L0 = s
// Claim
// (L1 - L0) / L0 = dx / x = dy / y
//
// Proof
// --- Equation 1 ---
// (L1 - L0) / L0 = (sqrt((x + dx)(y + dy)) - sqrt(xy)) / sqrt(xy)
//
// dx / dy = x / y so replace dy = dx * y / x
//
// --- Equation 2 ---
// Equation 1 = (sqrt(xy + 2ydx + dx^2 * y / x) - sqrt(xy)) / sqrt(xy)
//
// Multiply by sqrt(x) / sqrt(x)
// Equation 2 = (sqrt(x^2y + 2xydx + dx^2 * y) - sqrt(x^2y)) / sqrt(x^2y)
// = (sqrt(y)(sqrt(x^2 + 2xdx + dx^2) - sqrt(x^2))) / (sqrt(y)sqrt(x^2))
// sqrt(y) on top and bottom cancels out
//
// --- Equation 3 ---
// Equation 2 = (sqrt(x^2 + 2xdx + dx^2) - sqrt(x^2)) / sqrt(x^2)
// = (sqrt((x + dx)^2) - sqrt(x^2)) / sqrt(x^2)
// = ((x + dx) - x) / x
// = dx / x
// Since dx / dy = x / y,
// dx / x = dy / y
//
// Finally
// (L1 - L0) / L0 = dx / x = dy / y
let total_supply = self.total_supply.read();
let shares = if (total_supply == 0) {
(amount0 * amount1).sqrt().into()
} else {
PrivateFunctions::min(
amount0 * total_supply / reserve0, amount1 * total_supply / reserve1,
)
};
assert(shares > 0, "shares = 0");
self._mint(caller, shares);
self._update(self.token0.read().balance_of(this), self.token1.read().balance_of(this));
shares
}
fn remove_liquidity(ref self: ContractState, shares: u256) -> (u256, u256) {
let caller = get_caller_address();
let this = get_contract_address();
let (token0, token1): (IERC20Dispatcher, IERC20Dispatcher) = (
self.token0.read(), self.token1.read(),
);
// Claim
// dx, dy = amount of liquidity to remove
// dx = s / T * x
// dy = s / T * y
//
// Proof
// Let's find dx, dy such that
// v / L = s / T
//
// where
// v = f(dx, dy) = sqrt(dxdy)
// L = total liquidity = sqrt(xy)
// s = shares
// T = total supply
//
// --- Equation 1 ---
// v = s / T * L
// sqrt(dxdy) = s / T * sqrt(xy)
//
// Amount of liquidity to remove must not change price so
// dx / dy = x / y
//
// replace dy = dx * y / x
// sqrt(dxdy) = sqrt(dx * dx * y / x) = dx * sqrt(y / x)
//
// Divide both sides of Equation 1 with sqrt(y / x)
// dx = s / T * sqrt(xy) / sqrt(y / x)
// = s / T * sqrt(x^2) = s / T * x
//
// Likewise
// dy = s / T * y
// bal0 >= reserve0
// bal1 >= reserve1
let (bal0, bal1): (u256, u256) = (token0.balance_of(this), token1.balance_of(this));
let total_supply = self.total_supply.read();
let (amount0, amount1): (u256, u256) = (
(shares * bal0) / total_supply, (shares * bal1) / total_supply,
);
assert(amount0 > 0 && amount1 > 0, "amount0 or amount1 = 0");
self._burn(caller, shares);
self._update(bal0 - amount0, bal1 - amount1);
token0.transfer(caller, amount0);
token1.transfer(caller, amount1);
(amount0, amount1)
}
}
}
```
# Crowdfunding
Source: https://docs.starknet.io/build/starknet-by-example/applications/crowdfunding
Crowdfunding is a method of raising capital through the collective effort of many individuals. It allows project creators to raise funds from a large number of people, usually through small contributions.
1. Contract admin creates a campaign in some user's name (i.e. creator).
2. Users can pledge, transferring their token to a campaign.
3. Users can "unpledge", retrieving their tokens.
4. The creator can at any point refund any of the users.
5. Once the total amount pledged is more than the campaign goal, the campaign funds are "locked" in the contract, meaning the users can no longer unpledge; they can still pledge though.
6. After the campaign ends, the campaign creator can claim the funds if the campaign goal is reached.
7. Otherwise, campaign did not reach it's goal, pledgers can retrieve their funds.
8. The creator can at any point cancel the campaign for whatever reason and refund all of the pledgers.
9. The contract admin can upgrade the contract implementation, refunding all of the users and resetting the campaign state (we will use this in the [Advanced Factory chapter](./advanced-factory)).
Because contract upgrades need to be able to refund all of the pledges, we need to be able to iterate over all of the pledgers and their amounts. Since iteration is not supported by `Map`, we need to create a custom storage type that will encompass pledge management. We use a component for this purpose.
```rust theme={null}
use starknet::ContractAddress;
#[starknet::interface]
pub trait IPledgeable<TContractState> {
fn add(ref self: TContractState, pledger: ContractAddress, amount: u256);
fn get(self: @TContractState, pledger: ContractAddress) -> u256;
fn get_pledger_count(self: @TContractState) -> u32;
fn array(self: @TContractState) -> Array<ContractAddress>;
fn get_total(self: @TContractState) -> u256;
fn remove(ref self: TContractState, pledger: ContractAddress) -> u256;
}
#[starknet::component]
pub mod pledgeable_component {
use core::array::ArrayTrait;
use core::num::traits::Zero;
use starknet::ContractAddress;
use starknet::storage::{
Map, StorageMapReadAccess, StorageMapWriteAccess, StoragePointerReadAccess,
StoragePointerWriteAccess,
};
#[storage]
pub struct Storage {
index_to_pledger: Map<u32, ContractAddress>,
pledger_to_amount: Map<ContractAddress, u256>,
pledger_count: u32,
total_amount: u256,
}
#[event]
#[derive(Drop, starknet::Event)]
pub enum Event {}
mod Errors {
pub const INCONSISTENT_STATE: felt252 = "Non-indexed pledger found";
}
#[embeddable_as(Pledgeable)]
pub impl PledgeableImpl<
TContractState, +HasComponent<TContractState>,
> of super::IPledgeable<ComponentState<TContractState>> {
fn add(ref self: ComponentState<TContractState>, pledger: ContractAddress, amount: u256) {
let old_amount: u256 = self.pledger_to_amount.read(pledger);
if old_amount == 0 {
let index = self.pledger_count.read();
self.index_to_pledger.write(index, pledger);
self.pledger_count.write(index + 1);
}
self.pledger_to_amount.write(pledger, old_amount + amount);
self.total_amount.write(self.total_amount.read() + amount);
}
fn get(self: @ComponentState<TContractState>, pledger: ContractAddress) -> u256 {
self.pledger_to_amount.read(pledger)
}
fn get_pledger_count(self: @ComponentState<TContractState>) -> u32 {
self.pledger_count.read()
}
fn array(self: @ComponentState<TContractState>) -> Array<ContractAddress> {
let mut result = array![];
let mut index = self.pledger_count.read();
while index != 0 {
index -= 1;
let pledger = self.index_to_pledger.read(index);
result.append(pledger);
};
result
}
fn get_total(self: @ComponentState<TContractState>) -> u256 {
self.total_amount.read()
}
fn remove(ref self: ComponentState<TContractState>, pledger: ContractAddress) -> u256 {
let amount: u256 = self.pledger_to_amount.read(pledger);
// check if the pledge even exists
if amount == 0 {
return 0;
}
let last_index = self.pledger_count.read() - 1;
// if there are other pledgers, we need to update our indices
if last_index != 0 {
let mut pledger_index = last_index;
loop {
if self.index_to_pledger.read(pledger_index) == pledger {
break;
}
// if pledger_to_amount contains a pledger, then so does index_to_pledger
// thus this will never underflow
pledger_index -= 1;
};
self.index_to_pledger.write(pledger_index, self.index_to_pledger.read(last_index));
}
// last_index == new pledger count
self.pledger_count.write(last_index);
self.pledger_to_amount.write(pledger, 0);
self.index_to_pledger.write(last_index, Zero::zero());
self.total_amount.write(self.total_amount.read() - amount);
amount
}
}
}
```
Now we can create the `Campaign` contract.
```rust theme={null}
pub mod pledgeable;
use starknet::{ClassHash, ContractAddress};
#[derive(Drop, Serde)]
pub struct Details {
pub canceled: bool,
pub claimed: bool,
pub creator: ContractAddress,
pub description: ByteArray,
pub end_time: u64,
pub goal: u256,
pub start_time: u64,
pub title: ByteArray,
pub token: ContractAddress,
pub total_pledges: u256,
}
#[starknet::interface]
pub trait ICampaign<TContractState> {
fn claim(ref self: TContractState);
fn cancel(ref self: TContractState, reason: ByteArray);
fn pledge(ref self: TContractState, amount: u256);
fn get_pledge(self: @TContractState, pledger: ContractAddress) -> u256;
fn get_pledgers(self: @TContractState) -> Array<ContractAddress>;
fn get_details(self: @TContractState) -> Details;
fn refund(ref self: TContractState, pledger: ContractAddress, reason: ByteArray);
fn upgrade(ref self: TContractState, impl_hash: ClassHash, new_end_time: Option<u64>);
fn unpledge(ref self: TContractState, reason: ByteArray);
}
#[starknet::contract]
pub mod Campaign {
use starknet::storage::{StoragePointerReadAccess, StoragePointerWriteAccess};
use components::ownable::ownable_component::OwnableInternalTrait;
use core::num::traits::Zero;
use openzeppelin_token::erc20::interface::{IERC20Dispatcher, IERC20DispatcherTrait};
use starknet::{
ClassHash, ContractAddress, get_block_timestamp, get_caller_address, get_contract_address,
};
use components::ownable::ownable_component;
use super::pledgeable::pledgeable_component;
use super::Details;
component!(path: ownable_component, storage: ownable, event: OwnableEvent);
component!(path: pledgeable_component, storage: pledges, event: PledgeableEvent);
#[abi(embed_v0)]
pub impl OwnableImpl = ownable_component::Ownable<ContractState>;
impl OwnableInternalImpl = ownable_component::OwnableInternalImpl<ContractState>;
#[abi(embed_v0)]
impl PledgeableImpl = pledgeable_component::Pledgeable<ContractState>;
#[storage]
struct Storage {
canceled: bool,
claimed: bool,
creator: ContractAddress,
description: ByteArray,
end_time: u64,
goal: u256,
#[substorage(v0)]
ownable: ownable_component::Storage,
#[substorage(v0)]
pledges: pledgeable_component::Storage,
start_time: u64,
title: ByteArray,
token: IERC20Dispatcher,
}
#[event]
#[derive(Drop, starknet::Event)]
pub enum Event {
Claimed: Claimed,
Canceled: Canceled,
#[flat]
OwnableEvent: ownable_component::Event,
PledgeableEvent: pledgeable_component::Event,
PledgeMade: PledgeMade,
Refunded: Refunded,
RefundedAll: RefundedAll,
Unpledged: Unpledged,
Upgraded: Upgraded,
}
#[derive(Drop, starknet::Event)]
pub struct Canceled {
pub reason: ByteArray,
}
#[derive(Drop, starknet::Event)]
pub struct Claimed {
pub amount: u256,
}
#[derive(Drop, starknet::Event)]
pub struct PledgeMade {
#[key]
pub pledger: ContractAddress,
pub amount: u256,
}
#[derive(Drop, starknet::Event)]
pub struct Refunded {
#[key]
pub pledger: ContractAddress,
pub amount: u256,
pub reason: ByteArray,
}
#[derive(Drop, starknet::Event)]
pub struct RefundedAll {
pub reason: ByteArray,
}
#[derive(Drop, starknet::Event)]
pub struct Unpledged {
#[key]
pub pledger: ContractAddress,
pub amount: u256,
pub reason: ByteArray,
}
#[derive(Drop, starknet::Event)]
pub struct Upgraded {
pub implementation: ClassHash,
}
pub mod Errors {
pub const CANCELED: felt252 = "Campaign canceled";
pub const CLAIMED: felt252 = "Campaign already claimed";
pub const CLASS_HASH_ZERO: felt252 = "Class hash zero";
pub const CREATOR_ZERO: felt252 = "Creator address zero";
pub const ENDED: felt252 = "Campaign already ended";
pub const END_BEFORE_NOW: felt252 = "End time < now";
pub const END_BEFORE_START: felt252 = "End time < start time";
pub const END_BIGGER_THAN_MAX: felt252 = "End time > max duration";
pub const NOTHING_TO_REFUND: felt252 = "Nothing to refund";
pub const NOTHING_TO_UNPLEDGE: felt252 = "Nothing to unpledge";
pub const NOT_CREATOR: felt252 = "Not creator";
pub const NOT_STARTED: felt252 = "Campaign not started";
pub const PLEDGES_LOCKED: felt252 = "Goal reached, pledges locked";
pub const START_TIME_IN_PAST: felt252 = "Start time < now";
pub const STILL_ACTIVE: felt252 = "Campaign not ended";
pub const GOAL_NOT_REACHED: felt252 = "Goal not reached";
pub const TITLE_EMPTY: felt252 = "Title empty";
pub const TRANSFER_FAILED: felt252 = "Transfer failed";
pub const ZERO_ADDRESS_CALLER: felt252 = "Caller address zero";
pub const ZERO_ADDRESS_PLEDGER: felt252 = "Pledger address zero";
pub const ZERO_ADDRESS_TOKEN: felt252 = "Token address zero";
pub const ZERO_DONATION: felt252 = "Donation must be > 0";
pub const ZERO_GOAL: felt252 = "Goal must be > 0";
pub const ZERO_PLEDGES: felt252 = "No pledges to claim";
}
const NINETY_DAYS: u64 = 90 * 24 * 60 * 60;
#[constructor]
fn constructor(
ref self: ContractState,
creator: ContractAddress,
title: ByteArray,
description: ByteArray,
goal: u256,
start_time: u64,
end_time: u64,
token_address: ContractAddress,
) {
assert(creator.is_non_zero(), Errors::CREATOR_ZERO);
assert(title.len() > 0, Errors::TITLE_EMPTY);
assert(goal > 0, Errors::ZERO_GOAL);
assert(start_time >= get_block_timestamp(), Errors::START_TIME_IN_PAST);
assert(end_time >= start_time, Errors::END_BEFORE_START);
assert(end_time <= get_block_timestamp() + NINETY_DAYS, Errors::END_BIGGER_THAN_MAX);
assert(token_address.is_non_zero(), Errors::ZERO_ADDRESS_TOKEN);
self.creator.write(creator);
self.title.write(title);
self.goal.write(goal);
self.description.write(description);
self.start_time.write(start_time);
self.end_time.write(end_time);
self.token.write(IERC20Dispatcher { contract_address: token_address });
self.ownable._init(get_caller_address());
}
#[abi(embed_v0)]
impl Campaign of super::ICampaign<ContractState> {
fn cancel(ref self: ContractState, reason: ByteArray) {
self._assert_only_프로젝트로 돌아가기