Skip to content

Lottery smart contracts #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: starter-code
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Lottery Smart Contract in Stacks

## Introduction
This is a lottery smart contract in Stacks. Players transfer specific lottery fee(STX) to participate current round lottery when the lottery is open.

And then the smart contract owner can close the lottery and calculate the winner by sending a transation to this smart contract. This smart contract use the vrf-seed of blockchain to generate a pseudorandom number, which is used for calculate the winner of this round lottery.

After the winner is calculated, it transfers the whole jackpots(STX) in this round to the winner. And then the smart contract owner can open the lottery again, starting next round.

To mock the above process, run
```shell
cd lottery-contracts
clarinet run --allow-wallets --allow-read --allow-write mock/run-lottery-mock-script.ts
```

<img width="931" alt="CleanShot 2022-08-27 at 09 39 08@2x" src="https://user-images.githubusercontent.com/17610879/187009322-4387609e-4bd4-47a9-97a5-3fc7267fd85c.png">

## Details of some login point
### players have to pay for the entry fee
Actually players have to pay for the entry fee. When they pay for the lottery fee(variable `fee`) to participate this round, which the entry fee is included in. And the entry fee is up to the variable `entry-fee-rate`. Both `fee` and `entry-fee-rate` can be update by the constract owner, but only when the lottery state in `lottery-state-winner-announced`. Since they shouldn't be updated bwteen the time the lottery is open and calculated the winner.
(To more detail, see contract `lottery` method: `get-fee` / `get-entry-fee-rate` / `get-entry-fee` / `update-fee` / `update-entry-fee-rate`)

### Jackpot
The The jackpot for every round is the full fee from the players minus the entry fee. As once as the winner is calculated, the contract transfers the jackpot to this winner address.
(To more detail, see contract `lottery` method: `get-jackpots`)

### Calculate the winner of each round
- **pseudorandom number**
This contract use the vrf-seed of blockchain to generate a pseudorandom number, which is use to come out a winner. Since the generator algorithm, it only supports to generate the random number between 0(inclusive) to 256(exclusive), and the random number between 0 to 256 appears with equal probability.
- **players have the same probability of winning**
Winner is the players whose index equals to the remainder of dividing a random number by the count of players.
Since only when the random number between 0 to 256, it appears with equal probability, so to make all the players have the same probability of winning, the contract do these things:
- Number of players per round cannot exceed 256
- When the number of players less than 256, the ramdom number must less than `Y`, and `Y` is the largest integer satisfying `Y * (the number of players) < 256`. For example, when the number of players is 100, the ramdom number mush less than 200. That is to ensure every players have the bassically equal probability of winning.
- But so it have a probability that the lottery cannot come out a winner since the ramdom number may not fit into. When it happens, the smart contract refund the fee except the entry fee to all the players.
(To more detail, see contract `pseudorandom-generator` methond `get-random-number`)
- **Auth permissions**
Except the method `participate-in-lottery` offer to users to participate the lottery, other methods making transations are all only available to the contract owner

## Others
This lottery use a pseudorandom number generated by blockchain block info. It cannot satisfy both security and on-chain. But it's quite funny to write this contracts to learn more about the Stacks and Clarity language.

## Reference
[Pointer tutorial: Build a Dex with Stacks](https://www.pointer.gg/tutorials/build-a-dex-with-stacks/56abb3a4-05c1-4608-b096-f82189e9f759)
[How To Create Random Numbers in Clarity](https://app.sigle.io/friendsferdinand.id.stx/fAyQTanTRkIDXtqFPpoGO)
[Stacks document](https://docs.stacks.co/docs/intro)
[Clarity of Mind](https://book.clarity-lang.org/title-page.html)
5 changes: 5 additions & 0 deletions lottery-contracts/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
**/settings/Mainnet.toml
**/settings/Testnet.toml
.requirements/
history.txt
.vscode/
23 changes: 23 additions & 0 deletions lottery-contracts/Clarinet.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@

[project]
name = "lottery-contracts"
authors = []
telemetry = false
cache_dir = "./.requirements"

[contracts.lottery]
path = "contracts/lottery.clar"
[contracts.pseudorandom-generator]
path = "contracts/pseudorandom-generator.clar"

[repl.analysis]
passes = ["check_checker"]
check_checker = { trusted_sender = false, trusted_caller = false, callee_filter = false }

# Check-checker settings:
# trusted_sender: if true, inputs are trusted after tx_sender has been checked.
# trusted_caller: if true, inputs are trusted after contract-caller has been checked.
# callee_filter: if true, untrusted data may be passed into a private function without a
# warning, if it gets checked inside. This check will also propagate up to the
# caller.
# More informations: https://www.hiro.so/blog/new-safety-checks-in-clarinet
236 changes: 236 additions & 0 deletions lottery-contracts/contracts/lottery.clar
Original file line number Diff line number Diff line change
@@ -0,0 +1,236 @@
;; --------------------------- errors define -----------------------------------------
(define-constant err-owner-only (err u100))

(define-constant err-lotery-is-not-open (err u200))
(define-constant err-lottery-is-not-winner-announced (err u201))
(define-constant err-lottery-is-not-closed (err u202))

(define-constant err-fee-can-not-be-zero (err u300))
(define-constant err-fee-rate-can-not-be-zero (err u301))
(define-constant err-withdraw-amount-exceed (err u302))

(define-constant err-players-is-full (err u400))
;; --------------------------- errors define -----------------------------------------

;; --------------------------- constants define -----------------------------------------
(define-constant contract-owner tx-sender)
(define-constant contract-address (as-contract tx-sender))
(define-constant max-players-size u256) ;;exclusive
;; --------------------------- constants define -----------------------------------------

;; --------------------------- variables define -----------------------------------------
;; the fee for one lottery
(define-data-var fee uint u100000)
;; entry fee rate, entry fee = fee * entry-fee-rate / 10000
(define-data-var entry-fee-rate uint u1000) ;; 10%
;; total balance of this round
;; (define-data-var total-balance uint u0)

(define-constant lottery-state-open "lottery-state-open")
(define-constant lottery-state-closed "lottery-state-closed")
(define-constant lottery-state-winner-announced "lottery-state-winner-announced")
;; the current state of this round lottery
(define-data-var lottery-state (string-ascii 30) lottery-state-open)

;; to store the players who perticipate this round lottery
(define-data-var players (list 256 principal) (list))

(define-data-var lasted-winner (optional principal) none)
(define-data-var lasted-jackpots uint u0)
;; --------------------------- variables define -----------------------------------------

(define-read-only (get-fee)
(var-get fee)
)

;; To update the fee
;; only available to the contract owner and under the state "lottery-state-winner-announced"
(define-public (update-fee (to-fee uint))
(begin
(asserts! (is-eq tx-sender contract-owner) err-owner-only)
(asserts! (is-eq (var-get lottery-state) lottery-state-winner-announced) err-lottery-is-not-winner-announced)
(asserts! (> to-fee u0) err-fee-can-not-be-zero)

(ok (var-set fee to-fee))
)
)

(define-read-only (get-entry-fee-rate)
(var-get entry-fee-rate)
)

(define-read-only (get-entry-fee)
(let (
(f (var-get fee))
(f-rate (var-get entry-fee-rate))
(enter-fee (/ (* f f-rate) u10000))
)
enter-fee
)
)

;; To update the entry fee rate of fee
;; only available to the contract owner and under the state "lottery-state-winner-announced"
(define-public (update-entry-fee-rate (to-rate uint))
(begin
(asserts! (is-eq tx-sender contract-owner) err-owner-only)
(asserts! (is-eq (var-get lottery-state) lottery-state-winner-announced) err-lottery-is-not-winner-announced)
(asserts! (> to-rate u0) err-fee-rate-can-not-be-zero)

(ok (var-set entry-fee-rate to-rate))
)
)

(define-read-only (get-lasted-winner-info)
{
winner: (var-get lasted-winner),
jackpots: (var-get lasted-jackpots)
}
)

;; Get the amount of jackpots
(define-read-only (get-jackpots)
;; Due to the entry fee
;; so jackpots = (1 - entry-fee-rate / 10000) * fee * (len players)
(* (len (var-get players)) (- (var-get fee) (get-entry-fee)))
)

(define-read-only (get-players)
(var-get players)
)

(define-read-only (get-lottery-state)
(var-get lottery-state)
)

;; To open the lottery
;; only available to the contract owner
;; and only if the lottery is on the "lottery-state-winner-announced" state
;; then it could turn to the "lottery-state-open" state
(define-public (open-lottery)
(begin
(asserts! (is-eq tx-sender contract-owner) err-owner-only)
(asserts! (is-eq (var-get lottery-state) lottery-state-winner-announced) err-lottery-is-not-winner-announced)

(ok (var-set lottery-state lottery-state-open))
)
)

;; To end the lottery
;; only available to the contract owner
;; and only if the lottery is on the "lottery-state-open" state
;; then it could turn to the "lottery-state-closed" state
(define-public (end-lottery)
(begin
(asserts! (is-eq tx-sender contract-owner) err-owner-only)
(asserts! (is-eq (var-get lottery-state) lottery-state-open) err-lotery-is-not-open)

(ok (var-set lottery-state lottery-state-closed))
)
)

;; To calculate the winner of this round lottery
;; only available to the contract owner
;; and only if the lottery is on the "lottery-state-closed" state
;; then it could calculate the winner
(define-public (calculate-lottery-winner)
(begin
(asserts! (is-eq tx-sender contract-owner) err-owner-only)
(asserts! (is-eq (var-get lottery-state) lottery-state-closed) err-lottery-is-not-closed)

(let (
;; calculate the winner
(players-count (len (var-get players)))
(winer-index (unwrap-panic (contract-call? .pseudorandom-generator get-random-number players-count)))
(winner (get-player-by-index winer-index))
(jackpots (get-jackpots))
)

(try! (transfer-jackpots-to-winner winner jackpots))

(var-set lasted-winner winner)
(var-set lasted-jackpots jackpots)
(var-set lottery-state lottery-state-winner-announced)
;; empty the players list, wait to next round
(var-set players (list))

(ok {
winner: winner,
players: (var-get players),
jackspots: jackpots
})
)
)
)

(define-private (get-player-by-index (index int))
(if (> index -1)
(element-at (var-get players) (to-uint index))
none
)
)

;; To transfer jackpots to the winner
;; or when it fail to calculate the winner since it fail to get a random number
;; the jackspots will refund to every players
(define-private (transfer-jackpots-to-winner (winner (optional principal)) (jackpots uint))
(if (is-none winner)
;; if there's no winer, refund to evenry players
(begin
(map refund-to-player (var-get players))
(ok true) ;; just to make the the returned match the 'if'
)
;; if there is a winer, transfer to the winner
(as-contract (stx-transfer? jackpots contract-address (unwrap-panic winner)))
)
)

(define-private (refund-to-player (player principal))
(
let (
(enter-fee (get-entry-fee))
(refund-amount (- (var-get fee) enter-fee))
)

(as-contract (stx-transfer? refund-amount contract-address player))
)
)

(define-read-only (get-total-avaliable-entry-fee)
(begin
(asserts! (is-eq tx-sender contract-owner) err-owner-only)
(let (
(players-count (len (var-get players)))
(lottery-fee (var-get fee))
(total-balance (stx-get-balance contract-address))
;; total-avaliable-entry-fee = total-balance of this contract - current lottery total fee
;; and current lottery total fee = count of players * fee for each lotery
(total-avaliable-entry-fee (- total-balance (* players-count lottery-fee)))
)

(ok total-avaliable-entry-fee)
)
)
)

(define-public (withdraw-avaliable-entry-fee (withdraw-amount uint) (to-who principal))
(begin
(asserts! (is-eq tx-sender contract-owner) err-owner-only)
(asserts! (< withdraw-amount (unwrap-panic (get-total-avaliable-entry-fee))) err-withdraw-amount-exceed)
;; withdraw the total avaliable entry fee to a specific address
;; to-who is unchecked, we allow the contract owner to transfer whoever they like
;; #[allow(unchecked_data)]
(as-contract (stx-transfer? withdraw-amount contract-owner to-who))
)
)

;; Custom function to participate in the lottery
(define-public (participate-in-lottery)
(begin
(asserts! (< (len (var-get players)) max-players-size) err-players-is-full)
;; transfer lottery fee
(try! (stx-transfer? (var-get fee) tx-sender contract-address))
(var-set players (unwrap-panic (as-max-len? (append (var-get players) tx-sender) u256)))
(ok (var-get players))
)
)
76 changes: 76 additions & 0 deletions lottery-contracts/contracts/pseudorandom-generator.clar
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
(define-constant err-random-number-over-bound (err u100))

(define-constant max-random-number-bound u256) ;;exclusive

;; cause there's no anonymous function in clarity
;; and cannot define a function in the middle of a function body
;; so I have to use a var to store the temp value for the filter function
(define-data-var filter-bound-temp uint u256)

;; use to convert hex to uint
(define-constant BUFF_TO_BYTE (list
0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09 0x0a 0x0b 0x0c 0x0d 0x0e 0x0f
0x10 0x11 0x12 0x13 0x14 0x15 0x16 0x17 0x18 0x19 0x1a 0x1b 0x1c 0x1d 0x1e 0x1f
0x20 0x21 0x22 0x23 0x24 0x25 0x26 0x27 0x28 0x29 0x2a 0x2b 0x2c 0x2d 0x2e 0x2f
0x30 0x31 0x32 0x33 0x34 0x35 0x36 0x37 0x38 0x39 0x3a 0x3b 0x3c 0x3d 0x3e 0x3f
0x40 0x41 0x42 0x43 0x44 0x45 0x46 0x47 0x48 0x49 0x4a 0x4b 0x4c 0x4d 0x4e 0x4f
0x50 0x51 0x52 0x53 0x54 0x55 0x56 0x57 0x58 0x59 0x5a 0x5b 0x5c 0x5d 0x5e 0x5f
0x60 0x61 0x62 0x63 0x64 0x65 0x66 0x67 0x68 0x69 0x6a 0x6b 0x6c 0x6d 0x6e 0x6f
0x70 0x71 0x72 0x73 0x74 0x75 0x76 0x77 0x78 0x79 0x7a 0x7b 0x7c 0x7d 0x7e 0x7f
0x80 0x81 0x82 0x83 0x84 0x85 0x86 0x87 0x88 0x89 0x8a 0x8b 0x8c 0x8d 0x8e 0x8f
0x90 0x91 0x92 0x93 0x94 0x95 0x96 0x97 0x98 0x99 0x9a 0x9b 0x9c 0x9d 0x9e 0x9f
0xa0 0xa1 0xa2 0xa3 0xa4 0xa5 0xa6 0xa7 0xa8 0xa9 0xaa 0xab 0xac 0xad 0xae 0xaf
0xb0 0xb1 0xb2 0xb3 0xb4 0xb5 0xb6 0xb7 0xb8 0xb9 0xba 0xbb 0xbc 0xbd 0xbe 0xbf
0xc0 0xc1 0xc2 0xc3 0xc4 0xc5 0xc6 0xc7 0xc8 0xc9 0xca 0xcb 0xcc 0xcd 0xce 0xcf
0xd0 0xd1 0xd2 0xd3 0xd4 0xd5 0xd6 0xd7 0xd8 0xd9 0xda 0xdb 0xdc 0xdd 0xde 0xdf
0xe0 0xe1 0xe2 0xe3 0xe4 0xe5 0xe6 0xe7 0xe8 0xe9 0xea 0xeb 0xec 0xed 0xee 0xef
0xf0 0xf1 0xf2 0xf3 0xf4 0xf5 0xf6 0xf7 0xf8 0xf9 0xfa 0xfb 0xfc 0xfd 0xfe 0xff
))

(define-private (get-vrf)
(unwrap-panic
(get-block-info? vrf-seed (- block-height u1))
)
)

;; only generate random number between [0, 256)
;; output: ok(random-number) or ok(-1) when it return -1 means it fail to generate a random number
(define-public (get-random-number (random-number-bound uint))
(begin
(asserts! (<= random-number-bound max-random-number-bound) err-random-number-over-bound)
(let ((random-number-list (unwrap-panic (get-random-number-list random-number-bound))))
(if (> (len random-number-list) u0)
(ok (to-int (mod (unwrap-panic (element-at random-number-list u0)) random-number-bound)))
(ok -1)
)
)
)
)

(define-public (get-random-number-list (random-number-bound uint))
;; #[allow(unchecked_data)]
(begin
(let (
(block-info-vrf (get-vrf))
(vrf-number-list (map convert-to-int block-info-vrf))
;; In order to ensure that the probability of random numbers is equal basically,
;; the numbers which is greater than Y in vrf are removed,
;; and Y is the largest integer satisfying Y * random-number-bound < max-random-number-bound
(filter-bound (* (/ max-random-number-bound random-number-bound) random-number-bound))
)
(begin
(var-set filter-bound-temp filter-bound)
(ok (filter is-under-bound vrf-number-list))
))
)
)

(define-private (convert-to-int (hex (buff 1)))
(unwrap-panic
(index-of BUFF_TO_BYTE hex)
)
)

(define-private (is-under-bound (number uint))
(< number (var-get filter-bound-temp))
)
Loading