-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathmod.rs
619 lines (478 loc) · 16.1 KB
/
mod.rs
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
use near_sdk::{
env, near, test_utils::VMContextBuilder, testing_env, AccountId, BorshStorageKey,
PanicOnDefault,
};
use near_sdk_contract_tools::{
escrow::Escrow, migrate::MigrateHook, owner::Owner, pause::Pause, rbac::Rbac,
standard::nep297::Event, Escrow, Migrate, Owner, Pause, Rbac,
};
mod escrow;
mod event;
mod migrate;
mod owner;
mod pause;
mod standard;
mod my_event {
use near_sdk::{serde::Serialize, AccountId};
use near_sdk_contract_tools::Nep297;
#[derive(Serialize, Nep297)]
#[serde(crate = "near_sdk::serde")]
#[nep297(standard = "x-myevent", version = "1.0.0", rename = "snake_case")]
pub struct ValueChanged {
pub from: u32,
pub to: u32,
}
#[derive(Serialize, Nep297)]
#[serde(crate = "near_sdk::serde")]
#[nep297(standard = "x-myevent", version = "1.0.0", rename = "snake_case")]
pub struct PermissionGranted {
pub to: AccountId,
}
}
#[derive(BorshStorageKey)]
#[near]
enum StorageKey {
Owner,
Pause,
Rbac,
}
#[derive(BorshStorageKey)]
#[near]
pub enum Role {
CanPause,
CanSetValue,
}
mod integration {
use super::*;
#[derive(Owner, Pause, Rbac, Escrow, PanicOnDefault)]
#[owner(storage_key = "StorageKey::Owner")]
#[pause(storage_key = "StorageKey::Pause")]
#[rbac(storage_key = "StorageKey::Rbac", roles = "Role")]
#[escrow(storage_key = "StorageKey::Owner", id = "u64", state = "String")]
#[near(contract_state)]
pub struct Integration {
pub value: u32,
}
#[allow(clippy::needless_pass_by_value)]
#[near]
impl Integration {
#[init]
pub fn new(owner_id: AccountId) -> Self {
let mut contract = Self { value: 0 };
Owner::init(&mut contract, &owner_id);
contract.add_role(&owner_id, &Role::CanSetValue);
contract.add_role(&owner_id, &Role::CanPause);
contract
}
pub fn add_value_setter(&mut self, account_id: AccountId) {
Self::require_owner();
self.add_role(&account_id, &Role::CanSetValue);
my_event::PermissionGranted { to: account_id }.emit();
}
pub fn set_value(&mut self, value: u32) {
Self::require_unpaused();
Self::require_role(&Role::CanSetValue);
let old = self.value;
self.value = value;
my_event::ValueChanged {
from: old,
to: value,
}
.emit();
}
pub fn pause(&mut self) {
Self::require_role(&Role::CanPause);
Pause::pause(self);
}
pub fn unpause(&mut self) {
Self::require_role(&Role::CanPause);
Pause::unpause(self);
}
pub fn get_value(&self) -> u32 {
self.value
}
pub fn lock_data(&mut self, id: u64, data: String) {
self.lock(&id, &data);
}
pub fn unlock_data(&mut self, id: u64) {
self.unlock(&id, |data| !data.is_empty());
}
pub fn check_is_locked(&self, id: u64) -> bool {
self.is_locked(&id)
}
}
}
use integration::Integration;
#[derive(Migrate, Owner, Pause, Rbac, PanicOnDefault)]
#[migrate(from = "Integration")]
#[owner(storage_key = "StorageKey::Owner")]
#[pause(storage_key = "StorageKey::Pause")]
#[rbac(storage_key = "StorageKey::Rbac", roles = "Role")]
#[near(contract_state)]
struct MigrateIntegration {
pub new_value: String,
pub moved_value: u32,
}
impl MigrateHook for MigrateIntegration {
fn on_migrate(old: Integration) -> Self {
Self::require_owner();
Self::require_unpaused();
Self {
new_value: "my string".to_string(),
moved_value: old.value,
}
}
}
#[near]
impl MigrateIntegration {
pub fn add_value_setter(&mut self, account_id: AccountId) {
Self::require_owner();
self.add_role(&account_id, &Role::CanSetValue);
my_event::PermissionGranted { to: account_id }.emit();
}
pub fn set_value(&mut self, value: u32) {
Self::require_unpaused();
Self::require_role(&Role::CanSetValue);
let old = self.moved_value;
self.moved_value = value;
my_event::ValueChanged {
from: old,
to: value,
}
.emit();
}
pub fn pause(&mut self) {
Self::require_role(&Role::CanPause);
Pause::pause(self);
}
pub fn unpause(&mut self) {
Self::require_role(&Role::CanPause);
Pause::unpause(self);
}
pub fn get_value(&self) -> u32 {
self.moved_value
}
}
#[test]
fn integration() {
let owner: AccountId = "owner".parse().unwrap();
let alice: AccountId = "alice".parse().unwrap();
let context = VMContextBuilder::new()
.predecessor_account_id(owner.clone())
.build();
testing_env!(context);
let mut c = Integration::new(owner.clone());
c.set_value(5);
assert_eq!(c.get_value(), 5);
c.add_value_setter(alice.clone());
let context = VMContextBuilder::new()
.predecessor_account_id(alice.clone())
.build();
testing_env!(context);
c.set_value(15);
assert_eq!(c.get_value(), 15);
let context = VMContextBuilder::new()
.predecessor_account_id(owner.clone())
.build();
testing_env!(context);
Integration::pause(&mut c);
Integration::unpause(&mut c);
c.set_value(25);
assert_eq!(c.get_value(), 25);
// Perform migration
env::state_write(&c);
let mut migrated = MigrateIntegration::migrate();
assert_eq!(migrated.moved_value, 25);
assert_eq!(migrated.get_value(), 25);
assert_eq!(migrated.new_value, "my string");
let bob: AccountId = "bob_addr".parse().unwrap();
migrated.set_value(5);
assert_eq!(migrated.get_value(), 5);
// make sure alice still has permission
let context = VMContextBuilder::new()
.predecessor_account_id(alice.clone())
.build();
testing_env!(context);
migrated.set_value(256);
assert_eq!(migrated.get_value(), 256);
// add bob permissions
let context = VMContextBuilder::new()
.predecessor_account_id(owner.clone())
.build();
testing_env!(context);
migrated.add_value_setter(bob.clone());
let context = VMContextBuilder::new()
.predecessor_account_id(bob.clone())
.build();
testing_env!(context);
migrated.set_value(77);
assert_eq!(migrated.get_value(), 77);
let context = VMContextBuilder::new()
.predecessor_account_id(owner.clone())
.build();
testing_env!(context);
MigrateIntegration::pause(&mut migrated);
MigrateIntegration::unpause(&mut migrated);
migrated.set_value(8);
assert_eq!(migrated.get_value(), 8);
c.lock_data(1, "Data".to_string());
assert!(c.check_is_locked(1));
c.unlock_data(1);
}
#[test]
#[should_panic(expected = "Unauthorized")]
fn integration_fail_missing_role() {
let owner: AccountId = "owner".parse().unwrap();
let alice: AccountId = "alice".parse().unwrap();
let context = VMContextBuilder::new()
.predecessor_account_id(owner.clone())
.build();
testing_env!(context);
let mut c = Integration::new(owner.clone());
let context = VMContextBuilder::new()
.predecessor_account_id(alice.clone())
.build();
testing_env!(context);
c.set_value(15);
}
#[test]
#[should_panic(expected = "Disallowed while contract is paused")]
fn integration_fail_set_paused() {
let owner: AccountId = "owner".parse().unwrap();
let context = VMContextBuilder::new()
.predecessor_account_id(owner.clone())
.build();
testing_env!(context);
let mut c = Integration::new(owner.clone());
Integration::pause(&mut c);
c.set_value(5);
}
#[test]
#[should_panic(expected = "Owner only")]
fn integration_fail_migrate_allow() {
let owner: AccountId = "owner".parse().unwrap();
let alice: AccountId = "alice".parse().unwrap();
let context = VMContextBuilder::new()
.predecessor_account_id(owner.clone())
.build();
testing_env!(context);
let c = Integration::new(owner.clone());
env::state_write(&c);
let context = VMContextBuilder::new()
.predecessor_account_id(alice.clone())
.build();
testing_env!(context);
MigrateIntegration::migrate();
}
#[test]
#[should_panic(expected = "Disallowed while contract is paused")]
fn integration_fail_migrate_paused() {
let owner: AccountId = "owner".parse().unwrap();
let context = VMContextBuilder::new()
.predecessor_account_id(owner.clone())
.build();
testing_env!(context);
let mut c = Integration::new(owner.clone());
Integration::pause(&mut c);
env::state_write(&c);
MigrateIntegration::migrate();
}
#[test]
#[should_panic(expected = "Already locked")]
fn integration_fail_cannot_lock_twice() {
let owner: AccountId = "owner".parse().unwrap();
let context = VMContextBuilder::new()
.predecessor_account_id(owner.clone())
.build();
testing_env!(context);
let mut c = Integration::new(owner.clone());
let id = 1;
let data = "Data".to_string();
c.lock_data(id, data.clone());
c.lock_data(id, data.clone());
}
#[cfg(test)]
mod pausable_fungible_token {
use near_sdk::{
env, near, test_utils::VMContextBuilder, testing_env, AccountId, NearToken, PanicOnDefault,
};
use near_sdk_contract_tools::{
ft::*,
hook::Hook,
pause::{hooks::Pausable, Pause},
Pause,
};
#[derive(FungibleToken, Pause, PanicOnDefault)]
#[fungible_token(all_hooks = "Pausable", transfer_hook = "TransferHook")]
#[near(contract_state)]
struct Contract {
pub storage_usage: u64,
}
#[near]
impl Contract {
#[init]
pub fn new() -> Self {
let mut contract = Self { storage_usage: 0 };
contract.set_metadata(&ContractMetadata::new("Pausable Fungible Token", "PFT", 18));
contract
}
}
#[derive(Default)]
struct TransferHook;
impl Hook<Contract, Nep141Transfer<'_>> for TransferHook {
fn hook<R>(
contract: &mut Contract,
_args: &Nep141Transfer,
f: impl FnOnce(&mut Contract) -> R,
) -> R {
let state = env::storage_usage();
let r = f(contract);
let storage_delta = env::storage_usage() - state;
println!("Storage delta: {storage_delta}");
contract.storage_usage = storage_delta;
r
}
}
#[test]
fn hooks_modify_state() {
let alice: AccountId = "alice".parse().unwrap();
let bob: AccountId = "bob_account".parse().unwrap();
let mut c = Contract::new();
let context = VMContextBuilder::new()
.attached_deposit(NearToken::from_near(1).saturating_div(100))
.predecessor_account_id(alice.clone())
.build();
testing_env!(context);
c.storage_deposit(None, None);
let context = VMContextBuilder::new()
.attached_deposit(NearToken::from_near(1).saturating_div(100))
.predecessor_account_id(bob.clone())
.build();
testing_env!(context);
c.storage_deposit(None, None);
c.deposit_unchecked(&alice, 100).unwrap();
let context = VMContextBuilder::new()
.attached_deposit(NearToken::from_yoctonear(1))
.predecessor_account_id(alice.clone())
.build();
testing_env!(context);
c.ft_transfer(bob.clone(), 50.into(), None);
assert_ne!(c.storage_usage, 0);
}
#[test]
#[should_panic(expected = "Disallowed while contract is paused")]
fn hooks_can_terminate_on_error() {
let alice: AccountId = "alice".parse().unwrap();
let bob: AccountId = "bob_account".parse().unwrap();
let mut c = Contract::new();
c.deposit_unchecked(&alice, 100).unwrap();
let context = VMContextBuilder::new()
.attached_deposit(NearToken::from_yoctonear(1))
.predecessor_account_id(alice.clone())
.build();
testing_env!(context);
Pause::pause(&mut c);
c.ft_transfer(bob.clone(), 50.into(), None);
}
}
#[cfg(test)]
mod owned_fungible_token {
use near_sdk::{
env, json_types::U128, near, test_utils::VMContextBuilder, testing_env, AccountId,
};
use near_sdk::{NearToken, PanicOnDefault};
use near_sdk_contract_tools::{
ft::*,
owner::{hooks::OnlyOwner, *},
Owner,
};
#[derive(Owner, FungibleToken, PanicOnDefault)]
#[fungible_token(all_hooks = "OnlyOwner")] // only the owner can transfer, etc. the tokens
#[near(contract_state)]
pub struct Contract {}
#[near]
impl Contract {
#[init]
pub fn new() -> Self {
let mut contract = Self {};
Owner::init(&mut contract, &env::predecessor_account_id());
contract
}
pub fn mint(&mut self, amount: U128) {
Nep141Controller::mint(
self,
&Nep141Mint::new(amount.0, env::predecessor_account_id()),
)
.unwrap();
}
}
#[test]
fn mint_and_transfer() {
let alice: AccountId = "alice".parse().unwrap();
let bob: AccountId = "bob".parse().unwrap();
testing_env!(VMContextBuilder::new()
.predecessor_account_id(alice.clone())
.build());
let mut contract = Contract::new(); // since alice is the predecessor during init, alice is the owner
// internal method calls
contract
.deposit_to_storage_account(&alice, NearToken::from_near(1))
.unwrap();
contract
.deposit_to_storage_account(&bob, NearToken::from_near(1))
.unwrap();
// external; alice is still predecessor
contract.mint(U128(100));
assert_eq!(contract.ft_balance_of(alice.clone()), U128(100));
assert_eq!(contract.ft_balance_of(bob.clone()), U128(0));
testing_env!(VMContextBuilder::new()
.predecessor_account_id(alice.clone())
.attached_deposit(NearToken::from_yoctonear(1u128))
.build());
contract.ft_transfer(bob.clone(), U128(10), None);
assert_eq!(contract.ft_balance_of(alice), U128(90));
assert_eq!(contract.ft_balance_of(bob), U128(10));
}
#[test]
#[should_panic = "Owner only"]
fn mint_fail_not_owner() {
let alice: AccountId = "alice".parse().unwrap();
let bob: AccountId = "bob".parse().unwrap();
testing_env!(VMContextBuilder::new()
.predecessor_account_id(alice.clone())
.build());
let mut contract = Contract::new(); // since alice is the predecessor during init, alice is the owner
// internal method calls
contract
.deposit_to_storage_account(&alice, NearToken::from_near(1))
.unwrap();
contract
.deposit_to_storage_account(&bob, NearToken::from_near(1))
.unwrap();
testing_env!(VMContextBuilder::new().predecessor_account_id(bob).build());
contract.mint(U128(100));
}
#[test]
#[should_panic = "Owner only"]
fn transfer_fail_not_owner() {
let alice: AccountId = "alice".parse().unwrap();
let bob: AccountId = "bob".parse().unwrap();
testing_env!(VMContextBuilder::new()
.predecessor_account_id(alice.clone())
.build());
let mut contract = Contract::new(); // since alice is the predecessor during init, alice is the owner
// internal method calls
contract
.deposit_to_storage_account(&alice, NearToken::from_near(1))
.unwrap();
contract
.deposit_to_storage_account(&bob, NearToken::from_near(1))
.unwrap();
Nep141Controller::deposit_unchecked(&mut contract, &bob, 100).unwrap();
testing_env!(VMContextBuilder::new()
.predecessor_account_id(bob)
.attached_deposit(NearToken::from_yoctonear(1))
.build());
contract.ft_transfer(alice, U128(10), None);
}
}