-
Notifications
You must be signed in to change notification settings - Fork 27
/
psp22.rs
342 lines (288 loc) · 10.6 KB
/
psp22.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
// Copyright (c) 2012-2022 Supercolony
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the"Software"),
// to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
pub use crate::{
psp22,
psp22::Internal as _,
traits::psp22::*,
};
pub use psp22::{
Internal as _,
Transfer as _,
};
use ink_env::{
CallFlags,
Error as EnvError,
};
use ink_prelude::vec::Vec;
use openbrush::{
storage::{
Mapping,
TypeGuard,
},
traits::{
AccountId,
AccountIdExt,
Balance,
Storage,
String,
},
};
pub const STORAGE_KEY: u32 = openbrush::storage_unique_key!(Data);
#[derive(Default, Debug)]
#[openbrush::upgradeable_storage(STORAGE_KEY)]
pub struct Data {
pub supply: Balance,
pub balances: Mapping<AccountId, Balance>,
pub allowances: Mapping<(AccountId, AccountId), Balance, AllowancesKey>,
pub _reserved: Option<()>,
}
pub struct AllowancesKey;
impl<'a> TypeGuard<'a> for AllowancesKey {
type Type = &'a (&'a AccountId, &'a AccountId);
}
impl<T: Storage<Data>> PSP22 for T {
default fn total_supply(&self) -> Balance {
self.data().supply.clone()
}
default fn balance_of(&self, owner: AccountId) -> Balance {
self._balance_of(&owner)
}
default fn allowance(&self, owner: AccountId, spender: AccountId) -> Balance {
self._allowance(&owner, &spender)
}
default fn transfer(&mut self, to: AccountId, value: Balance, data: Vec<u8>) -> Result<(), PSP22Error> {
let from = Self::env().caller();
self._transfer_from_to(from, to, value, data)?;
Ok(())
}
default fn transfer_from(
&mut self,
from: AccountId,
to: AccountId,
value: Balance,
data: Vec<u8>,
) -> Result<(), PSP22Error> {
let caller = Self::env().caller();
let allowance = self._allowance(&from, &caller);
if allowance < value {
return Err(PSP22Error::InsufficientAllowance)
}
self._approve_from_to(from, caller, allowance - value)?;
self._transfer_from_to(from, to, value, data)?;
Ok(())
}
default fn approve(&mut self, spender: AccountId, value: Balance) -> Result<(), PSP22Error> {
let owner = Self::env().caller();
self._approve_from_to(owner, spender, value)?;
Ok(())
}
default fn increase_allowance(&mut self, spender: AccountId, delta_value: Balance) -> Result<(), PSP22Error> {
let owner = Self::env().caller();
self._approve_from_to(owner, spender, self._allowance(&owner, &spender) + delta_value)
}
default fn decrease_allowance(&mut self, spender: AccountId, delta_value: Balance) -> Result<(), PSP22Error> {
let owner = Self::env().caller();
let allowance = self._allowance(&owner, &spender);
if allowance < delta_value {
return Err(PSP22Error::InsufficientAllowance)
}
self._approve_from_to(owner, spender, allowance - delta_value)
}
}
pub trait Internal {
/// User must override those methods in their contract.
fn _emit_transfer_event(&self, _from: Option<AccountId>, _to: Option<AccountId>, _amount: Balance);
fn _emit_approval_event(&self, _owner: AccountId, _spender: AccountId, _amount: Balance);
fn _balance_of(&self, owner: &AccountId) -> Balance;
fn _allowance(&self, owner: &AccountId, spender: &AccountId) -> Balance;
fn _do_safe_transfer_check(
&mut self,
from: &AccountId,
to: &AccountId,
value: &Balance,
data: &Vec<u8>,
) -> Result<(), PSP22Error>;
fn _transfer_from_to(
&mut self,
from: AccountId,
to: AccountId,
amount: Balance,
data: Vec<u8>,
) -> Result<(), PSP22Error>;
fn _approve_from_to(&mut self, owner: AccountId, spender: AccountId, amount: Balance) -> Result<(), PSP22Error>;
fn _mint_to(&mut self, account: AccountId, amount: Balance) -> Result<(), PSP22Error>;
fn _burn_from(&mut self, account: AccountId, amount: Balance) -> Result<(), PSP22Error>;
}
impl<T: Storage<Data>> Internal for T {
default fn _emit_transfer_event(&self, _from: Option<AccountId>, _to: Option<AccountId>, _amount: Balance) {}
default fn _emit_approval_event(&self, _owner: AccountId, _spender: AccountId, _amount: Balance) {}
default fn _balance_of(&self, owner: &AccountId) -> Balance {
self.data().balances.get(owner).unwrap_or(0)
}
default fn _allowance(&self, owner: &AccountId, spender: &AccountId) -> Balance {
self.data().allowances.get(&(owner, spender)).unwrap_or(0)
}
default fn _do_safe_transfer_check(
&mut self,
from: &AccountId,
to: &AccountId,
value: &Balance,
data: &Vec<u8>,
) -> Result<(), PSP22Error> {
self.flush();
let builder = PSP22ReceiverRef::before_received_builder(
to,
Self::env().caller(),
from.clone(),
value.clone(),
data.clone(),
)
.call_flags(CallFlags::default().set_allow_reentry(true));
let result = match builder.fire() {
Ok(result) => {
match result {
Ok(_) => Ok(()),
Err(e) => Err(e.into()),
}
}
Err(e) => {
match e {
// `NotCallable` means that the receiver is not a contract.
// `CalleeTrapped` means that the receiver has no method called `before_received` or it failed inside.
// First case is expected. Second - not. But we can't tell them apart so it is a positive case for now.
// https://github.com/paritytech/ink/issues/1002
EnvError::NotCallable | EnvError::CalleeTrapped => Ok(()),
_ => {
Err(PSP22Error::SafeTransferCheckFailed(String::from(
"Error during call to receiver",
)))
}
}
}
};
self.load();
result?;
Ok(())
}
default fn _transfer_from_to(
&mut self,
from: AccountId,
to: AccountId,
amount: Balance,
data: Vec<u8>,
) -> Result<(), PSP22Error> {
if from.is_zero() {
return Err(PSP22Error::ZeroSenderAddress)
}
if to.is_zero() {
return Err(PSP22Error::ZeroRecipientAddress)
}
let from_balance = self._balance_of(&from);
if from_balance < amount {
return Err(PSP22Error::InsufficientBalance)
}
self._before_token_transfer(Some(&from), Some(&to), &amount)?;
self.data().balances.insert(&from, &(from_balance - amount));
self._do_safe_transfer_check(&from, &to, &amount, &data)?;
let to_balance = self._balance_of(&to);
self.data().balances.insert(&to, &(to_balance + amount));
self._after_token_transfer(Some(&from), Some(&to), &amount)?;
self._emit_transfer_event(Some(from), Some(to), amount);
Ok(())
}
default fn _approve_from_to(
&mut self,
owner: AccountId,
spender: AccountId,
amount: Balance,
) -> Result<(), PSP22Error> {
if owner.is_zero() {
return Err(PSP22Error::ZeroSenderAddress)
}
if spender.is_zero() {
return Err(PSP22Error::ZeroRecipientAddress)
}
self.data().allowances.insert(&(&owner, &spender), &amount);
self._emit_approval_event(owner, spender, amount);
Ok(())
}
default fn _mint_to(&mut self, account: AccountId, amount: Balance) -> Result<(), PSP22Error> {
if account.is_zero() {
return Err(PSP22Error::ZeroRecipientAddress)
}
self._before_token_transfer(None, Some(&account), &amount)?;
let mut new_balance = self._balance_of(&account);
new_balance += amount;
self.data().balances.insert(&account, &new_balance);
self.data().supply += amount;
self._after_token_transfer(None, Some(&account), &amount)?;
self._emit_transfer_event(None, Some(account), amount);
Ok(())
}
default fn _burn_from(&mut self, account: AccountId, amount: Balance) -> Result<(), PSP22Error> {
if account.is_zero() {
return Err(PSP22Error::ZeroRecipientAddress)
}
let mut from_balance = self._balance_of(&account);
if from_balance < amount {
return Err(PSP22Error::InsufficientBalance)
}
self._before_token_transfer(Some(&account), None, &amount)?;
from_balance -= amount;
self.data().balances.insert(&account, &from_balance);
self.data().supply -= amount;
self._after_token_transfer(Some(&account), None, &amount)?;
self._emit_transfer_event(Some(account), None, amount);
Ok(())
}
}
pub trait Transfer {
fn _before_token_transfer(
&mut self,
_from: Option<&AccountId>,
_to: Option<&AccountId>,
_amount: &Balance,
) -> Result<(), PSP22Error>;
fn _after_token_transfer(
&mut self,
_from: Option<&AccountId>,
_to: Option<&AccountId>,
_amount: &Balance,
) -> Result<(), PSP22Error>;
}
impl<T: Storage<Data>> Transfer for T {
default fn _before_token_transfer(
&mut self,
_from: Option<&AccountId>,
_to: Option<&AccountId>,
_amount: &Balance,
) -> Result<(), PSP22Error> {
Ok(())
}
default fn _after_token_transfer(
&mut self,
_from: Option<&AccountId>,
_to: Option<&AccountId>,
_amount: &Balance,
) -> Result<(), PSP22Error> {
Ok(())
}
}