bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 73쪽 중 23쪽
tion](https://solidity-by-example.org/app/dutch-auction/).
Here's how it works:
* The seller of the NFT deploys this contract with a startingPrice.
* The auction lasts for a specified duration.
* The price decreases over time.
* Participants can purchase NFTs at any time as long as the totalSupply has not been reached.
* The auction ends when either the totalSupply is reached or the duration has elapsed.
```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,
);
}
#[starknet::interface]
trait IERC721<TContractState> {
fn get_name(self: @TContractState) -> felt252;
fn get_symbol(self: @TContractState) -> felt252;
fn get_token_uri(self: @TContractState, token_id: u256) -> felt252;
fn balance_of(self: @TContractState, account: ContractAddress) -> u256;
fn owner_of(self: @TContractState, token_id: u256) -> ContractAddress;
fn get_approved(self: @TContractState, token_id: u256) -> ContractAddress;
fn is_approved_for_all(
self: @TContractState, owner: ContractAddress, operator: ContractAddress,
) -> bool;
fn approve(ref self: TContractState, to: ContractAddress, token_id: u256);
fn set_approval_for_all(ref self: TContractState, operator: ContractAddress, approved: bool);
fn transfer_from(
ref self: TContractState, from: ContractAddress, to: ContractAddress, token_id: u256,
);
fn mint(ref self: TContractState, to: ContractAddress, token_id: u256);
}
#[starknet::interface]
pub trait INFTDutchAuction<TContractState> {
fn buy(ref self: TContractState, token_id: u256);
fn get_price(self: @TContractState) -> u64;
}
#[starknet::contract]
pub mod NFTDutchAuction {
use super::{IERC20Dispatcher, IERC20DispatcherTrait, IERC721Dispatcher, IERC721DispatcherTrait};
use starknet::{ContractAddress, get_caller_address, get_block_timestamp};
use starknet::storage::{StoragePointerReadAccess, StoragePointerWriteAccess};
#[storage]
struct Storage {
erc20_token: ContractAddress,
erc721_token: ContractAddress,
starting_price: u64,
seller: ContractAddress,
duration: u64,
discount_rate: u64,
start_at: u64,
expires_at: u64,
purchase_count: u128,
total_supply: u128,
}
mod Errors {
pub const AUCTION_ENDED: felt252 = "auction has ended";
pub const LOW_STARTING_PRICE: felt252 = "low starting price";
pub const INSUFFICIENT_BALANCE: felt252 = "insufficient balance";
}
#[constructor]
fn constructor(
ref self: ContractState,
erc20_token: ContractAddress,
erc721_token: ContractAddress,
starting_price: u64,
seller: ContractAddress,
duration: u64,
discount_rate: u64,
total_supply: u128,
) {
assert(starting_price >= discount_rate * duration, Errors::LOW_STARTING_PRICE);
self.erc20_token.write(erc20_token);
self.erc721_token.write(erc721_token);
self.starting_price.write(starting_price);
self.seller.write(seller);
self.duration.write(duration);
self.discount_rate.write(discount_rate);
self.start_at.write(get_block_timestamp());
self.expires_at.write(get_block_timestamp() + duration * 1000);
self.total_supply.write(total_supply);
}
#[abi(embed_v0)]
impl NFTDutchAuction of super::INFTDutchAuction<ContractState> {
fn get_price(self: @ContractState) -> u64 {
let time_elapsed = (get_block_timestamp() - self.start_at.read())
/ 1000; // Ignore milliseconds
let discount = self.discount_rate.read() * time_elapsed;
self.starting_price.read() - discount
}
fn buy(ref self: ContractState, token_id: u256) {
// Check duration
assert(get_block_timestamp() < self.expires_at.read(), Errors::AUCTION_ENDED);
// Check total supply
assert(self.purchase_count.read() < self.total_supply.read(), Errors::AUCTION_ENDED);
let erc20_dispatcher = IERC20Dispatcher { contract_address: self.erc20_token.read() };
let erc721_dispatcher = IERC721Dispatcher {
contract_address: self.erc721_token.read(),
};
let caller = get_caller_address();
// Get NFT price
let price: u256 = self.get_price().into();
let buyer_balance: u256 = erc20_dispatcher.balance_of(caller).into();
// Ensure buyer has enough token for payment
assert(buyer_balance >= price, Errors::INSUFFICIENT_BALANCE);
// Transfer payment token from buyer to seller
erc20_dispatcher.transfer_from(caller, self.seller.read(), price.try_into().unwrap());
// Mint token to buyer's address
erc721_dispatcher.mint(caller, token_id);
// Increase purchase count
self.purchase_count.write(self.purchase_count.read() + 1);
}
}
}
```
# Random number generator
Source: https://docs.starknet.io/build/starknet-by-example/applications/random-number-generator
Randomness plays a crucial role in blockchain and smart contract development. In the context of blockchain, randomness is about generating unpredictable values using some source of entropy that is fair and resistant to manipulation.
In blockchain and smart contracts, randomness is needed for:
* **Gaming:** Ensuring fair outcomes in games of chance.
* **Lotteries:** Selecting winners in a verifiable and unbiased manner.
* **Security:** Generating cryptographic keys and nonces that are hard to predict.
* **Consensus Protocols:** Selecting validators or block producers in some proof-of-stake systems.
However, achieving true randomness on a decentralized platform poses significant challenges. There are numerous sources of entropy, each with its strengths and weaknesses.
### Sources of Entropy
#### 1. Block Properties
* **Description:** Using properties of the blockchain itself, like the hash of a block, or a block timestamp, as a source of randomness.
* **Example:** A common approach is to use the hash of a recent block as a seed for random number generation.
* **Risks:**
* **Predictability:** Miners can influence future block hashes by controlling the nonce they use during mining.
* **Manipulation:** Many of the blockchain properties (block hash, timestamp etc.) can be manipulated by some entities, especially if they stand to gain from a specific random outcome.
#### 2. User-Provided Inputs
* **Description:** Allowing users to provide entropy directly, often combined with other sources to generate a random number.
* **Example:** Users submitting their own random values which are then hashed together with other inputs.
* **Risks:**
* **Collusion:** Users may collude to provide inputs that skew the randomness in their favor.
* **Front-Running:** Other participants might observe a user's input and act on it before it gets included in the block, affecting the outcome.
#### 3. External Oracles
* **Description:** Using a trusted third-party service to supply randomness. Oracles are off-chain services that provide data to smart contracts.
* **Example:** Pragma VRF (Verifiable Random Function) is a service that provides cryptographically secure randomness.
* **Risks:**
* **Trust:** Reliance on a third party undermines the trustless nature of blockchain.
* **Centralization:** If the oracle service is compromised or shut down, so is the randomness it provides.
* **Cost:** Using an oracle often involves additional transaction fees.
#### 4. Commit-Reveal Schemes
* **Description:** A multi-phase protocol where participants commit to a value in the first phase and reveal it in the second.
* **Example:** Participants submit a hash of their random value (commitment) first and reveal the actual value later. The final random number is derived from all revealed values.
* **Risks:**
* **Dishonest Behavior:** Participants may choose not to reveal their values if the outcome is unfavorable.
* **Coordination:** Requires honest participation from multiple parties, which can be hard to guarantee.
:::info
There are other ways to generate randomness on-chain, for more information read the ["Public Randomness and Randomness Beacons"](https://a16zcrypto.com/posts/article/public-randomness-and-randomness-beacons/) article.
:::
## CoinFlip using Pragma VRF
Below is an implementation of a `CoinFlip` contract that utilizes a [Pragma Verifiable Random Function (VRF)](https://docs.pragma.build/v1/Resources/randomness/randomness) to generate random numbers on-chain.
* Players can flip a virtual coin and receive a random outcome of `Heads` or `Tails`
* The contract needs to be funded with enough ETH to perform the necessary operations, including paying fees to Pragma's Randomness Oracle which returns a random value
* When the coin is "flipped", the contract makes a call to the Randomness Oracle to request a random value and the `Flipped` event is emitted
* Randomness is generated off-chain, and then submitted to the contract using the `receive_random_words` callback
* Based on this random value, the contract determines whether the coin "landed" on `Heads` or on `Tails`, and the `Landed` event is emitted
```rust theme={null}
use starknet::ContractAddress;
#[starknet::interface]
pub trait ICoinFlip<TContractState> {
fn flip(ref self: TContractState);
}
// declares just the pragma_lib::abi::IRandomness.receive_random_words function
#[starknet::interface]
pub trait IPragmaVRF<TContractState> {
fn receive_random_words(
ref self: TContractState,
requestor_address: ContractAddress,
request_id: u64,
random_words: Span<felt252>,
calldata: Array<felt252>,
);
}
#[starknet::contract]
pub mod CoinFlip {
use core::num::traits::zero::Zero;
use starknet::{ContractAddress, get_caller_address, get_contract_address};
use starknet::storage::{
Map, StoragePointerReadAccess, StoragePathEntry, StoragePointerWriteAccess,
};
use pragma_lib::abi::{IRandomnessDispatcher, IRandomnessDispatcherTrait};
use openzeppelin_token::erc20::interface::{IERC20Dispatcher, IERC20DispatcherTrait};
#[storage]
struct Storage {
eth_dispatcher: IERC20Dispatcher,
flips: Map<u64, ContractAddress>,
nonce: u64,
randomness_contract_address: ContractAddress,
}
#[event]
#[derive(Drop, starknet::Event)]
pub enum Event {
Flipped: Flipped,
Landed: Landed,
}
#[derive(Drop, starknet::Event)]
pub struct Flipped {
pub flip_id: u64,
pub flipper: ContractAddress,
}
#[derive(Drop, starknet::Event)]
pub struct Landed {
pub flip_id: u64,
pub flipper: ContractAddress,
pub side: Side,
}
#[derive(Drop, Debug, PartialEq, Serde)]
pub enum Side {
Heads,
Tails,
}
pub mod Errors {
pub const CALLER_NOT_RANDOMNESS: felt252 = "Caller not randomness contract";
pub const INVALID_ADDRESS: felt252 = "Invalid address";
pub const INVALID_FLIP_ID: felt252 = "No flip with the given ID";
pub const REQUESTOR_NOT_SELF: felt252 = "Requestor is not self";
pub const TRANSFER_FAILED: felt252 = "Transfer failed";
}
pub const PUBLISH_DELAY: u64 = 1; // return the random value asap
pub const NUM_OF_WORDS: u64 = 1; // one random value is sufficient
pub const CALLBACK_FEE_LIMIT: u128 = 100_000_000_000_000; // 0.0001 ETH
pub const MAX_CALLBACK_FEE_DEPOSIT: u256 =
500_000_000_000_000; // CALLBACK_FEE_LIMIT * 5; needs to cover the Premium fee
#[constructor]
fn constructor(
ref self: ContractState,
randomness_contract_address: ContractAddress,
eth_address: ContractAddress,
) {
assert(randomness_contract_address.is_non_zero(), Errors::INVALID_ADDRESS);
assert(eth_address.is_non_zero(), Errors::INVALID_ADDRESS);
self.randomness_contract_address.write(randomness_contract_address);
self.eth_dispatcher.write(IERC20Dispatcher { contract_address: eth_address });
}
#[abi(embed_v0)]
impl CoinFlip of super::ICoinFlip<ContractState> {
/// The contract needs to be funded with some ETH in order for this function
/// to be callable. For simplicity, anyone can fund the contract.
fn flip(ref self: ContractState) {
let flip_id = self._request_my_randomness();
let flipper = get_caller_address();
self.flips.entry(flip_id).write(flipper);
self.emit(Event::Flipped(Flipped { flip_id, flipper }));
}
}
#[abi(embed_v0)]
impl PragmaVRF of super::IPragmaVRF<ContractState> {
fn receive_random_words(
ref self: ContractState,
requestor_address: ContractAddress,
request_id: u64,
random_words: Span<felt252>,
calldata: Array<felt252>,
) {
let caller = get_caller_address();
assert(
caller == self.randomness_contract_address.read(), Errors::CALLER_NOT_RANDOMNESS,
);
let this = get_contract_address();
assert(requestor_address == this, Errors::REQUESTOR_NOT_SELF);
self._process_coin_flip(request_id, random_words.at(0));
}
}
#[generate_trait]
impl Private of PrivateTrait {
fn _request_my_randomness(ref self: ContractState) -> u64 {
let randomness_contract_address = self.randomness_contract_address.read();
let randomness_dispatcher = IRandomnessDispatcher {
contract_address: randomness_contract_address,
};
let this = get_contract_address();
// Approve the randomness contract to transfer the callback deposit/fee
let eth_dispatcher = self.eth_dispatcher.read();
eth_dispatcher.approve(randomness_contract_address, MAX_CALLBACK_FEE_DEPOSIT);
let nonce = self.nonce.read();
// Request the randomness to be used to construct the winning combination
let request_id = randomness_dispatcher
.request_random(
nonce, this, CALLBACK_FEE_LIMIT, PUBLISH_DELAY, NUM_OF_WORDS, array![],
);
self.nonce.write(nonce + 1);
request_id
}
fn _process_coin_flip(ref self: ContractState, flip_id: u64, random_value: @felt252) {
let flipper = self.flips.entry(flip_id).read();
assert(flipper.is_non_zero(), Errors::INVALID_FLIP_ID);
let random_value: u256 = (*random_value).into();
let side = if random_value % 2 == 0 {
Side::Heads
} else {
Side::Tails
};
self.emit(Event::Landed(Landed { flip_id, flipper, side }));
}
}
}
```
# Simple storage
Source: https://docs.starknet.io/build/starknet-by-example/applications/simple-storage
In this example, we will use a SimpleStorage Cairo contract deployed on Starknet Sepolia Testnet and show how you can interact with the contract using Starknet-js.
## Writing SimpleStorage contract in Cairo
The SimpleStorage contract has only one purpose: storing a number. We want the users to interact with the stored number by **writing** to the currently stored number and **reading** the number in the contract.
We will use the following SimpleStorage contract. In the [Storage Variables](../basic/variables) page, you can find explanations for each component of the contract:
```cairo theme={null}
// [!include ~/listings/applications/simple_storage_starknetjs/src/storage.cairo:contract]
```
Because we want to interact with the get and set functions of the SimpleStorage contract using Starknet-js, we define the function signatures in `#[starknet::interface]`. The functions are defined under the macro `#[abi(embed_v0)]` where external functions are written.
Only deployed instances of the contract can be interacted with. You can refer to the [How to Deploy](/build/quickstart/hellostarknet) page. Note down the address of your contract, as it is needed for the following part.
## Interacting with SimpleStorage contract
We will interact with the SimpleStorage contract using Starknet-js. Firstly, create a new folder and inside the directory of the new folder, initialize the npm package (click Enter several items, you can skip adding the package info):
```bash [Terminal] theme={null}
npm init
```
Now, `package.json{:md}` file is created. Change the type of the package to a module.
```json theme={null}
"type": "module"
```
Let's add Starknet-js as a dependency:
```bash [Terminal] theme={null}
npm install starknet@next
```
Create a file named `index.js{:md}` where we will write JavaScript code to interact with our contract. Let's start our code by importing from Starknet-js, and from other libraries we will need:
```js theme={null}
// [!include ~/listings/applications/simple_storage_starknetjs/index.js:imports]
```
Let's create our provider object, and add our account address as a constant variable. We need the provider in order to send our queries and transactions to a Starknet node that is connected to the Starknet network:
```js theme={null}
// [!include ~/listings/applications/simple_storage_starknetjs/index.js:provider]
const accountAddress = // 'PASTE_ACCOUNT_ADDRESS_HERE';
```
The next step is creating an `Account` object that will be used to sign transactions, so we need to import the account private key. You can access it directly from your keystore with the following command using Starkli:
```bash [Terminal] theme={null}
starkli signer keystore inspect-private /path/to/starkli-wallet/keystore.json --raw
```
Create a `.env{:md}` file in your project folder, and paste your private key as shown in the following line:
```bash [Terminal] theme={null}
// [!include ~/listings/applications/simple_storage_starknetjs/.env.example]
```
:::warning
Using `.env{:md}` files is not recommended for production environments, please use `.env{:md}` files only for development purposes! It is HIGHLY recommended to add `.gitignore{:md}`, and include your .env file there if you will be pushing your project to GitHub.
:::
Now, import your private key from the environment variables and create your Account object.
```js theme={null}
const accountAddress = // 'PASTE_ACCOUNT_PUBLIC_ADDRESS_HERE';
// [!include ~/listings/applications/simple_storage_starknetjs/index.js:account]
```
Now, let's create a Contract object in order to interact with our contract. In order to create the Contract object, we need the ABI and the address of our contract. The ABI contains information about what kind of data structures and functions there are in our contract so that we can interact with them using SDKs like Starknet-js.
We will copy `./target/simple_storage_SimpleStorage.contract_class.json{:md}` to `abi.json{:md}` in the Scarb project folder. The beginning of the content of the ABI file should look like this:
```json theme={null}
{"sierra_program":["0x1","0x5","0x0","0x2","0x6","0x3","0x98","0x68","0x18", //...
```
We can then create the Account object and the Contract object in our `index.js{:md}` file:
```js theme={null}
const contractAddress = 'PASTE_CONTRACT_ADDRESS_HERE';
// [!include ~/listings/applications/simple_storage_starknetjs/index.js:contract]
```
The setup is finished! By calling the `fn get(self: @ContractState) -> u128` function, we will be able to read the `stored_data` variable from the contract:
```js theme={null}
// [!include ~/listings/applications/simple_storage_starknetjs/index.js:get]
```
In order to run your code, run the command `node index.js{:md}` in your project directory. After a short amount of time, you should see a "0" as the stored data.
Now, we will set a new number to the `stored_data` variable by calling the `fn set(self: @mut ContractState, new_data: u128)` function. This is an `INVOKE{:md}` transaction, so we need to sign the transaction with our account's private key and pass along the calldata.
The transaction is signed and broadcasted to the network and it can takes a few seconds for the transaction to be confirmed.
```js theme={null}
// [!include ~/listings/applications/simple_storage_starknetjs/index.js:set]
```
# Simple DeFi vault
Source: https://docs.starknet.io/build/starknet-by-example/applications/simple-vault
This is the Cairo adaptation of the [Solidity by Examp프로젝트로 돌아가기