-
Notifications
You must be signed in to change notification settings - Fork 53
/
lib.rs
570 lines (515 loc) · 20.5 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
#![cfg_attr(not(feature = "std"), no_std)]
#[ink::contract]
mod erc20 {
use ink::storage::Mapping;
/// The ERC-20 error types.
#[derive(Debug, PartialEq, Eq, scale::Encode, scale::Decode)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub enum Error {
/// Returned if not enough balance to fulfill a request is available.
InsufficientBalance,
/// Returned if not enough allowance to fulfill a request is available.
InsufficientAllowance,
}
/// The ERC-20 result type.
pub type Result<T> = core::result::Result<T, Error>;
/// Trait implemented by all ERC-20 respecting smart contracts.
#[ink::trait_definition]
pub trait BaseErc20 {
/// Returns the total token supply.
#[ink(message)]
fn total_supply(&self) -> Balance;
/// Returns the account balance for the specified `owner`.
#[ink(message)]
fn balance_of(&self, owner: AccountId) -> Balance;
/// Returns the amount which `spender` is still allowed to withdraw from `owner`.
#[ink(message)]
fn allowance(&self, owner: AccountId, spender: AccountId) -> Balance;
/// Transfers `value` amount of tokens from the caller's account to account `to`.
#[ink(message)]
fn transfer(&mut self, to: AccountId, value: Balance) -> Result<()>;
/// Allows `spender` to withdraw from the caller's account multiple times, up to
/// the `value` amount.
#[ink(message)]
fn approve(&mut self, spender: AccountId, value: Balance) -> Result<()>;
/// Transfers `value` tokens on the behalf of `from` to the account `to`.
#[ink(message)]
fn transfer_from(
&mut self,
from: AccountId,
to: AccountId,
value: Balance,
) -> Result<()>;
}
/// A simple ERC-20 contract.
#[ink(storage)]
#[derive(Default)]
pub struct Erc20 {
/// Total token supply.
total_supply: Balance,
/// Mapping from owner to number of owned token.
balances: Mapping<AccountId, Balance>,
/// Mapping of the token amount which an account is allowed to withdraw
/// from another account.
allowances: Mapping<(AccountId, AccountId), Balance>,
}
/// Event emitted when a token transfer occurs.
#[ink(event)]
pub struct Transfer {
#[ink(topic)]
from: Option<AccountId>,
#[ink(topic)]
to: Option<AccountId>,
#[ink(topic)]
value: Balance,
}
/// Event emitted when an approval occurs that `spender` is allowed to withdraw
/// up to the amount of `value` tokens from `owner`.
#[ink(event)]
pub struct Approval {
#[ink(topic)]
owner: AccountId,
#[ink(topic)]
spender: AccountId,
#[ink(topic)]
value: Balance,
}
impl Erc20 {
/// Creates a new ERC-20 contract with the specified initial supply.
#[ink(constructor)]
pub fn new(total_supply: Balance) -> Self {
let mut balances = Mapping::default();
let caller = Self::env().caller();
balances.insert(caller, &total_supply);
Self::env().emit_event(Transfer {
from: None,
to: Some(caller),
value: total_supply,
});
Self {
total_supply,
balances,
allowances: Default::default(),
}
}
}
impl BaseErc20 for Erc20 {
/// Returns the total token supply.
#[ink(message)]
fn total_supply(&self) -> Balance {
self.total_supply
}
/// Returns the account balance for the specified `owner`.
///
/// Returns `0` if the account is non-existent.
#[ink(message)]
fn balance_of(&self, owner: AccountId) -> Balance {
self.balance_of_impl(&owner)
}
/// Returns the amount which `spender` is still allowed to withdraw from `owner`.
///
/// Returns `0` if no allowance has been set.
#[ink(message)]
fn allowance(&self, owner: AccountId, spender: AccountId) -> Balance {
self.allowance_impl(&owner, &spender)
}
/// Transfers `value` amount of tokens from the caller's account to account `to`.
///
/// On success a `Transfer` event is emitted.
///
/// # Errors
///
/// Returns `InsufficientBalance` error if there are not enough tokens on
/// the caller's account balance.
#[ink(message)]
fn transfer(&mut self, to: AccountId, value: Balance) -> Result<()> {
let from = self.env().caller();
self.transfer_from_to(&from, &to, value)
}
/// Allows `spender` to withdraw from the caller's account multiple times, up to
/// the `value` amount.
///
/// If this function is called again it overwrites the current allowance with `value`.
///
/// An `Approval` event is emitted.
#[ink(message)]
fn approve(&mut self, spender: AccountId, value: Balance) -> Result<()> {
let owner = self.env().caller();
self.allowances.insert((&owner, &spender), &value);
self.env().emit_event(Approval {
owner,
spender,
value,
});
Ok(())
}
/// Transfers `value` tokens on the behalf of `from` to the account `to`.
///
/// This can be used to allow a contract to transfer tokens on ones behalf and/or
/// to charge fees in sub-currencies, for example.
///
/// On success a `Transfer` event is emitted.
///
/// # Errors
///
/// Returns `InsufficientAllowance` error if there are not enough tokens allowed
/// for the caller to withdraw from `from`.
///
/// Returns `InsufficientBalance` error if there are not enough tokens on
/// the account balance of `from`.
#[ink(message)]
fn transfer_from(
&mut self,
from: AccountId,
to: AccountId,
value: Balance,
) -> Result<()> {
let caller = self.env().caller();
let allowance = self.allowance_impl(&from, &caller);
if allowance < value {
return Err(Error::InsufficientAllowance)
}
self.transfer_from_to(&from, &to, value)?;
self.allowances
.insert((&from, &caller), &(allowance - value));
Ok(())
}
}
#[ink(impl)]
impl Erc20 {
/// Returns the account balance for the specified `owner`.
///
/// Returns `0` if the account is non-existent.
///
/// # Note
///
/// Prefer to call this method over `balance_of` since this
/// works using references which are more efficient in Wasm.
#[inline]
fn balance_of_impl(&self, owner: &AccountId) -> Balance {
self.balances.get(owner).unwrap_or_default()
}
/// Returns the amount which `spender` is still allowed to withdraw from `owner`.
///
/// Returns `0` if no allowance has been set.
///
/// # Note
///
/// Prefer to call this method over `allowance` since this
/// works using references which are more efficient in Wasm.
#[inline]
fn allowance_impl(&self, owner: &AccountId, spender: &AccountId) -> Balance {
self.allowances.get((owner, spender)).unwrap_or_default()
}
/// Transfers `value` amount of tokens from the caller's account to account `to`.
///
/// On success a `Transfer` event is emitted.
///
/// # Errors
///
/// Returns `InsufficientBalance` error if there are not enough tokens on
/// the caller's account balance.
fn transfer_from_to(
&mut self,
from: &AccountId,
to: &AccountId,
value: Balance,
) -> Result<()> {
let from_balance = self.balance_of_impl(from);
if from_balance < value {
return Err(Error::InsufficientBalance)
}
self.balances.insert(from, &(from_balance - value));
let to_balance = self.balance_of_impl(to);
self.balances.insert(to, &(to_balance + value));
self.env().emit_event(Transfer {
from: Some(*from),
to: Some(*to),
value,
});
Ok(())
}
}
/// 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::hash::{
Blake2x256,
CryptoHash,
HashOutput,
},
primitives::Clear,
};
type Event = <Erc20 as ::ink::reflect::ContractEventBase>::Type;
fn assert_transfer_event(
event: &ink::env::test::EmittedEvent,
expected_from: Option<AccountId>,
expected_to: Option<AccountId>,
expected_value: Balance,
) {
let decoded_event = <Event as scale::Decode>::decode(&mut &event.data[..])
.expect("encountered invalid contract event data buffer");
if let Event::Transfer(Transfer { from, to, value }) = decoded_event {
assert_eq!(from, expected_from, "encountered invalid Transfer.from");
assert_eq!(to, expected_to, "encountered invalid Transfer.to");
assert_eq!(value, expected_value, "encountered invalid Trasfer.value");
} else {
panic!("encountered unexpected event kind: expected a Transfer event")
}
fn encoded_into_hash<T>(entity: &T) -> Hash
where
T: scale::Encode,
{
let mut result = Hash::CLEAR_HASH;
let len_result = result.as_ref().len();
let encoded = entity.encode();
let len_encoded = encoded.len();
if len_encoded <= len_result {
result.as_mut()[..len_encoded].copy_from_slice(&encoded);
return result
}
let mut hash_output =
<<Blake2x256 as HashOutput>::Type as Default>::default();
<Blake2x256 as CryptoHash>::hash(&encoded, &mut hash_output);
let copy_len = core::cmp::min(hash_output.len(), len_result);
result.as_mut()[0..copy_len].copy_from_slice(&hash_output[0..copy_len]);
result
}
let expected_topics = [
encoded_into_hash(&PrefixedValue {
prefix: b"",
value: b"Erc20::Transfer",
}),
encoded_into_hash(&PrefixedValue {
prefix: b"Erc20::Transfer::from",
value: &expected_from,
}),
encoded_into_hash(&PrefixedValue {
prefix: b"Erc20::Transfer::to",
value: &expected_to,
}),
encoded_into_hash(&PrefixedValue {
prefix: b"Erc20::Transfer::value",
value: &expected_value,
}),
];
for (n, (actual_topic, expected_topic)) in
event.topics.iter().zip(expected_topics).enumerate()
{
let topic = <Hash as scale::Decode>::decode(&mut &actual_topic[..])
.expect("encountered invalid topic encoding");
assert_eq!(topic, expected_topic, "encountered invalid topic at {n}");
}
}
/// The default constructor does its job.
#[ink::test]
fn new_works() {
// Constructor works.
let initial_supply = 100;
let erc20 = Erc20::new(initial_supply);
// The `BaseErc20` trait has indeed been implemented.
assert_eq!(<Erc20 as BaseErc20>::total_supply(&erc20), initial_supply);
// Transfer event triggered during initial construction.
let emitted_events = ink::env::test::recorded_events().collect::<Vec<_>>();
assert_eq!(1, emitted_events.len());
assert_transfer_event(
&emitted_events[0],
None,
Some(AccountId::from([0x01; 32])),
100,
);
}
/// The total supply was applied.
#[ink::test]
fn total_supply_works() {
// Constructor works.
let initial_supply = 100;
let erc20 = Erc20::new(initial_supply);
// Transfer event triggered during initial construction.
let emitted_events = ink::env::test::recorded_events().collect::<Vec<_>>();
assert_transfer_event(
&emitted_events[0],
None,
Some(AccountId::from([0x01; 32])),
100,
);
// Get the token total supply.
assert_eq!(erc20.total_supply(), 100);
}
/// Get the actual balance of an account.
#[ink::test]
fn balance_of_works() {
// Constructor works
let initial_supply = 100;
let erc20 = Erc20::new(initial_supply);
// Transfer event triggered during initial construction
let emitted_events = ink::env::test::recorded_events().collect::<Vec<_>>();
assert_transfer_event(
&emitted_events[0],
None,
Some(AccountId::from([0x01; 32])),
100,
);
let accounts =
ink::env::test::default_accounts::<ink::env::DefaultEnvironment>();
// Alice owns all the tokens on contract instantiation
assert_eq!(erc20.balance_of(accounts.alice), 100);
// Bob does not owns tokens
assert_eq!(erc20.balance_of(accounts.bob), 0);
}
#[ink::test]
fn transfer_works() {
// Constructor works.
let initial_supply = 100;
let mut erc20 = Erc20::new(initial_supply);
// Transfer event triggered during initial construction.
let accounts =
ink::env::test::default_accounts::<ink::env::DefaultEnvironment>();
assert_eq!(erc20.balance_of(accounts.bob), 0);
// Alice transfers 10 tokens to Bob.
assert_eq!(erc20.transfer(accounts.bob, 10), Ok(()));
// Bob owns 10 tokens.
assert_eq!(erc20.balance_of(accounts.bob), 10);
let emitted_events = ink::env::test::recorded_events().collect::<Vec<_>>();
assert_eq!(emitted_events.len(), 2);
// Check first transfer event related to ERC-20 instantiation.
assert_transfer_event(
&emitted_events[0],
None,
Some(AccountId::from([0x01; 32])),
100,
);
// Check the second transfer event relating to the actual trasfer.
assert_transfer_event(
&emitted_events[1],
Some(AccountId::from([0x01; 32])),
Some(AccountId::from([0x02; 32])),
10,
);
}
#[ink::test]
fn invalid_transfer_should_fail() {
// Constructor works.
let initial_supply = 100;
let mut erc20 = Erc20::new(initial_supply);
let accounts =
ink::env::test::default_accounts::<ink::env::DefaultEnvironment>();
assert_eq!(erc20.balance_of(accounts.bob), 0);
// Set Bob as caller
set_caller(accounts.bob);
// Bob fails to transfers 10 tokens to Eve.
assert_eq!(
erc20.transfer(accounts.eve, 10),
Err(Error::InsufficientBalance)
);
// Alice owns all the tokens.
assert_eq!(erc20.balance_of(accounts.alice), 100);
assert_eq!(erc20.balance_of(accounts.bob), 0);
assert_eq!(erc20.balance_of(accounts.eve), 0);
// Transfer event triggered during initial construction.
let emitted_events = ink::env::test::recorded_events().collect::<Vec<_>>();
assert_eq!(emitted_events.len(), 1);
assert_transfer_event(
&emitted_events[0],
None,
Some(AccountId::from([0x01; 32])),
100,
);
}
#[ink::test]
fn transfer_from_works() {
// Constructor works.
let initial_supply = 100;
let mut erc20 = Erc20::new(initial_supply);
// Transfer event triggered during initial construction.
let accounts =
ink::env::test::default_accounts::<ink::env::DefaultEnvironment>();
// Bob fails to transfer tokens owned by Alice.
assert_eq!(
erc20.transfer_from(accounts.alice, accounts.eve, 10),
Err(Error::InsufficientAllowance)
);
// Alice approves Bob for token transfers on her behalf.
assert_eq!(erc20.approve(accounts.bob, 10), Ok(()));
// The approve event takes place.
assert_eq!(ink::env::test::recorded_events().count(), 2);
// Set Bob as caller.
set_caller(accounts.bob);
// Bob transfers tokens from Alice to Eve.
assert_eq!(
erc20.transfer_from(accounts.alice, accounts.eve, 10),
Ok(())
);
// Eve owns tokens.
assert_eq!(erc20.balance_of(accounts.eve), 10);
// Check all transfer events that happened during the previous calls:
let emitted_events = ink::env::test::recorded_events().collect::<Vec<_>>();
assert_eq!(emitted_events.len(), 3);
assert_transfer_event(
&emitted_events[0],
None,
Some(AccountId::from([0x01; 32])),
100,
);
// The second event `emitted_events[1]` is an Approve event that we skip checking.
assert_transfer_event(
&emitted_events[2],
Some(AccountId::from([0x01; 32])),
Some(AccountId::from([0x05; 32])),
10,
);
}
#[ink::test]
fn allowance_must_not_change_on_failed_transfer() {
let initial_supply = 100;
let mut erc20 = Erc20::new(initial_supply);
let accounts =
ink::env::test::default_accounts::<ink::env::DefaultEnvironment>();
// Alice approves Bob for token transfers on her behalf.
let alice_balance = erc20.balance_of(accounts.alice);
let initial_allowance = alice_balance + 2;
assert_eq!(erc20.approve(accounts.bob, initial_allowance), Ok(()));
// Set Bob as caller.
set_caller(accounts.bob);
// Bob tries to transfer tokens from Alice to Eve.
let emitted_events_before = ink::env::test::recorded_events();
assert_eq!(
erc20.transfer_from(accounts.alice, accounts.eve, alice_balance + 1),
Err(Error::InsufficientBalance)
);
// Allowance must have stayed the same
assert_eq!(
erc20.allowance(accounts.alice, accounts.bob),
initial_allowance
);
// No more events must have been emitted
let emitted_events_after = ink::env::test::recorded_events();
assert_eq!(emitted_events_before.count(), emitted_events_after.count());
}
fn set_caller(sender: AccountId) {
ink::env::test::set_caller::<Environment>(sender);
}
/// For calculating the event topic hash.
struct PrefixedValue<'a, 'b, T> {
pub prefix: &'a [u8],
pub value: &'b T,
}
impl<X> scale::Encode for PrefixedValue<'_, '_, X>
where
X: scale::Encode,
{
#[inline]
fn size_hint(&self) -> usize {
self.prefix.size_hint() + self.value.size_hint()
}
#[inline]
fn encode_to<T: scale::Output + ?Sized>(&self, dest: &mut T) {
self.prefix.encode_to(dest);
self.value.encode_to(dest);
}
}
}
}