forked from use-ink/ink
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.rs
730 lines (685 loc) · 26.7 KB
/
lib.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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
//! # ERC-721
//!
//! This is an ERC-721 Token implementation.
//!
//! ## Warning
//!
//! This contract is an *example*. It is neither audited nor endorsed for production use.
//! Do **not** rely on it to keep anything of value secure.
//!
//! ## Overview
//!
//! This contract demonstrates how to build non-fungible or unique tokens using ink!.
//!
//! ## Error Handling
//!
//! Any function that modifies the state returns a `Result` type and does not changes the state
//! if the `Error` occurs.
//! The errors are defined as an `enum` type. Any other error or invariant violation
//! triggers a panic and therefore rolls back the transaction.
//!
//! ## Token Management
//!
//! After creating a new token, the function caller becomes the owner.
//! A token can be created, transferred, or destroyed.
//!
//! Token owners can assign other accounts for transferring specific tokens on their behalf.
//! It is also possible to authorize an operator (higher rights) for another account to handle tokens.
//!
//! ### Token Creation
//!
//! Token creation start by calling the `mint(&mut self, id: u32)` function.
//! The token owner becomes the function caller. The Token ID needs to be specified
//! as the argument on this function call.
//!
//! ### Token Transfer
//!
//! Transfers may be initiated by:
//! - The owner of a token
//! - The approved address of a token
//! - An authorized operator of the current owner of a token
//!
//! The token owner can transfer a token by calling the `transfer` or `transfer_from` functions.
//! An approved address can make a token transfer by calling the `transfer_from` function.
//! Operators can transfer tokens on another account's behalf or can approve a token transfer
//! for a different account.
//!
//! ### Token Removal
//!
//! Tokens can be destroyed by burning them. Only the token owner is allowed to burn a token.
#![cfg_attr(not(feature = "std"), no_std)]
use ink_lang as ink;
#[ink::contract]
mod erc721 {
#[cfg(not(feature = "ink-as-dependency"))]
use ink_storage::collections::{
hashmap::Entry,
HashMap as StorageHashMap,
};
use scale::{
Decode,
Encode,
};
/// A token ID.
pub type TokenId = u32;
#[ink(storage)]
#[derive(Default)]
pub struct Erc721 {
/// Mapping from token to owner.
token_owner: StorageHashMap<TokenId, AccountId>,
/// Mapping from token to approvals users.
token_approvals: StorageHashMap<TokenId, AccountId>,
/// Mapping from owner to number of owned token.
owned_tokens_count: StorageHashMap<AccountId, u32>,
/// Mapping from owner to operator approvals.
operator_approvals: StorageHashMap<(AccountId, AccountId), bool>,
}
#[derive(Encode, Decode, Debug, PartialEq, Eq, Copy, Clone)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub enum Error {
NotOwner,
NotApproved,
TokenExists,
TokenNotFound,
CannotInsert,
CannotRemove,
CannotFetchValue,
NotAllowed,
}
/// Event emitted when a token transfer occurs.
#[ink(event)]
pub struct Transfer {
#[ink(topic)]
from: Option<AccountId>,
#[ink(topic)]
to: Option<AccountId>,
#[ink(topic)]
id: TokenId,
}
/// Event emitted when a token approve occurs.
#[ink(event)]
pub struct Approval {
#[ink(topic)]
from: AccountId,
#[ink(topic)]
to: AccountId,
#[ink(topic)]
id: TokenId,
}
/// Event emitted when an operator is enabled or disabled for an owner.
/// The operator can manage all NFTs of the owner.
#[ink(event)]
pub struct ApprovalForAll {
#[ink(topic)]
owner: AccountId,
#[ink(topic)]
operator: AccountId,
approved: bool,
}
impl Erc721 {
/// Creates a new ERC-721 token contract.
#[ink(constructor)]
pub fn new() -> Self {
Self {
token_owner: Default::default(),
token_approvals: Default::default(),
owned_tokens_count: Default::default(),
operator_approvals: Default::default(),
}
}
/// Returns the balance of the owner.
///
/// This represents the amount of unique tokens the owner has.
#[ink(message)]
pub fn balance_of(&self, owner: AccountId) -> u32 {
self.balance_of_or_zero(&owner)
}
/// Returns the owner of the token.
#[ink(message)]
pub fn owner_of(&self, id: TokenId) -> Option<AccountId> {
self.token_owner.get(&id).cloned()
}
/// Returns the approved account ID for this token if any.
#[ink(message)]
pub fn get_approved(&self, id: TokenId) -> Option<AccountId> {
self.token_approvals.get(&id).cloned()
}
/// Returns `true` if the operator is approved by the owner.
#[ink(message)]
pub fn is_approved_for_all(&self, owner: AccountId, operator: AccountId) -> bool {
self.approved_for_all(owner, operator)
}
/// Approves or disapproves the operator for all tokens of the caller.
#[ink(message, selector = 0xFEEDBABE)]
pub fn set_approval_for_all(
&mut self,
to: AccountId,
approved: bool,
) -> Result<(), Error> {
self.approve_for_all(to, approved)?;
Ok(())
}
/// Approves the account to transfer the specified token on behalf of the caller.
#[ink(message)]
pub fn approve(&mut self, to: AccountId, id: TokenId) -> Result<(), Error> {
self.approve_for(&to, id)?;
Ok(())
}
/// Transfers the token from the caller to the given destination.
#[ink(message)]
pub fn transfer(
&mut self,
destination: AccountId,
id: TokenId,
) -> Result<(), Error> {
let caller = self.env().caller();
self.transfer_token_from(&caller, &destination, id)?;
Ok(())
}
/// Transfer approved or owned token.
#[ink(message)]
pub fn transfer_from(
&mut self,
from: AccountId,
to: AccountId,
id: TokenId,
) -> Result<(), Error> {
self.transfer_token_from(&from, &to, id)?;
Ok(())
}
/// Creates a new token.
#[ink(message)]
pub fn mint(&mut self, id: TokenId) -> Result<(), Error> {
let caller = self.env().caller();
self.add_token_to(&caller, id)?;
self.env().emit_event(Transfer {
from: Some(AccountId::from([0x0; 32])),
to: Some(caller),
id,
});
Ok(())
}
/// Deletes an existing token. Only the owner can burn the token.
#[ink(message)]
pub fn burn(&mut self, id: TokenId) -> Result<(), Error> {
let caller = self.env().caller();
let Self {
token_owner,
owned_tokens_count,
..
} = self;
let occupied = match token_owner.entry(id) {
Entry::Vacant(_) => return Err(Error::TokenNotFound),
Entry::Occupied(occupied) => occupied,
};
if occupied.get() != &caller {
return Err(Error::NotOwner)
};
decrease_counter_of(owned_tokens_count, &caller)?;
occupied.remove_entry();
self.env().emit_event(Transfer {
from: Some(caller),
to: Some(AccountId::from([0x0; 32])),
id,
});
Ok(())
}
/// Transfers token `id` `from` the sender to the `to` `AccountId`.
fn transfer_token_from(
&mut self,
from: &AccountId,
to: &AccountId,
id: TokenId,
) -> Result<(), Error> {
let caller = self.env().caller();
if !self.exists(id) {
return Err(Error::TokenNotFound)
};
if !self.approved_or_owner(Some(caller), id) {
return Err(Error::NotApproved)
};
self.clear_approval(id)?;
self.remove_token_from(from, id)?;
self.add_token_to(to, id)?;
self.env().emit_event(Transfer {
from: Some(*from),
to: Some(*to),
id,
});
Ok(())
}
/// Removes token `id` from the owner.
fn remove_token_from(
&mut self,
from: &AccountId,
id: TokenId,
) -> Result<(), Error> {
let Self {
token_owner,
owned_tokens_count,
..
} = self;
let occupied = match token_owner.entry(id) {
Entry::Vacant(_) => return Err(Error::TokenNotFound),
Entry::Occupied(occupied) => occupied,
};
decrease_counter_of(owned_tokens_count, from)?;
occupied.remove_entry();
Ok(())
}
/// Adds the token `id` to the `to` AccountID.
fn add_token_to(&mut self, to: &AccountId, id: TokenId) -> Result<(), Error> {
let Self {
token_owner,
owned_tokens_count,
..
} = self;
let vacant_token_owner = match token_owner.entry(id) {
Entry::Vacant(vacant) => vacant,
Entry::Occupied(_) => return Err(Error::TokenExists),
};
if *to == AccountId::from([0x0; 32]) {
return Err(Error::NotAllowed)
};
let entry = owned_tokens_count.entry(*to);
increase_counter_of(entry);
vacant_token_owner.insert(*to);
Ok(())
}
/// Approves or disapproves the operator to transfer all tokens of the caller.
fn approve_for_all(
&mut self,
to: AccountId,
approved: bool,
) -> Result<(), Error> {
let caller = self.env().caller();
if to == caller {
return Err(Error::NotAllowed)
}
self.env().emit_event(ApprovalForAll {
owner: caller,
operator: to,
approved,
});
if self.approved_for_all(caller, to) {
let status = self
.operator_approvals
.get_mut(&(caller, to))
.ok_or(Error::CannotFetchValue)?;
*status = approved;
Ok(())
} else {
match self.operator_approvals.insert((caller, to), approved) {
Some(_) => Err(Error::CannotInsert),
None => Ok(()),
}
}
}
/// Approve the passed `AccountId` to transfer the specified token on behalf of the message's sender.
fn approve_for(&mut self, to: &AccountId, id: TokenId) -> Result<(), Error> {
let caller = self.env().caller();
let owner = self.owner_of(id);
if !(owner == Some(caller)
|| self.approved_for_all(owner.expect("Error with AccountId"), caller))
{
return Err(Error::NotAllowed)
};
if *to == AccountId::from([0x0; 32]) {
return Err(Error::NotAllowed)
};
if self.token_approvals.insert(id, *to).is_some() {
return Err(Error::CannotInsert)
};
self.env().emit_event(Approval {
from: caller,
to: *to,
id,
});
Ok(())
}
/// Removes existing approval from token `id`.
fn clear_approval(&mut self, id: TokenId) -> Result<(), Error> {
if !self.token_approvals.contains_key(&id) {
return Ok(())
};
match self.token_approvals.take(&id) {
Some(_res) => Ok(()),
None => Err(Error::CannotRemove),
}
}
// Returns the total number of tokens from an account.
fn balance_of_or_zero(&self, of: &AccountId) -> u32 {
*self.owned_tokens_count.get(of).unwrap_or(&0)
}
/// Gets an operator on other Account's behalf.
fn approved_for_all(&self, owner: AccountId, operator: AccountId) -> bool {
*self
.operator_approvals
.get(&(owner, operator))
.unwrap_or(&false)
}
/// Returns true if the `AccountId` `from` is the owner of token `id`
/// or it has been approved on behalf of the token `id` owner.
fn approved_or_owner(&self, from: Option<AccountId>, id: TokenId) -> bool {
let owner = self.owner_of(id);
from != Some(AccountId::from([0x0; 32]))
&& (from == owner
|| from == self.token_approvals.get(&id).cloned()
|| self.approved_for_all(
owner.expect("Error with AccountId"),
from.expect("Error with AccountId"),
))
}
/// Returns true if token `id` exists or false if it does not.
fn exists(&self, id: TokenId) -> bool {
self.token_owner.get(&id).is_some() && self.token_owner.contains_key(&id)
}
}
fn decrease_counter_of(
hmap: &mut StorageHashMap<AccountId, u32>,
of: &AccountId,
) -> Result<(), Error> {
let count = (*hmap).get_mut(of).ok_or(Error::CannotFetchValue)?;
*count -= 1;
Ok(())
}
/// Increase token counter from the `of` `AccountId`.
fn increase_counter_of(entry: Entry<AccountId, u32>) {
entry.and_modify(|v| *v += 1).or_insert(1);
}
/// Unit tests
#[cfg(test)]
mod tests {
/// Imports all the definitions from the outer scope so we can use them here.
use super::*;
use ink_env::{
call,
test,
};
use ink_lang as ink;
#[ink::test]
fn mint_works() {
let accounts =
ink_env::test::default_accounts::<ink_env::DefaultEnvironment>()
.expect("Cannot get accounts");
// Create a new contract instance.
let mut erc721 = Erc721::new();
// Token 1 does not exists.
assert_eq!(erc721.owner_of(1), None);
// Alice does not owns tokens.
assert_eq!(erc721.balance_of(accounts.alice), 0);
// Create token Id 1.
assert_eq!(erc721.mint(1), Ok(()));
// Alice owns 1 token.
assert_eq!(erc721.balance_of(accounts.alice), 1);
}
#[ink::test]
fn mint_existing_should_fail() {
let accounts =
ink_env::test::default_accounts::<ink_env::DefaultEnvironment>()
.expect("Cannot get accounts");
// Create a new contract instance.
let mut erc721 = Erc721::new();
// Create token Id 1.
assert_eq!(erc721.mint(1), Ok(()));
// The first Transfer event takes place
assert_eq!(1, ink_env::test::recorded_events().count());
// Alice owns 1 token.
assert_eq!(erc721.balance_of(accounts.alice), 1);
// Alice owns token Id 1.
assert_eq!(erc721.owner_of(1), Some(accounts.alice));
// Cannot create token Id if it exists.
// Bob cannot own token Id 1.
assert_eq!(erc721.mint(1), Err(Error::TokenExists));
}
#[ink::test]
fn transfer_works() {
let accounts =
ink_env::test::default_accounts::<ink_env::DefaultEnvironment>()
.expect("Cannot get accounts");
// Create a new contract instance.
let mut erc721 = Erc721::new();
// Create token Id 1 for Alice
assert_eq!(erc721.mint(1), Ok(()));
// Alice owns token 1
assert_eq!(erc721.balance_of(accounts.alice), 1);
// Bob does not owns any token
assert_eq!(erc721.balance_of(accounts.bob), 0);
// The first Transfer event takes place
assert_eq!(1, ink_env::test::recorded_events().count());
// Alice transfers token 1 to Bob
assert_eq!(erc721.transfer(accounts.bob, 1), Ok(()));
// The second Transfer event takes place
assert_eq!(2, ink_env::test::recorded_events().count());
// Bob owns token 1
assert_eq!(erc721.balance_of(accounts.bob), 1);
}
#[ink::test]
fn invalid_transfer_should_fail() {
let accounts =
ink_env::test::default_accounts::<ink_env::DefaultEnvironment>()
.expect("Cannot get accounts");
// Create a new contract instance.
let mut erc721 = Erc721::new();
// Transfer token fails if it does not exists.
assert_eq!(erc721.transfer(accounts.bob, 2), Err(Error::TokenNotFound));
// Token Id 2 does not exists.
assert_eq!(erc721.owner_of(2), None);
// Create token Id 2.
assert_eq!(erc721.mint(2), Ok(()));
// Alice owns 1 token.
assert_eq!(erc721.balance_of(accounts.alice), 1);
// Token Id 2 is owned by Alice.
assert_eq!(erc721.owner_of(2), Some(accounts.alice));
// Get contract address
let callee = ink_env::account_id::<ink_env::DefaultEnvironment>()
.unwrap_or_else(|_| [0x0; 32].into());
// Create call
let mut data =
ink_env::test::CallData::new(ink_env::call::Selector::new([0x00; 4])); // balance_of
data.push_arg(&accounts.bob);
// Push the new execution context to set Bob as caller
ink_env::test::push_execution_context::<ink_env::DefaultEnvironment>(
accounts.bob,
callee,
1000000,
1000000,
data,
);
// Bob cannot transfer not owned tokens.
assert_eq!(erc721.transfer(accounts.eve, 2), Err(Error::NotApproved));
}
#[ink::test]
fn approved_transfer_works() {
let accounts =
ink_env::test::default_accounts::<ink_env::DefaultEnvironment>()
.expect("Cannot get accounts");
// Create a new contract instance.
let mut erc721 = Erc721::new();
// Create token Id 1.
assert_eq!(erc721.mint(1), Ok(()));
// Token Id 1 is owned by Alice.
assert_eq!(erc721.owner_of(1), Some(accounts.alice));
// Approve token Id 1 transfer for Bob on behalf of Alice.
assert_eq!(erc721.approve(accounts.bob, 1), Ok(()));
// Get contract address.
let callee = ink_env::account_id::<ink_env::DefaultEnvironment>()
.unwrap_or_else(|_| [0x0; 32].into());
// Create call
let mut data =
ink_env::test::CallData::new(ink_env::call::Selector::new([0x00; 4])); // balance_of
data.push_arg(&accounts.bob);
// Push the new execution context to set Bob as caller
ink_env::test::push_execution_context::<ink_env::DefaultEnvironment>(
accounts.bob,
callee,
1000000,
1000000,
data,
);
// Bob transfers token Id 1 from Alice to Eve.
assert_eq!(
erc721.transfer_from(accounts.alice, accounts.eve, 1),
Ok(())
);
// TokenId 3 is owned by Eve.
assert_eq!(erc721.owner_of(1), Some(accounts.eve));
// Alice does not owns tokens.
assert_eq!(erc721.balance_of(accounts.alice), 0);
// Bob does not owns tokens.
assert_eq!(erc721.balance_of(accounts.bob), 0);
// Eve owns 1 token.
assert_eq!(erc721.balance_of(accounts.eve), 1);
}
#[ink::test]
fn approved_for_all_works() {
let accounts =
ink_env::test::default_accounts::<ink_env::DefaultEnvironment>()
.expect("Cannot get accounts");
// Create a new contract instance.
let mut erc721 = Erc721::new();
// Create token Id 1.
assert_eq!(erc721.mint(1), Ok(()));
// Create token Id 2.
assert_eq!(erc721.mint(2), Ok(()));
// Alice owns 2 tokens.
assert_eq!(erc721.balance_of(accounts.alice), 2);
// Approve token Id 1 transfer for Bob on behalf of Alice.
assert_eq!(erc721.set_approval_for_all(accounts.bob, true), Ok(()));
// Bob is an approved operator for Alice
assert!(erc721.is_approved_for_all(accounts.alice, accounts.bob));
// Get contract address.
let callee = ink_env::account_id::<ink_env::DefaultEnvironment>()
.unwrap_or_else(|_| [0x0; 32].into());
// Create call
let mut data =
ink_env::test::CallData::new(ink_env::call::Selector::new([0x00; 4])); // balance_of
data.push_arg(&accounts.bob);
// Push the new execution context to set Bob as caller
ink_env::test::push_execution_context::<ink_env::DefaultEnvironment>(
accounts.bob,
callee,
1000000,
1000000,
data,
);
// Bob transfers token Id 1 from Alice to Eve.
assert_eq!(
erc721.transfer_from(accounts.alice, accounts.eve, 1),
Ok(())
);
// TokenId 1 is owned by Eve.
assert_eq!(erc721.owner_of(1), Some(accounts.eve));
// Alice owns 1 token.
assert_eq!(erc721.balance_of(accounts.alice), 1);
// Bob transfers token Id 2 from Alice to Eve.
assert_eq!(
erc721.transfer_from(accounts.alice, accounts.eve, 2),
Ok(())
);
// Bob does not owns tokens.
assert_eq!(erc721.balance_of(accounts.bob), 0);
// Eve owns 2 tokens.
assert_eq!(erc721.balance_of(accounts.eve), 2);
// Get back to the parent execution context.
ink_env::test::pop_execution_context();
// Remove operator approval for Bob on behalf of Alice.
assert_eq!(erc721.set_approval_for_all(accounts.bob, false), Ok(()));
// Bob is not an approved operator for Alice.
assert!(!erc721.is_approved_for_all(accounts.alice, accounts.bob));
}
#[ink::test]
fn not_approved_transfer_should_fail() {
let accounts =
ink_env::test::default_accounts::<ink_env::DefaultEnvironment>()
.expect("Cannot get accounts");
// Create a new contract instance.
let mut erc721 = Erc721::new();
// Create token Id 1.
assert_eq!(erc721.mint(1), Ok(()));
// Alice owns 1 token.
assert_eq!(erc721.balance_of(accounts.alice), 1);
// Bob does not owns tokens.
assert_eq!(erc721.balance_of(accounts.bob), 0);
// Eve does not owns tokens.
assert_eq!(erc721.balance_of(accounts.eve), 0);
// Get contract address.
let callee = ink_env::account_id::<ink_env::DefaultEnvironment>()
.unwrap_or_else(|_| [0x0; 32].into());
// Create call
let mut data =
ink_env::test::CallData::new(ink_env::call::Selector::new([0x00; 4])); // balance_of
data.push_arg(&accounts.bob);
// Push the new execution context to set Eve as caller
ink_env::test::push_execution_context::<ink_env::DefaultEnvironment>(
accounts.eve,
callee,
1000000,
1000000,
data,
);
// Eve is not an approved operator by Alice.
assert_eq!(
erc721.transfer_from(accounts.alice, accounts.frank, 1),
Err(Error::NotApproved)
);
// Alice owns 1 token.
assert_eq!(erc721.balance_of(accounts.alice), 1);
// Bob does not owns tokens.
assert_eq!(erc721.balance_of(accounts.bob), 0);
// Eve does not owns tokens.
assert_eq!(erc721.balance_of(accounts.eve), 0);
}
#[ink::test]
fn burn_works() {
let accounts =
ink_env::test::default_accounts::<ink_env::DefaultEnvironment>()
.expect("Cannot get accounts");
// Create a new contract instance.
let mut erc721 = Erc721::new();
// Create token Id 1 for Alice
assert_eq!(erc721.mint(1), Ok(()));
// Alice owns 1 token.
assert_eq!(erc721.balance_of(accounts.alice), 1);
// Alice owns token Id 1.
assert_eq!(erc721.owner_of(1), Some(accounts.alice));
// Destroy token Id 1.
assert_eq!(erc721.burn(1), Ok(()));
// Alice does not owns tokens.
assert_eq!(erc721.balance_of(accounts.alice), 0);
// Token Id 1 does not exists
assert_eq!(erc721.owner_of(1), None);
}
#[ink::test]
fn burn_fails_token_not_found() {
// Create a new contract instance.
let mut erc721 = Erc721::new();
// Try burning a non existent token
assert_eq!(erc721.burn(1), Err(Error::TokenNotFound));
}
#[ink::test]
fn burn_fails_not_owner() {
let accounts =
ink_env::test::default_accounts::<ink_env::DefaultEnvironment>()
.expect("Cannot get accounts");
// Create a new contract instance.
let mut erc721 = Erc721::new();
// Create token Id 1 for Alice
assert_eq!(erc721.mint(1), Ok(()));
// Try burning this token with a different account
set_sender(accounts.eve);
assert_eq!(erc721.burn(1), Err(Error::NotOwner));
}
fn set_sender(sender: AccountId) {
let callee = ink_env::account_id::<ink_env::DefaultEnvironment>()
.unwrap_or_else(|_| [0x0; 32].into());
test::push_execution_context::<Environment>(
sender,
callee,
1000000,
1000000,
test::CallData::new(call::Selector::new([0x00; 4])), // dummy
);
}
}
}