-
Notifications
You must be signed in to change notification settings - Fork 443
/
Copy pathlib.rs
776 lines (680 loc) · 27.4 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
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
#![cfg_attr(not(feature = "std"), no_std)]
use ink::{
prelude::vec::Vec,
primitives::AccountId,
};
// This is the return value that we expect if a smart contract supports receiving ERC-1155
// tokens.
//
// It is calculated with
// `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`, and corresponds
// to 0xf23a6e61.
#[cfg_attr(test, allow(dead_code))]
const ON_ERC_1155_RECEIVED_SELECTOR: [u8; 4] = [0xF2, 0x3A, 0x6E, 0x61];
// This is the return value that we expect if a smart contract supports batch receiving ERC-1155
// tokens.
//
// It is calculated with
// `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`, and
// corresponds to 0xbc197c81.
const _ON_ERC_1155_BATCH_RECEIVED_SELECTOR: [u8; 4] = [0xBC, 0x19, 0x7C, 0x81];
/// A type representing the unique IDs of tokens managed by this contract.
pub type TokenId = u128;
type Balance = <ink::env::DefaultEnvironment as ink::env::Environment>::Balance;
// The ERC-1155 error types.
#[derive(Debug, PartialEq, Eq, scale::Encode, scale::Decode)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub enum Error {
/// This token ID has not yet been created by the contract.
UnexistentToken,
/// The caller tried to sending tokens to the zero-address (`0x00`).
ZeroAddressTransfer,
/// The caller is not approved to transfer tokens on behalf of the account.
NotApproved,
/// The account does not have enough funds to complete the transfer.
InsufficientBalance,
/// An account does not need to approve themselves to transfer tokens.
SelfApproval,
/// The number of tokens being transferred does not match the specified number of transfers.
BatchTransferMismatch,
}
// The ERC-1155 result types.
pub type Result<T> = core::result::Result<T, Error>;
/// Evaluate `$x:expr` and if not true return `Err($y:expr)`.
///
/// Used as `ensure!(expression_to_ensure, expression_to_return_on_false)`.
macro_rules! ensure {
( $condition:expr, $error:expr $(,)? ) => {{
if !$condition {
return ::core::result::Result::Err(::core::convert::Into::into($error))
}
}};
}
/// The interface for an ERC-1155 compliant contract.
///
/// The interface is defined here: <https://eips.ethereum.org/EIPS/eip-1155>.
///
/// The goal of ERC-1155 is to allow a single contract to manage a variety of assets.
/// These assets can be fungible, non-fungible, or a combination.
///
/// By tracking multiple assets the ERC-1155 standard is able to support batch transfers, which
/// make it easy to transfer a mix of multiple tokens at once.
#[ink::trait_definition]
pub trait Erc1155 {
/// Transfer a `value` amount of `token_id` tokens to the `to` account from the `from`
/// account.
///
/// Note that the call does not have to originate from the `from` account, and may originate
/// from any account which is approved to transfer `from`'s tokens.
#[ink(message)]
fn safe_transfer_from(
&mut self,
from: AccountId,
to: AccountId,
token_id: TokenId,
value: Balance,
data: Vec<u8>,
) -> Result<()>;
/// Perform a batch transfer of `token_ids` to the `to` account from the `from` account.
///
/// The number of `values` specified to be transferred must match the number of `token_ids`,
/// otherwise this call will revert.
///
/// Note that the call does not have to originate from the `from` account, and may originate
/// from any account which is approved to transfer `from`'s tokens.
#[ink(message)]
fn safe_batch_transfer_from(
&mut self,
from: AccountId,
to: AccountId,
token_ids: Vec<TokenId>,
values: Vec<Balance>,
data: Vec<u8>,
) -> Result<()>;
/// Query the balance of a specific token for the provided account.
#[ink(message)]
fn balance_of(&self, owner: AccountId, token_id: TokenId) -> Balance;
/// Query the balances for a set of tokens for a set of accounts.
///
/// E.g use this call if you want to query what Alice and Bob's balances are for Tokens ID 1 and
/// ID 2.
///
/// This will return all the balances for a given owner before moving on to the next owner. In
/// the example above this means that the return value should look like:
///
/// [Alice Balance of Token ID 1, Alice Balance of Token ID 2, Bob Balance of Token ID 1, Bob Balance of Token ID 2]
#[ink(message)]
fn balance_of_batch(
&self,
owners: Vec<AccountId>,
token_ids: Vec<TokenId>,
) -> Vec<Balance>;
/// Enable or disable a third party, known as an `operator`, to control all tokens on behalf of
/// the caller.
#[ink(message)]
fn set_approval_for_all(&mut self, operator: AccountId, approved: bool)
-> Result<()>;
/// Query if the given `operator` is allowed to control all of `owner`'s tokens.
#[ink(message)]
fn is_approved_for_all(&self, owner: AccountId, operator: AccountId) -> bool;
}
/// The interface for an ERC-1155 Token Receiver contract.
///
/// The interface is defined here: <https://eips.ethereum.org/EIPS/eip-1155>.
///
/// Smart contracts which want to accept token transfers must implement this interface. By default
/// if a contract does not support this interface any transactions originating from an ERC-1155
/// compliant contract which attempt to transfer tokens directly to the contract's address must be
/// reverted.
#[ink::trait_definition]
pub trait Erc1155TokenReceiver {
/// Handle the receipt of a single ERC-1155 token.
///
/// This should be called by a compliant ERC-1155 contract if the intended recipient is a smart
/// contract.
///
/// If the smart contract implementing this interface accepts token transfers then it must
/// return `ON_ERC_1155_RECEIVED_SELECTOR` from this function. To reject a transfer it must revert.
///
/// Any callers must revert if they receive anything other than `ON_ERC_1155_RECEIVED_SELECTOR` as a return
/// value.
#[ink(message, selector = 0xF23A6E61)]
fn on_received(
&mut self,
operator: AccountId,
from: AccountId,
token_id: TokenId,
value: Balance,
data: Vec<u8>,
) -> Vec<u8>;
/// Handle the receipt of multiple ERC-1155 tokens.
///
/// This should be called by a compliant ERC-1155 contract if the intended recipient is a smart
/// contract.
///
/// If the smart contract implementing this interface accepts token transfers then it must
/// return `BATCH_ON_ERC_1155_RECEIVED_SELECTOR` from this function. To reject a transfer it must revert.
///
/// Any callers must revert if they receive anything other than `BATCH_ON_ERC_1155_RECEIVED_SELECTOR` as a return
/// value.
#[ink(message, selector = 0xBC197C81)]
fn on_batch_received(
&mut self,
operator: AccountId,
from: AccountId,
token_ids: Vec<TokenId>,
values: Vec<Balance>,
data: Vec<u8>,
) -> Vec<u8>;
}
#[ink::contract]
mod erc1155 {
use super::*;
use ink::storage::Mapping;
type Owner = AccountId;
type Operator = AccountId;
/// Indicate that a token transfer has occured.
///
/// This must be emitted even if a zero value transfer occurs.
#[ink(event)]
pub struct TransferSingle {
#[ink(topic)]
operator: Option<AccountId>,
#[ink(topic)]
from: Option<AccountId>,
#[ink(topic)]
to: Option<AccountId>,
token_id: TokenId,
value: Balance,
}
/// Indicate that an approval event has happened.
#[ink(event)]
pub struct ApprovalForAll {
#[ink(topic)]
owner: AccountId,
#[ink(topic)]
operator: AccountId,
approved: bool,
}
/// Indicate that a token's URI has been updated.
#[ink(event)]
pub struct Uri {
value: ink::prelude::string::String,
#[ink(topic)]
token_id: TokenId,
}
/// An ERC-1155 contract.
#[ink(storage)]
#[derive(Default)]
pub struct Contract {
/// Tracks the balances of accounts across the different tokens that they might be holding.
balances: Mapping<(AccountId, TokenId), Balance>,
/// Which accounts (called operators) have been approved to spend funds on behalf of an owner.
approvals: Mapping<(Owner, Operator), ()>,
/// A unique identifier for the tokens which have been minted (and are therefore supported)
/// by this contract.
token_id_nonce: TokenId,
}
impl Contract {
/// Initialize a default instance of this ERC-1155 implementation.
#[ink(constructor)]
pub fn new() -> Self {
Default::default()
}
/// Create the initial supply for a token.
///
/// The initial supply will be provided to the caller (a.k.a the minter), and the
/// `token_id` will be assigned by the smart contract.
///
/// Note that as implemented anyone can create tokens. If you were to instantiate
/// this contract in a production environment you'd probably want to lock down
/// the addresses that are allowed to create tokens.
#[ink(message)]
pub fn create(&mut self, value: Balance) -> TokenId {
let caller = self.env().caller();
// Given that TokenId is a `u128` the likelihood of this overflowing is pretty slim.
self.token_id_nonce += 1;
self.balances.insert((caller, self.token_id_nonce), &value);
// Emit transfer event but with mint semantics
self.env().emit_event(TransferSingle {
operator: Some(caller),
from: None,
to: if value == 0 { None } else { Some(caller) },
token_id: self.token_id_nonce,
value,
});
self.token_id_nonce
}
/// Mint a `value` amount of `token_id` tokens.
///
/// It is assumed that the token has already been `create`-ed. The newly minted supply will
/// be assigned to the caller (a.k.a the minter).
///
/// Note that as implemented anyone can mint tokens. If you were to instantiate
/// this contract in a production environment you'd probably want to lock down
/// the addresses that are allowed to mint tokens.
#[ink(message)]
pub fn mint(&mut self, token_id: TokenId, value: Balance) -> Result<()> {
ensure!(token_id <= self.token_id_nonce, Error::UnexistentToken);
let caller = self.env().caller();
self.balances.insert((caller, token_id), &value);
// Emit transfer event but with mint semantics
self.env().emit_event(TransferSingle {
operator: Some(caller),
from: None,
to: Some(caller),
token_id,
value,
});
Ok(())
}
// Helper function for performing single token transfers.
//
// Should not be used directly since it's missing certain checks which are important to the
// ERC-1155 standard (it is expected that the caller has already performed these).
//
// # Panics
//
// If `from` does not hold any `token_id` tokens.
fn perform_transfer(
&mut self,
from: AccountId,
to: AccountId,
token_id: TokenId,
value: Balance,
) {
let mut sender_balance = self
.balances
.get((from, token_id))
.expect("Caller should have ensured that `from` holds `token_id`.");
sender_balance -= value;
self.balances.insert((from, token_id), &sender_balance);
let mut recipient_balance = self.balances.get((to, token_id)).unwrap_or(0);
recipient_balance += value;
self.balances.insert((to, token_id), &recipient_balance);
let caller = self.env().caller();
self.env().emit_event(TransferSingle {
operator: Some(caller),
from: Some(from),
to: Some(to),
token_id,
value,
});
}
// Check if the address at `to` is a smart contract which accepts ERC-1155 token transfers.
//
// If they're a smart contract which **doesn't** accept tokens transfers this call will
// revert. Otherwise we risk locking user funds at in that contract with no chance of
// recovery.
#[cfg_attr(test, allow(unused_variables))]
fn transfer_acceptance_check(
&mut self,
caller: AccountId,
from: AccountId,
to: AccountId,
token_id: TokenId,
value: Balance,
data: Vec<u8>,
) {
// This is disabled during tests due to the use of `invoke_contract()` not being
// supported (tests end up panicking).
#[cfg(not(test))]
{
use ink::env::call::{
build_call,
ExecutionInput,
Selector,
};
// If our recipient is a smart contract we need to see if they accept or
// reject this transfer. If they reject it we need to revert the call.
let result = build_call::<Environment>()
.call(to)
.gas_limit(5000)
.exec_input(
ExecutionInput::new(Selector::new(ON_ERC_1155_RECEIVED_SELECTOR))
.push_arg(caller)
.push_arg(from)
.push_arg(token_id)
.push_arg(value)
.push_arg(data),
)
.returns::<Vec<u8>>()
.params()
.try_invoke();
match result {
Ok(v) => {
ink::env::debug_println!(
"Received return value \"{:?}\" from contract {:?}",
v.clone().expect(
"Call should be valid, don't expect a `LangError`."
),
from
);
assert_eq!(
v.clone().expect("Call should be valid, don't expect a `LangError`."),
&ON_ERC_1155_RECEIVED_SELECTOR[..],
"The recipient contract at {to:?} does not accept token transfers.\n
Expected: {ON_ERC_1155_RECEIVED_SELECTOR:?}, Got {v:?}"
)
}
Err(e) => {
match e {
ink::env::Error::CodeNotFound
| ink::env::Error::NotCallable => {
// Our recipient wasn't a smart contract, so there's nothing more for
// us to do
ink::env::debug_println!("Recipient at {:?} from is not a smart contract ({:?})", from, e);
}
_ => {
// We got some sort of error from the call to our recipient smart
// contract, and as such we must revert this call
panic!(
"Got error \"{e:?}\" while trying to call {from:?}"
)
}
}
}
}
}
}
}
impl super::Erc1155 for Contract {
#[ink(message)]
fn safe_transfer_from(
&mut self,
from: AccountId,
to: AccountId,
token_id: TokenId,
value: Balance,
data: Vec<u8>,
) -> Result<()> {
let caller = self.env().caller();
if caller != from {
ensure!(self.is_approved_for_all(from, caller), Error::NotApproved);
}
ensure!(to != zero_address(), Error::ZeroAddressTransfer);
let balance = self.balance_of(from, token_id);
ensure!(balance >= value, Error::InsufficientBalance);
self.perform_transfer(from, to, token_id, value);
self.transfer_acceptance_check(caller, from, to, token_id, value, data);
Ok(())
}
#[ink(message)]
fn safe_batch_transfer_from(
&mut self,
from: AccountId,
to: AccountId,
token_ids: Vec<TokenId>,
values: Vec<Balance>,
data: Vec<u8>,
) -> Result<()> {
let caller = self.env().caller();
if caller != from {
ensure!(self.is_approved_for_all(from, caller), Error::NotApproved);
}
ensure!(to != zero_address(), Error::ZeroAddressTransfer);
ensure!(!token_ids.is_empty(), Error::BatchTransferMismatch);
ensure!(
token_ids.len() == values.len(),
Error::BatchTransferMismatch,
);
let transfers = token_ids.iter().zip(values.iter());
for (&id, &v) in transfers.clone() {
let balance = self.balance_of(from, id);
ensure!(balance >= v, Error::InsufficientBalance);
}
for (&id, &v) in transfers {
self.perform_transfer(from, to, id, v);
}
// Can use the any token ID/value here, we really just care about knowing if `to` is a
// smart contract which accepts transfers
self.transfer_acceptance_check(
caller,
from,
to,
token_ids[0],
values[0],
data,
);
Ok(())
}
#[ink(message)]
fn balance_of(&self, owner: AccountId, token_id: TokenId) -> Balance {
self.balances.get((owner, token_id)).unwrap_or(0)
}
#[ink(message)]
fn balance_of_batch(
&self,
owners: Vec<AccountId>,
token_ids: Vec<TokenId>,
) -> Vec<Balance> {
let mut output = Vec::new();
for o in &owners {
for t in &token_ids {
let amount = self.balance_of(*o, *t);
output.push(amount);
}
}
output
}
#[ink(message)]
fn set_approval_for_all(
&mut self,
operator: AccountId,
approved: bool,
) -> Result<()> {
let caller = self.env().caller();
ensure!(operator != caller, Error::SelfApproval);
if approved {
self.approvals.insert((&caller, &operator), &());
} else {
self.approvals.remove((&caller, &operator));
}
self.env().emit_event(ApprovalForAll {
owner: caller,
operator,
approved,
});
Ok(())
}
#[ink(message)]
fn is_approved_for_all(&self, owner: AccountId, operator: AccountId) -> bool {
self.approvals.contains((&owner, &operator))
}
}
impl super::Erc1155TokenReceiver for Contract {
#[ink(message, selector = 0xF23A6E61)]
fn on_received(
&mut self,
_operator: AccountId,
_from: AccountId,
_token_id: TokenId,
_value: Balance,
_data: Vec<u8>,
) -> Vec<u8> {
// The ERC-1155 standard dictates that if a contract does not accept token transfers
// directly to the contract, then the contract must revert.
//
// This prevents a user from unintentionally transferring tokens to a smart contract
// and getting their funds stuck without any sort of recovery mechanism.
//
// Note that the choice of whether or not to accept tokens is implementation specific,
// and we've decided to not accept them in this implementation.
unimplemented!("This smart contract does not accept token transfer.")
}
#[ink(message, selector = 0xBC197C81)]
fn on_batch_received(
&mut self,
_operator: AccountId,
_from: AccountId,
_token_ids: Vec<TokenId>,
_values: Vec<Balance>,
_data: Vec<u8>,
) -> Vec<u8> {
// The ERC-1155 standard dictates that if a contract does not accept token transfers
// directly to the contract, then the contract must revert.
//
// This prevents a user from unintentionally transferring tokens to a smart contract
// and getting their funds stuck without any sort of recovery mechanism.
//
// Note that the choice of whether or not to accept tokens is implementation specific,
// and we've decided to not accept them in this implementation.
unimplemented!("This smart contract does not accept batch token transfers.")
}
}
/// Helper for referencing the zero address (`0x00`). Note that in practice this address should
/// not be treated in any special way (such as a default placeholder) since it has a known
/// private key.
fn zero_address() -> AccountId {
[0u8; 32].into()
}
#[cfg(test)]
mod tests {
/// Imports all the definitions from the outer scope so we can use them here.
use super::*;
use crate::Erc1155;
fn set_sender(sender: AccountId) {
ink::env::test::set_caller::<Environment>(sender);
}
fn default_accounts() -> ink::env::test::DefaultAccounts<Environment> {
ink::env::test::default_accounts::<Environment>()
}
fn alice() -> AccountId {
default_accounts().alice
}
fn bob() -> AccountId {
default_accounts().bob
}
fn charlie() -> AccountId {
default_accounts().charlie
}
fn init_contract() -> Contract {
let mut erc = Contract::new();
erc.balances.insert((alice(), 1), &10);
erc.balances.insert((alice(), 2), &20);
erc.balances.insert((bob(), 1), &10);
erc
}
#[ink::test]
fn can_get_correct_balance_of() {
let erc = init_contract();
assert_eq!(erc.balance_of(alice(), 1), 10);
assert_eq!(erc.balance_of(alice(), 2), 20);
assert_eq!(erc.balance_of(alice(), 3), 0);
assert_eq!(erc.balance_of(bob(), 2), 0);
}
#[ink::test]
fn can_get_correct_batch_balance_of() {
let erc = init_contract();
assert_eq!(
erc.balance_of_batch(vec![alice()], vec![1, 2, 3]),
vec![10, 20, 0]
);
assert_eq!(
erc.balance_of_batch(vec![alice(), bob()], vec![1]),
vec![10, 10]
);
assert_eq!(
erc.balance_of_batch(vec![alice(), bob(), charlie()], vec![1, 2]),
vec![10, 20, 10, 0, 0, 0]
);
}
#[ink::test]
fn can_send_tokens_between_accounts() {
let mut erc = init_contract();
assert!(erc.safe_transfer_from(alice(), bob(), 1, 5, vec![]).is_ok());
assert_eq!(erc.balance_of(alice(), 1), 5);
assert_eq!(erc.balance_of(bob(), 1), 15);
assert!(erc.safe_transfer_from(alice(), bob(), 2, 5, vec![]).is_ok());
assert_eq!(erc.balance_of(alice(), 2), 15);
assert_eq!(erc.balance_of(bob(), 2), 5);
}
#[ink::test]
fn sending_too_many_tokens_fails() {
let mut erc = init_contract();
let res = erc.safe_transfer_from(alice(), bob(), 1, 99, vec![]);
assert_eq!(res.unwrap_err(), Error::InsufficientBalance);
}
#[ink::test]
fn sending_tokens_to_zero_address_fails() {
let burn: AccountId = [0; 32].into();
let mut erc = init_contract();
let res = erc.safe_transfer_from(alice(), burn, 1, 10, vec![]);
assert_eq!(res.unwrap_err(), Error::ZeroAddressTransfer);
}
#[ink::test]
fn can_send_batch_tokens() {
let mut erc = init_contract();
assert!(erc
.safe_batch_transfer_from(alice(), bob(), vec![1, 2], vec![5, 10], vec![])
.is_ok());
let balances = erc.balance_of_batch(vec![alice(), bob()], vec![1, 2]);
assert_eq!(balances, vec![5, 10, 15, 10])
}
#[ink::test]
fn rejects_batch_if_lengths_dont_match() {
let mut erc = init_contract();
let res = erc.safe_batch_transfer_from(
alice(),
bob(),
vec![1, 2, 3],
vec![5],
vec![],
);
assert_eq!(res.unwrap_err(), Error::BatchTransferMismatch);
}
#[ink::test]
fn batch_transfers_fail_if_len_is_zero() {
let mut erc = init_contract();
let res =
erc.safe_batch_transfer_from(alice(), bob(), vec![], vec![], vec![]);
assert_eq!(res.unwrap_err(), Error::BatchTransferMismatch);
}
#[ink::test]
fn operator_can_send_tokens() {
let mut erc = init_contract();
let owner = alice();
let operator = bob();
set_sender(owner);
assert!(erc.set_approval_for_all(operator, true).is_ok());
set_sender(operator);
assert!(erc
.safe_transfer_from(owner, charlie(), 1, 5, vec![])
.is_ok());
assert_eq!(erc.balance_of(alice(), 1), 5);
assert_eq!(erc.balance_of(charlie(), 1), 5);
}
#[ink::test]
fn approvals_work() {
let mut erc = init_contract();
let owner = alice();
let operator = bob();
let another_operator = charlie();
// Note: All of these tests are from the context of the owner who is either allowing or
// disallowing an operator to control their funds.
set_sender(owner);
assert!(!erc.is_approved_for_all(owner, operator));
assert!(erc.set_approval_for_all(operator, true).is_ok());
assert!(erc.is_approved_for_all(owner, operator));
assert!(erc.set_approval_for_all(another_operator, true).is_ok());
assert!(erc.is_approved_for_all(owner, another_operator));
assert!(erc.set_approval_for_all(operator, false).is_ok());
assert!(!erc.is_approved_for_all(owner, operator));
}
#[ink::test]
fn minting_tokens_works() {
let mut erc = Contract::new();
set_sender(alice());
assert_eq!(erc.create(0), 1);
assert_eq!(erc.balance_of(alice(), 1), 0);
assert!(erc.mint(1, 123).is_ok());
assert_eq!(erc.balance_of(alice(), 1), 123);
}
#[ink::test]
fn minting_not_allowed_for_nonexistent_tokens() {
let mut erc = Contract::new();
let res = erc.mint(1, 123);
assert_eq!(res.unwrap_err(), Error::UnexistentToken);
}
}
}