-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathdata.rs
More file actions
383 lines (359 loc) · 12.4 KB
/
data.rs
File metadata and controls
383 lines (359 loc) · 12.4 KB
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
use crate::PSP22Error;
use ink::prelude::string::String;
use ink::{
prelude::{vec, vec::Vec},
primitives::AccountId,
storage::Mapping,
};
use ink::env::call::{build_call, ExecutionInput, Selector};
use ink::env::DefaultEnvironment;
/// Temporary type for events emitted during operations that change the
/// state of PSP22Data struct.
/// This is meant to be replaced with proper ink! events as soon as the
/// language allows for event definitions outside contracts.
pub enum PSP22Event {
Transfer {
from: Option<AccountId>,
to: Option<AccountId>,
value: u128,
},
Approval {
owner: AccountId,
spender: AccountId,
amount: u128,
},
}
/// A class implementing the internal logic of a PSP22 token.
//
/// Holds the state of all account balances and allowances.
/// Each method of this class corresponds to one type of transaction
/// as defined in the PSP22 standard.
//
/// Since this code is outside of `ink::contract` macro, the caller's
/// address cannot be obtained automatically. Because of that, all
/// the methods that need to know the caller require an additional argument
/// (compared to transactions defined by the PSP22 standard or the PSP22 trait).
//
/// `lib.rs` contains an example implementation of a smart contract using this class.
#[ink::storage_item]
#[derive(Debug, Default)]
pub struct PSP22Data {
total_supply: u128,
balances: Mapping<AccountId, u128>,
allowances: Mapping<(AccountId, AccountId), u128>,
}
impl PSP22Data {
/// Creates a token with `supply` balance, initially held by the `creator` account.
pub fn new(supply: u128, creator: AccountId) -> PSP22Data {
let mut data = PSP22Data {
total_supply: supply,
balances: Default::default(),
allowances: Default::default(),
};
data.balances.insert(creator, &supply);
data
}
pub fn total_supply(&self) -> u128 {
self.total_supply
}
pub fn balance_of(&self, owner: AccountId) -> u128 {
self.balances.get(owner).unwrap_or_default()
}
pub fn allowance(&self, owner: AccountId, spender: AccountId) -> u128 {
self.allowances.get((owner, spender)).unwrap_or_default()
}
/// Transfers `value` tokens from `caller` to `to`.
pub fn transfer(
&mut self,
caller: AccountId,
to: AccountId,
value: u128,
) -> Result<Vec<PSP22Event>, PSP22Error> {
if caller == to || value == 0 {
return Ok(vec![]);
}
let from_balance = self.balance_of(caller);
if from_balance < value {
return Err(PSP22Error::InsufficientBalance);
}
if from_balance == value {
self.balances.remove(caller);
} else {
self.balances
.insert(caller, &(from_balance.saturating_sub(value)));
}
let to_balance = self.balance_of(to);
// Total supply is limited by u128.MAX so no overflow is possible
self.balances
.insert(to, &(to_balance.saturating_add(value)));
Ok(vec![PSP22Event::Transfer {
from: Some(caller),
to: Some(to),
value,
}])
}
/// Transfers `value` tokens from `from` to `to`, but using the allowance
/// granted be `from` to `caller.
pub fn transfer_from(
&mut self,
caller: AccountId,
from: AccountId,
to: AccountId,
value: u128,
) -> Result<Vec<PSP22Event>, PSP22Error> {
if from == to || value == 0 {
return Ok(vec![]);
}
if caller == from {
return self.transfer(caller, to, value);
}
let allowance = self.allowance(from, caller);
if allowance < value {
return Err(PSP22Error::InsufficientAllowance);
}
let from_balance = self.balance_of(from);
if from_balance < value {
return Err(PSP22Error::InsufficientBalance);
}
if allowance == value {
self.allowances.remove((from, caller));
} else {
self.allowances
.insert((from, caller), &(allowance.saturating_sub(value)));
}
if from_balance == value {
self.balances.remove(from);
} else {
self.balances
.insert(from, &(from_balance.saturating_sub(value)));
}
let to_balance = self.balance_of(to);
// Total supply is limited by u128.MAX so no overflow is possible
self.balances
.insert(to, &(to_balance.saturating_add(value)));
Ok(vec![
PSP22Event::Approval {
owner: from,
spender: caller,
amount: allowance.saturating_sub(value),
},
PSP22Event::Transfer {
from: Some(from),
to: Some(to),
value,
},
])
}
/// Sets a new `value` for allowance granted by `owner` to `spender`.
/// Overwrites the previously granted value.
pub fn approve(
&mut self,
owner: AccountId,
spender: AccountId,
value: u128,
) -> Result<Vec<PSP22Event>, PSP22Error> {
if owner == spender {
return Ok(vec![]);
}
if value == 0 {
self.allowances.remove((owner, spender));
} else {
self.allowances.insert((owner, spender), &value);
}
Ok(vec![PSP22Event::Approval {
owner,
spender,
amount: value,
}])
}
/// Increases the allowance granted by `owner` to `spender` by `delta_value`.
pub fn increase_allowance(
&mut self,
owner: AccountId,
spender: AccountId,
delta_value: u128,
) -> Result<Vec<PSP22Event>, PSP22Error> {
if owner == spender || delta_value == 0 {
return Ok(vec![]);
}
let allowance = self.allowance(owner, spender);
let amount = allowance.saturating_add(delta_value);
self.allowances.insert((owner, spender), &amount);
Ok(vec![PSP22Event::Approval {
owner,
spender,
amount,
}])
}
/// Decreases the allowance granted by `owner` to `spender` by `delta_value`.
pub fn decrease_allowance(
&mut self,
owner: AccountId,
spender: AccountId,
delta_value: u128,
) -> Result<Vec<PSP22Event>, PSP22Error> {
if owner == spender || delta_value == 0 {
return Ok(vec![]);
}
let allowance = self.allowance(owner, spender);
if allowance < delta_value {
return Err(PSP22Error::InsufficientAllowance);
}
let amount = allowance.saturating_sub(delta_value);
if amount == 0 {
self.allowances.remove((owner, spender));
} else {
self.allowances.insert((owner, spender), &amount);
}
Ok(vec![PSP22Event::Approval {
owner,
spender,
amount,
}])
}
/// Mints a `value` of new tokens to `to` account.
pub fn mint(&mut self, to: AccountId, value: u128) -> Result<Vec<PSP22Event>, PSP22Error> {
if value == 0 {
return Ok(vec![]);
}
let new_supply = self
.total_supply
.checked_add(value)
.ok_or(PSP22Error::Custom(String::from(
"Max PSP22 supply exceeded. Max supply limited to 2^128-1.",
)))?;
self.total_supply = new_supply;
let new_balance = self.balance_of(to).saturating_add(value);
self.balances.insert(to, &new_balance);
Ok(vec![PSP22Event::Transfer {
from: None,
to: Some(to),
value,
}])
}
/// Burns `value` tokens from `from` account.
pub fn burn(&mut self, from: AccountId, value: u128) -> Result<Vec<PSP22Event>, PSP22Error> {
if value == 0 {
return Ok(vec![]);
}
let balance = self.balance_of(from);
if balance < value {
return Err(PSP22Error::InsufficientBalance);
}
if balance == value {
self.balances.remove(from);
} else {
self.balances.insert(from, &(balance.saturating_sub(value)));
}
self.total_supply = self.total_supply.saturating_sub(value);
Ok(vec![PSP22Event::Transfer {
from: Some(from),
to: None,
value,
}])
}
/// Burns `value` tokens from `from` account.
pub fn burn_from(&mut self,
caller: AccountId,
from: AccountId,
value: u128
) -> Result<Vec<PSP22Event>, PSP22Error> {
if value == 0 {
return Ok(vec![]);
}
let allowance = self.allowance(from, caller);
if allowance < value {
return Err(PSP22Error::InsufficientAllowance);
}
let balance = self.balance_of(from);
if balance < value {
return Err(PSP22Error::InsufficientBalance);
}
if allowance == value {
self.allowances.remove((from, caller));
} else {
self.allowances
.insert((from, caller), &(allowance.saturating_sub(value)));
}
if balance == value {
self.balances.remove(from);
} else {
self.balances.insert(from, &(balance.saturating_sub(value)));
}
self.total_supply = self.total_supply.saturating_sub(value);
Ok(vec![PSP22Event::Transfer {
from: Some(from),
to: None,
value,
}])
}
/// Deposits a specified amount of tokens from the `underlying` token contract to this contract.
///
/// This method transfers tokens from `sender` to the `contract` account (the current contract),
/// using the `underlying` token's `transfer_from` method. It's typically used in wrapper implementations.
///
/// # Arguments
///
/// * `underlying` - The AccountId of the underlying token contract.
/// * `sender` - The AccountId of the sender who is depositing tokens.
/// * `contract` - The AccountId of this contract, which will receive the tokens.
/// * `value` - The amount of tokens to be deposited.
///
/// # Returns
///
/// A `Result<(), PSP22Error>` indicating the success or failure of the operation.
pub fn deposit(&mut self,
underlying: AccountId,
sender: AccountId,
contract: AccountId,
value: u128
) -> Result<(), PSP22Error> {
pub const TRANSFER_FROM_SELECTOR: [u8; 4] = [84, 179, 199, 110];
build_call::<DefaultEnvironment>()
.call(underlying)
.gas_limit(0)
.transferred_value(0)
.exec_input(
ExecutionInput::new(Selector::new(TRANSFER_FROM_SELECTOR))
.push_arg(sender)
.push_arg(contract)
.push_arg(value)
.push_arg(Vec::<u8>::new())
)
.returns::<Result<(), PSP22Error>>()
.invoke()
}
/// Withdraws a specified amount of tokens from this contract to a specified account.
///
/// This method transfers tokens from this contract to the `account` specified,
/// using the `underlying` token's `transfer` method. It's typically used in wrapper implementations.
///
/// # Arguments
///
/// * `underlying` - The AccountId of the underlying token contract.
/// * `account` - The AccountId where tokens will be withdrawn to.
/// * `value` - The amount of tokens to be withdrawn.
///
/// # Returns
///
/// A `Result<(), PSP22Error>` indicating the success or failure of the operation.
pub fn withdraw(&mut self,
underlying: AccountId,
account: AccountId,
value: u128
) -> Result<(), PSP22Error> {
pub const TRANSFER_SELECTOR: [u8; 4] = [219, 32, 249, 245];
build_call::<DefaultEnvironment>()
.call(underlying)
.gas_limit(0)
.transferred_value(0)
.exec_input(
ExecutionInput::new(Selector::new(TRANSFER_SELECTOR))
.push_arg(account)
.push_arg(value)
.push_arg(Vec::<u8>::new())
)
.returns::<Result<(), PSP22Error>>()
.invoke()
}
}