-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathlib.rs
More file actions
454 lines (397 loc) · 15 KB
/
lib.rs
File metadata and controls
454 lines (397 loc) · 15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
#![cfg_attr(not(feature = "std"), no_std)]
mod errors;
use ink_lang as ink;
#[ink::contract]
pub mod button_game {
use access_control::{roles::Role, traits::AccessControlled, ACCESS_CONTROL_PUBKEY};
use game_token::MINT_SELECTOR;
use ink_env::{
call::{build_call, Call, ExecutionInput, Selector},
CallFlags, DefaultEnvironment, Error as InkEnvError,
};
use ink_lang::{codegen::EmitEvent, reflect::ContractEventBase};
use ink_prelude::{format, vec};
use ink_storage::traits::{PackedLayout, SpreadLayout};
use marketplace::RESET_SELECTOR as MARKETPLACE_RESET_SELECTOR;
use openbrush::contracts::psp22::PSP22Error;
use scale::{Decode, Encode};
use ticket_token::{BALANCE_OF_SELECTOR, TRANSFER_FROM_SELECTOR, TRANSFER_SELECTOR};
use crate::errors::GameError;
/// Result type
type ButtonResult<T> = core::result::Result<T, GameError>;
/// Event type
type Event = <ButtonGame as ContractEventBase>::Type;
/// Event emitted when TheButton is created
#[ink(event)]
#[derive(Debug)]
pub struct ButtonCreated {
#[ink(topic)]
reward_token: AccountId,
#[ink(topic)]
ticket_token: AccountId,
start: BlockNumber,
deadline: BlockNumber,
}
/// Event emitted when TheButton is pressed
#[ink(event)]
#[derive(Debug)]
pub struct ButtonPressed {
#[ink(topic)]
by: AccountId,
when: BlockNumber,
score: Balance,
}
/// Event emitted when the finished game is reset and pressiah is rewarded
#[ink(event)]
#[derive(Debug)]
pub struct GameReset {
when: BlockNumber,
}
/// Scoring strategy indicating what kind of reward users get for pressing the button
#[derive(Debug, Encode, Decode, Clone, Copy, SpreadLayout, PackedLayout, PartialEq, Eq)]
#[cfg_attr(
feature = "std",
derive(scale_info::TypeInfo, ink_storage::traits::StorageLayout)
)]
pub enum Scoring {
/// Pressing the button as soon as possible gives the highest reward
EarlyBirdSpecial,
/// Pressing the button as late as possible gives the highest reward
BackToTheFuture,
/// The reward increases linearly with the number of participants
ThePressiahCometh,
}
/// Game contracts storage
#[ink(storage)]
pub struct ButtonGame {
/// How long does TheButton live for?
pub button_lifetime: BlockNumber,
/// stores the last account that pressed The Button
pub last_presser: Option<AccountId>,
/// block number of the last press, set to current block number at button start/reset
pub last_press: BlockNumber,
/// sum of rewards paid to players in the current iteration
pub total_rewards: u128,
/// counter for the number of presses
pub presses: u128,
/// AccountId of the PSP22 ButtonToken instance on-chain
pub reward_token: AccountId,
/// Account ID of the ticket token
pub ticket_token: AccountId,
/// access control contract
pub access_control: AccountId,
/// ticket marketplace contract
pub marketplace: AccountId,
/// scoring strategy
pub scoring: Scoring,
/// current round number
pub round: u64,
}
impl AccessControlled for ButtonGame {
type ContractError = GameError;
}
impl ButtonGame {
#[ink(constructor)]
pub fn new(
ticket_token: AccountId,
reward_token: AccountId,
marketplace: AccountId,
button_lifetime: BlockNumber,
scoring: Scoring,
) -> Self {
let caller = Self::env().caller();
let code_hash = Self::env()
.own_code_hash()
.expect("Called new on a contract with no code hash");
let required_role = Role::Initializer(code_hash);
let access_control = AccountId::from(ACCESS_CONTROL_PUBKEY);
match ButtonGame::check_role(access_control, caller, required_role) {
Ok(_) => Self::init(
ticket_token,
reward_token,
marketplace,
button_lifetime,
scoring,
),
Err(why) => panic!("Could not initialize the contract {:?}", why),
}
}
/// Returns the current deadline
///
/// Deadline is the block number at which the game will end if there are no more participants
#[ink(message)]
pub fn deadline(&self) -> BlockNumber {
self.last_press + self.button_lifetime
}
/// Returns the curent round number
#[ink(message)]
pub fn round(&self) -> u64 {
self.round
}
/// Returns the buttons status
#[ink(message)]
pub fn is_dead(&self) -> bool {
self.env().block_number() > self.deadline()
}
/// Returns the last player who pressed the button.
/// If button is dead, this is The Pressiah.
#[ink(message)]
pub fn last_presser(&self) -> Option<AccountId> {
self.last_presser
}
/// Returns the current access control contract address
#[ink(message)]
pub fn access_control(&self) -> AccountId {
self.access_control
}
/// Returns address of the game's reward token
#[ink(message)]
pub fn reward_token(&self) -> AccountId {
self.reward_token
}
/// Returns address of the game's ticket token
#[ink(message)]
pub fn ticket_token(&self) -> AccountId {
self.ticket_token
}
/// Returns the address of the marketplace for exchanging this game's rewards for tickets.
#[ink(message)]
pub fn marketplace(&self) -> AccountId {
self.marketplace
}
/// Returns own code hash
#[ink(message)]
pub fn code_hash(&self) -> ButtonResult<Hash> {
self.env()
.own_code_hash()
.map_err(|_| GameError::CantRetrieveOwnCodeHash)
}
/// Presses the button
///
/// If called on alive button, instantaneously mints reward tokens to the caller
#[ink(message)]
pub fn press(&mut self) -> ButtonResult<()> {
if self.is_dead() {
return Err(GameError::AfterDeadline);
}
let caller = self.env().caller();
let now = Self::env().block_number();
let this = self.env().account_id();
// transfers 1 ticket token from the caller to self
// tx will fail if user did not give allowance to the game contract
// or does not have enough balance
self.transfer_ticket(caller, this, 1u128)??;
let score = self.score(now);
// mints reward tokens to pay out the reward
// contract needs to have a Minter role on the reward token contract
self.mint_reward(caller, score)??;
self.presses += 1;
self.last_presser = Some(caller);
self.last_press = now;
self.total_rewards += score;
Self::emit_event(
self.env(),
Event::ButtonPressed(ButtonPressed {
by: caller,
when: now,
score,
}),
);
Ok(())
}
/// Resets the game
///
/// Erases the storage and pays award to the Pressiah
/// Can be called by any account on behalf of a player
/// Can only be called after button's deadline
#[ink(message)]
pub fn reset(&mut self) -> ButtonResult<()> {
self.ensure_dead()?;
self.reward_pressiah()?;
self.reset_state()?;
self.transfer_tickets_to_marketplace()?;
self.reset_marketplace()
}
/// Sets new access control contract address
///
/// Should only be called by the contract owner
/// Implementing contract is responsible for setting up proper AccessControl
#[ink(message)]
pub fn set_access_control(&mut self, new_access_control: AccountId) -> ButtonResult<()> {
let caller = self.env().caller();
let this = self.env().account_id();
let required_role = Role::Owner(this);
ButtonGame::check_role(self.access_control, caller, required_role)?;
self.access_control = new_access_control;
Ok(())
}
/// Terminates the contract
///
/// Should only be called by the contract Owner
#[ink(message)]
pub fn terminate(&mut self) -> ButtonResult<()> {
let caller = self.env().caller();
let this = self.env().account_id();
let required_role = Role::Owner(this);
ButtonGame::check_role(self.access_control, caller, required_role)?;
self.env().terminate_contract(caller)
}
//===================================================================================================
fn init(
ticket_token: AccountId,
reward_token: AccountId,
marketplace: AccountId,
button_lifetime: BlockNumber,
scoring: Scoring,
) -> Self {
let now = Self::env().block_number();
let deadline = now + button_lifetime;
let contract = Self {
access_control: AccountId::from(ACCESS_CONTROL_PUBKEY),
button_lifetime,
reward_token,
ticket_token,
marketplace,
last_press: now,
scoring,
last_presser: None,
presses: 0,
total_rewards: 0,
round: 0,
};
Self::emit_event(
Self::env(),
Event::ButtonCreated(ButtonCreated {
start: now,
deadline,
ticket_token,
reward_token,
}),
);
contract
}
fn reset_state(&mut self) -> ButtonResult<()> {
let now = self.env().block_number();
self.presses = 0;
self.last_presser = None;
self.last_press = now;
self.total_rewards = 0;
self.round.checked_add(1).ok_or(GameError::Arithmethic)?;
Self::emit_event(self.env(), Event::GameReset(GameReset { when: now }));
Ok(())
}
fn reward_pressiah(&self) -> ButtonResult<()> {
if let Some(pressiah) = self.last_presser {
let reward = self.pressiah_score();
self.mint_reward(pressiah, reward)??;
};
Ok(())
}
fn ensure_dead(&self) -> ButtonResult<()> {
if !self.is_dead() {
Err(GameError::BeforeDeadline)
} else {
Ok(())
}
}
fn transfer_tickets_to_marketplace(&self) -> ButtonResult<()> {
build_call::<DefaultEnvironment>()
.call_type(Call::new().callee(self.ticket_token))
.exec_input(
ExecutionInput::new(Selector::new(TRANSFER_SELECTOR))
.push_arg(self.marketplace)
.push_arg(self.held_tickets()?)
.push_arg::<vec::Vec<u8>>(vec![]),
)
.call_flags(CallFlags::default().set_allow_reentry(true))
.returns::<Result<(), PSP22Error>>()
.fire()??;
Ok(())
}
fn held_tickets(&self) -> ButtonResult<Balance> {
let result = build_call::<DefaultEnvironment>()
.call_type(Call::new().callee(self.ticket_token))
.exec_input(
ExecutionInput::new(Selector::new(BALANCE_OF_SELECTOR))
.push_arg(self.env().account_id()),
)
.returns::<Balance>()
.fire()?;
Ok(result)
}
fn reset_marketplace(&self) -> ButtonResult<()> {
build_call::<DefaultEnvironment>()
.call_type(Call::new().callee(self.marketplace))
.exec_input(ExecutionInput::new(Selector::new(
MARKETPLACE_RESET_SELECTOR,
)))
.returns::<Result<(), PSP22Error>>()
.fire()??;
Ok(())
}
fn check_role(access_control: AccountId, account: AccountId, role: Role) -> ButtonResult<()>
where
Self: AccessControlled,
{
<Self as AccessControlled>::check_role(
access_control,
account,
role,
|why: InkEnvError| {
GameError::InkEnvError(format!("Calling access control has failed: {:?}", why))
},
GameError::MissingRole,
)
}
fn score(&self, now: BlockNumber) -> Balance {
match self.scoring {
Scoring::EarlyBirdSpecial => self.deadline().saturating_sub(now) as Balance,
Scoring::BackToTheFuture => now.saturating_sub(self.last_press) as Balance,
Scoring::ThePressiahCometh => (self.presses + 1) as Balance,
}
}
fn pressiah_score(&self) -> Balance {
(self.total_rewards / 4) as Balance
}
fn transfer_ticket(
&self,
from: AccountId,
to: AccountId,
value: Balance,
) -> Result<Result<(), PSP22Error>, InkEnvError> {
build_call::<DefaultEnvironment>()
.call_type(Call::new().callee(self.ticket_token))
.exec_input(
ExecutionInput::new(Selector::new(TRANSFER_FROM_SELECTOR))
.push_arg(from)
.push_arg(to)
.push_arg(value)
.push_arg::<vec::Vec<u8>>(vec![]),
)
.call_flags(CallFlags::default().set_allow_reentry(true))
.returns::<Result<(), PSP22Error>>()
.fire()
}
fn mint_reward(
&self,
to: AccountId,
amount: Balance,
) -> Result<Result<(), PSP22Error>, InkEnvError> {
build_call::<DefaultEnvironment>()
.call_type(Call::new().callee(self.reward_token))
.exec_input(
ExecutionInput::new(Selector::new(MINT_SELECTOR))
.push_arg(to)
.push_arg(amount),
)
.returns::<Result<(), PSP22Error>>()
.fire()
}
fn emit_event<EE>(emitter: EE, event: Event)
where
EE: EmitEvent<ButtonGame>,
{
emitter.emit_event(event);
}
}
}