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
#![cfg_attr(not(feature = "std"), no_std)]
#![allow(clippy::all)]
pub mod migrations;
pub mod weights;
mod benchmarking;
#[cfg(test)]
mod mock;
#[cfg(test)]
mod tests;
use codec::{Decode, Encode};
use frame_support::weights::Weight;
pub use weights::WeightInfo;
#[derive(Encode, Decode, Default, PartialEq, Eq, scale_info::TypeInfo)]
#[cfg_attr(feature = "std", derive(Debug))]
pub struct TokenLockInfo<Balance, Moment, AssetId> {
pub tokens: Balance,
pub unlocking_timestamp: Moment,
pub asset_id: AssetId,
}
#[derive(Encode, Decode, Eq, PartialEq, scale_info::TypeInfo)]
pub enum StorageVersion {
V1,
V2,
}
pub use pallet::*;
#[frame_support::pallet]
pub mod pallet {
use crate::{migrations, StorageVersion, TokenLockInfo, WeightInfo};
use common::prelude::{Balance, FixedWrapper};
use common::{balance, AssetInfoProvider};
use frame_support::pallet_prelude::*;
use frame_support::PalletId;
use frame_system::ensure_signed;
use frame_system::pallet_prelude::*;
use hex_literal::hex;
use pallet_timestamp as timestamp;
use sp_runtime::traits::AccountIdConversion;
use sp_std::vec::Vec;
const PALLET_ID: PalletId = PalletId(*b"crstlock");
#[pallet::config]
pub trait Config:
frame_system::Config + assets::Config + technical::Config + timestamp::Config
{
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
type CeresAssetId: Get<Self::AssetId>;
type WeightInfo: WeightInfo;
}
type Assets<T> = assets::Pallet<T>;
pub type Timestamp<T> = timestamp::Pallet<T>;
pub type AccountIdOf<T> = <T as frame_system::Config>::AccountId;
pub type AssetIdOf<T> = <T as assets::Config>::AssetId;
#[pallet::pallet]
#[pallet::generate_store(pub (super) trait Store)]
#[pallet::without_storage_info]
pub struct Pallet<T>(PhantomData<T>);
#[pallet::type_value]
pub fn DefaultForFeesAccount<T: Config>() -> AccountIdOf<T> {
let bytes = hex!("96ea3c9c0be7bbc7b0656a1983db5eed75210256891a9609012362e36815b132");
AccountIdOf::<T>::decode(&mut &bytes[..]).unwrap()
}
#[pallet::storage]
#[pallet::getter(fn fees_account)]
pub type FeesAccount<T: Config> =
StorageValue<_, AccountIdOf<T>, ValueQuery, DefaultForFeesAccount<T>>;
#[pallet::type_value]
pub fn DefaultForAuthorityAccount<T: Config>() -> AccountIdOf<T> {
let bytes = hex!("0a0455d92e1fda8dee17b2c58761c8efca490ef2a1a03322dbfea7379481d517");
AccountIdOf::<T>::decode(&mut &bytes[..]).unwrap()
}
#[pallet::storage]
#[pallet::getter(fn authority_account)]
pub type AuthorityAccount<T: Config> =
StorageValue<_, AccountIdOf<T>, ValueQuery, DefaultForAuthorityAccount<T>>;
#[pallet::type_value]
pub fn DefaultForPalletStorageVersion<T: Config>() -> StorageVersion {
StorageVersion::V1
}
#[pallet::storage]
#[pallet::getter(fn pallet_storage_version)]
pub type PalletStorageVersion<T: Config> =
StorageValue<_, StorageVersion, ValueQuery, DefaultForPalletStorageVersion<T>>;
#[pallet::type_value]
pub fn DefaultForFeeAmount<T: Config>() -> Balance {
balance!(0.005)
}
#[pallet::storage]
#[pallet::getter(fn fee_amount)]
pub type FeeAmount<T: Config> = StorageValue<_, Balance, ValueQuery, DefaultForFeeAmount<T>>;
#[pallet::storage]
#[pallet::getter(fn locker_data)]
pub type TokenLockerData<T: Config> = StorageMap<
_,
Identity,
AccountIdOf<T>,
Vec<TokenLockInfo<Balance, T::Moment, AssetIdOf<T>>>,
ValueQuery,
>;
#[pallet::event]
#[pallet::generate_deposit(pub (super) fn deposit_event)]
pub enum Event<T: Config> {
Locked(AccountIdOf<T>, Balance, AssetIdOf<T>),
Withdrawn(AccountIdOf<T>, Balance, AssetIdOf<T>),
FeeChanged(AccountIdOf<T>, Balance),
}
#[pallet::error]
pub enum Error<T> {
InvalidNumberOfTokens,
Unauthorized,
InvalidUnlockingTimestamp,
NotEnoughFunds,
NotUnlockedYet,
LockInfoDoesNotExist,
}
#[pallet::call]
impl<T: Config> Pallet<T> {
#[pallet::call_index(0)]
#[pallet::weight(<T as Config>::WeightInfo::lock_tokens())]
pub fn lock_tokens(
origin: OriginFor<T>,
asset_id: AssetIdOf<T>,
unlocking_timestamp: T::Moment,
number_of_tokens: Balance,
) -> DispatchResultWithPostInfo {
let user = ensure_signed(origin)?;
ensure!(
number_of_tokens > balance!(0),
Error::<T>::InvalidNumberOfTokens
);
let current_timestamp = Timestamp::<T>::get();
ensure!(
unlocking_timestamp > current_timestamp,
Error::<T>::InvalidUnlockingTimestamp
);
let token_lock_info = TokenLockInfo {
tokens: number_of_tokens,
unlocking_timestamp,
asset_id,
};
let fee = (FixedWrapper::from(number_of_tokens)
* FixedWrapper::from(FeeAmount::<T>::get()))
.try_into_balance()
.unwrap_or(0);
let total = number_of_tokens + fee;
ensure!(
total <= Assets::<T>::free_balance(&asset_id, &user).unwrap_or(0),
Error::<T>::NotEnoughFunds
);
Assets::<T>::transfer_from(&asset_id, &user, &Self::account_id(), number_of_tokens)?;
Assets::<T>::transfer_from(&asset_id, &user, &FeesAccount::<T>::get(), fee)?;
<TokenLockerData<T>>::append(&user, token_lock_info);
Self::deposit_event(Event::Locked(user, number_of_tokens, asset_id));
Ok(().into())
}
#[pallet::call_index(1)]
#[pallet::weight(<T as Config>::WeightInfo::withdraw_tokens())]
pub fn withdraw_tokens(
origin: OriginFor<T>,
asset_id: AssetIdOf<T>,
unlocking_timestamp: T::Moment,
number_of_tokens: Balance,
) -> DispatchResultWithPostInfo {
let user = ensure_signed(origin)?;
ensure!(
number_of_tokens > balance!(0),
Error::<T>::InvalidNumberOfTokens
);
let current_timestamp = Timestamp::<T>::get();
ensure!(
unlocking_timestamp < current_timestamp,
Error::<T>::NotUnlockedYet
);
let mut token_lock_info_vec = <TokenLockerData<T>>::get(&user);
let mut idx = 0;
let mut exist = false;
for (index, lock) in token_lock_info_vec.iter().enumerate() {
if lock.unlocking_timestamp == unlocking_timestamp
&& lock.asset_id == asset_id
&& lock.tokens == number_of_tokens
{
idx = index;
exist = true;
break;
}
}
if !exist {
return Err(Error::<T>::LockInfoDoesNotExist.into());
}
Assets::<T>::transfer_from(&asset_id, &Self::account_id(), &user, number_of_tokens)?;
token_lock_info_vec.remove(idx);
<TokenLockerData<T>>::insert(&user, token_lock_info_vec);
Self::deposit_event(Event::Withdrawn(user, number_of_tokens, asset_id));
Ok(().into())
}
#[pallet::call_index(2)]
#[pallet::weight(<T as Config>::WeightInfo::change_fee())]
pub fn change_fee(origin: OriginFor<T>, new_fee: Balance) -> DispatchResultWithPostInfo {
let user = ensure_signed(origin)?;
if user != AuthorityAccount::<T>::get() {
return Err(Error::<T>::Unauthorized.into());
}
FeeAmount::<T>::put(new_fee);
Self::deposit_event(Event::FeeChanged(user, new_fee));
Ok(().into())
}
}
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
fn on_runtime_upgrade() -> Weight {
if Self::pallet_storage_version() == StorageVersion::V1 {
let weight = migrations::migrate::<T>();
PalletStorageVersion::<T>::put(StorageVersion::V2);
weight
} else {
Weight::zero()
}
}
}
impl<T: Config> Pallet<T> {
fn account_id() -> T::AccountId {
PALLET_ID.into_account_truncating()
}
}
}