-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathdata.rs
241 lines (211 loc) · 7.09 KB
/
data.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
use crate::balances::balance_manager::Balances;
use crate::PSP34Error;
use ink::{
prelude::{string::String, vec, vec::Vec},
primitives::AccountId,
storage::Mapping,
};
#[cfg(feature = "std")]
use ink::storage::traits::StorageLayout;
/// Type for a PSP34 token id.
/// Contains all the possible permutations of id according to the standard.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, scale::Encode, scale::Decode)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo, StorageLayout))]
pub enum Id {
U8(u8),
U16(u16),
U32(u32),
U64(u64),
U128(u128),
Bytes(Vec<u8>),
}
/// Temporary type for events emitted during operations that change the
/// state of PSP34Data struct.
/// This is meant to be replaced with proper ink! events as soon as the
/// language allows for event definitions outside contracts.
pub enum PSP34Event {
Transfer {
from: Option<AccountId>,
to: Option<AccountId>,
id: Id,
},
Approval {
owner: AccountId,
operator: AccountId,
id: Option<Id>,
approved: bool,
},
AttributeSet {
id: Id,
key: Vec<u8>,
data: Vec<u8>,
},
}
/// A class implementing the internal logic of a PSP34 token.
//
/// Holds the state of all account balances and approvals.
/// Each method of this class corresponds to one type of transaction
/// as defined in the PSP34 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 PSP34 standard or the PSP34 trait).
//
/// `lib.rs` contains an example implementation of a smart contract using this class.
#[ink::storage_item]
#[derive(Debug, Default)]
pub struct PSP34Data {
token_owner: Mapping<Id, AccountId>,
operator_approvals: Mapping<(AccountId, AccountId, Option<Id>), ()>,
balance: Balances,
}
impl PSP34Data {
/// Creates a token with default values for every field.
/// Initially held by the 'creator' account.
pub fn new() -> PSP34Data {
Default::default()
}
pub fn total_supply(&self) -> u128 {
self.balance.total_supply()
}
pub fn balance_of(&self, owner: AccountId) -> u32 {
self.balance.balance_of(&owner)
}
pub fn owner_of(&self, id: &Id) -> Option<AccountId> {
self.token_owner.get(id)
}
pub fn allowance(&self, owner: AccountId, operator: AccountId, id: Option<&Id>) -> bool {
self.operator_approvals
.get((owner, operator, &None))
.is_some()
|| id.is_some() && self.operator_approvals.get((owner, operator, id)).is_some()
}
pub fn collection_id(&self, account_id: AccountId) -> Id {
Id::Bytes(<_ as AsRef<[u8; 32]>>::as_ref(&account_id).to_vec())
}
/// Sets a new `approved` for a token `id` or for all tokens if no `id` is provided,
/// granted by `caller` to `operator`.
/// Overwrites the previously granted value.
pub fn approve(
&mut self,
mut caller: AccountId,
operator: AccountId,
id: Option<Id>,
approved: bool,
) -> Result<Vec<PSP34Event>, PSP34Error> {
if let Some(id) = &id {
let owner = self.owner_of(id).ok_or(PSP34Error::TokenNotExists)?;
if approved && owner == operator {
return Err(PSP34Error::SelfApprove);
}
if owner != caller && !self.allowance(owner, caller, None) {
return Err(PSP34Error::NotApproved);
}
if !approved && self.allowance(owner, operator, None) {
return Err(PSP34Error::Custom(String::from(
"Cannot revoke approval for a single token, when the operator has approval for all tokens."
)));
}
caller = owner;
}
if approved {
self.operator_approvals
.insert((caller, operator, id.as_ref()), &());
} else {
self.operator_approvals
.remove((caller, operator, id.as_ref()));
}
Ok(vec![PSP34Event::Approval {
owner: caller,
operator,
id,
approved,
}])
}
/// Transfers `value` tokens from `caller` to `to`.
pub fn transfer(
&mut self,
caller: AccountId,
to: AccountId,
id: Id,
_data: Vec<u8>,
) -> Result<Vec<PSP34Event>, PSP34Error> {
let owner = self.owner_of(&id).ok_or(PSP34Error::TokenNotExists)?;
if owner == to {
return Ok(vec![]);
}
if owner != caller && !self.allowance(owner, caller, Some(&id)) {
return Err(PSP34Error::NotApproved);
}
self.balance.decrease_balance(&owner, &id, false);
self.operator_approvals.remove((owner, caller, Some(&id)));
self.token_owner.remove(&id);
self.token_owner.insert(&id, &to);
self.balance.increase_balance(&to, &id, false)?;
Ok(vec![PSP34Event::Transfer {
from: Some(caller),
to: Some(to),
id,
}])
}
/// Mints a token `id` to `account`.
pub fn mint(&mut self, account: AccountId, id: Id) -> Result<Vec<PSP34Event>, PSP34Error> {
if self.owner_of(&id).is_some() {
return Err(PSP34Error::TokenExists);
}
self.balance.increase_balance(&account, &id, true)?;
self.token_owner.insert(&id, &account);
Ok(vec![PSP34Event::Transfer {
from: None,
to: Some(account),
id,
}])
}
/// Burns token `id` from `account`, conducted by `caller`
pub fn burn(
&mut self,
caller: AccountId,
account: AccountId,
id: Id,
) -> Result<Vec<PSP34Event>, PSP34Error> {
if self.owner_of(&id).is_none() {
return Err(PSP34Error::TokenNotExists);
}
if account != caller && !self.allowance(caller, account, None) {
return Err(PSP34Error::NotApproved);
}
self.balance.decrease_balance(&account, &id, true);
self.token_owner.remove(&id);
Ok(vec![PSP34Event::Transfer {
from: Some(account),
to: None,
id,
}])
}
#[cfg(feature = "enumerable")]
pub fn owners_token_by_index(&self, owner: AccountId, index: u128) -> Result<Id, PSP34Error> {
self.balance.owners_token_by_index(owner, index)
}
#[cfg(feature = "enumerable")]
pub fn token_by_index(&self, index: u128) -> Result<Id, PSP34Error> {
self.balance.token_by_index(index)
}
}
impl Default for Id {
fn default() -> Self {
Self::U128(0)
}
}
impl From<Id> for u128 {
fn from(id: Id) -> Self {
match id {
Id::U8(val) => val as u128,
Id::U16(val) => val as u128,
Id::U32(val) => val as u128,
Id::U64(val) => val as u128,
Id::U128(val) => val,
Id::Bytes(val) => u128::from_be_bytes(val.as_slice().try_into().unwrap()),
}
}
}