-
Notifications
You must be signed in to change notification settings - Fork 95
Expand file tree
/
Copy pathlib.rs
More file actions
446 lines (377 loc) · 12.5 KB
/
Copy pathlib.rs
File metadata and controls
446 lines (377 loc) · 12.5 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
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
// This file is part of Bifrost.
// Copyright (C) 2019-2021 Liebi Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
// Ensure we're `no_std` when compiling for Wasm.
#![cfg_attr(not(feature = "std"), no_std)]
use frame_support::{
pallet_prelude::*,
sp_runtime::traits::{SaturatedConversion, Saturating, Zero},
};
use frame_system::pallet_prelude::*;
use node_primitives::{CurrencyId, LeasePeriod};
use orml_traits::{MultiCurrency, MultiReservableCurrency};
pub use pallet::*;
use sp_std::{cmp::min, collections::btree_set::BTreeSet};
use substrate_fixed::{traits::FromFixed, types::U64F64};
#[cfg(test)]
mod mock;
#[cfg(test)]
mod tests;
#[derive(Encode, Decode, Clone, Eq, PartialEq)]
pub struct OrderInfo<T: Config> {
/// The owner of the order
owner: AccountIdOf<T>,
/// The vsbond type of the order to sell
vsbond: CurrencyId,
/// The quantity of vsbond to sell
supply: BalanceOf<T>,
/// The quantity of vsbond has not be sold
remain: BalanceOf<T>,
unit_price: U64F64,
order_id: OrderId,
order_state: OrderState,
}
impl<T: Config> core::fmt::Debug for OrderInfo<T> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_tuple("")
.field(&self.owner)
.field(&self.vsbond)
.field(&self.supply)
.field(&self.unit_price)
.field(&self.order_id)
.field(&self.order_state)
.finish()
}
}
#[derive(Encode, Decode, Copy, Clone, Eq, PartialEq, Debug)]
enum OrderState {
InTrade,
Revoked,
Clinchd,
}
type OrderId = u64;
type ParaId = u32;
#[allow(type_alias_bounds)]
type AccountIdOf<T: Config> = <T as frame_system::Config>::AccountId;
#[allow(type_alias_bounds)]
type BalanceOf<T: Config> =
<<T as Config>::MultiCurrency as MultiCurrency<AccountIdOf<T>>>::Balance;
#[allow(type_alias_bounds)]
type LeasePeriodOf<T: Config> = <T as frame_system::Config>::BlockNumber;
#[frame_support::pallet]
pub mod pallet {
use super::*;
#[pallet::config]
pub trait Config: frame_system::Config<BlockNumber = LeasePeriod> {
type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;
/// The currency type that buyer to pay
#[pallet::constant]
type InvoicingCurrency: Get<CurrencyId>;
/// The amount of orders in-trade that user can hold
#[pallet::constant]
type MaximumOrderInTrade: Get<u32>;
/// The sale quantity needs to be greater than `MinimumSupply` to create an order
#[pallet::constant]
type MinimumSupply: Get<BalanceOf<Self>>;
type MultiCurrency: MultiCurrency<AccountIdOf<Self>, CurrencyId = CurrencyId>
+ MultiReservableCurrency<AccountIdOf<Self>, CurrencyId = CurrencyId>;
}
#[pallet::error]
pub enum Error<T> {
NotEnoughSupply,
NotFindOrderInfo,
NotEnoughBalanceToUnreserve,
NotEnoughBalanceToReserve,
CantPayThePrice,
ForbidRevokeOrderNotInTrade,
ForbidRevokeOrderWithoutOwnership,
ForbidClinchOrderNotInTrade,
ForbidClinchOrderWithinOwnership,
ExceedMaximumOrderInTrade,
Overflow,
Unexpected,
}
#[pallet::event]
#[pallet::generate_deposit(pub (crate) fn deposit_event)]
pub enum Event<T: Config> {
/// The order has been created.
///
/// [order_id, order_info]
OrderCreated(OrderId, OrderInfo<T>),
/// The order has been revoked.
///
/// [order_id_revoked, order_owner]
OrderRevoked(OrderId, AccountIdOf<T>),
/// The order has been clinched.
///
/// [order_id_clinched, order_owner, order_buyer, quantity]
OrderClinchd(OrderId, AccountIdOf<T>, AccountIdOf<T>, BalanceOf<T>),
}
#[pallet::storage]
#[pallet::getter(fn order_id)]
pub(crate) type NextOrderId<T: Config> = StorageValue<_, OrderId, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn in_trade_order_ids)]
pub(crate) type InTradeOrderIds<T: Config> =
StorageMap<_, Twox64Concat, AccountIdOf<T>, BTreeSet<OrderId>>;
#[pallet::storage]
#[pallet::getter(fn revoked_order_ids)]
pub(crate) type RevokedOrderIds<T: Config> =
StorageMap<_, Twox64Concat, AccountIdOf<T>, BTreeSet<OrderId>>;
#[pallet::storage]
#[pallet::getter(fn clinchd_order_ids)]
pub(crate) type ClinchdOrderIds<T: Config> =
StorageMap<_, Twox64Concat, AccountIdOf<T>, BTreeSet<OrderId>>;
#[pallet::storage]
#[pallet::getter(fn order_info)]
pub(crate) type TotalOrderInfos<T: Config> = StorageMap<_, Twox64Concat, OrderId, OrderInfo<T>>;
#[pallet::pallet]
pub struct Pallet<T>(PhantomData<T>);
#[pallet::call]
impl<T: Config> Pallet<T> {
#[pallet::weight(1_000)]
pub fn create_order(
origin: OriginFor<T>,
#[pallet::compact] index: ParaId,
#[pallet::compact] first_slot: LeasePeriodOf<T>,
#[pallet::compact] last_slot: LeasePeriodOf<T>,
#[pallet::compact] supply: BalanceOf<T>,
unit_price: U64F64,
) -> DispatchResultWithPostInfo {
// Check origin
let owner = ensure_signed(origin)?;
// Check supply
ensure!(supply > T::MinimumSupply::get(), Error::<T>::NotEnoughSupply);
// Construct vsbond
let vsbond =
CurrencyId::VSBond(*T::InvoicingCurrency::get(), index, first_slot, last_slot);
// Check the balance of vsbond
ensure!(
T::MultiCurrency::can_reserve(vsbond, &owner, supply),
Error::<T>::NotEnoughBalanceToReserve
);
let order_in_trade_amount = {
if let Some(sets) = Self::in_trade_order_ids(&owner) {
sets.len() as u32
} else {
0
}
};
ensure!(
order_in_trade_amount < T::MaximumOrderInTrade::get(),
Error::<T>::ExceedMaximumOrderInTrade,
);
// Create OrderInfo
let order_id = Self::next_order_id();
let order_info = OrderInfo::<T> {
owner: owner.clone(),
vsbond,
supply,
remain: supply,
unit_price,
order_id,
order_state: OrderState::InTrade,
};
// Reserve the balance of vsbond_type
T::MultiCurrency::reserve(vsbond, &owner, supply)?;
// Insert OrderInfo to Storage
TotalOrderInfos::<T>::insert(order_id, order_info.clone());
// Add order_id to the order_ids in-trade of account
if !InTradeOrderIds::<T>::contains_key(&owner) {
InTradeOrderIds::<T>::insert(owner.clone(), BTreeSet::<OrderId>::new());
}
InTradeOrderIds::<T>::try_mutate(owner.clone(), |list| match list {
Some(list) => {
list.insert(order_id);
Ok(())
}
None => Err(Error::<T>::Unexpected),
})?;
Self::deposit_event(Event::OrderCreated(order_id, order_info));
Ok(().into())
}
#[pallet::weight(1_000)]
pub fn revoke_order(
origin: OriginFor<T>,
#[pallet::compact] order_id: OrderId,
) -> DispatchResultWithPostInfo {
// Check origin
let from = ensure_signed(origin)?;
// Check OrderInfo
let order_info = Self::order_info(order_id).ok_or(Error::<T>::NotFindOrderInfo)?;
// Check OrderState
ensure!(
order_info.order_state == OrderState::InTrade,
Error::<T>::ForbidRevokeOrderNotInTrade
);
// Check OrderOwner
ensure!(order_info.owner == from, Error::<T>::ForbidRevokeOrderWithoutOwnership);
// Unreserve the vsbond
let reserved_balance =
T::MultiCurrency::reserved_balance(order_info.vsbond, &order_info.owner);
ensure!(reserved_balance >= order_info.remain, Error::<T>::NotEnoughBalanceToUnreserve);
T::MultiCurrency::unreserve(order_info.vsbond, &order_info.owner, order_info.remain);
// Revoke order
TotalOrderInfos::<T>::insert(
order_id,
OrderInfo { order_state: OrderState::Revoked, ..order_info },
);
// Move order_id from `InTrade` to `Revoked`.
InTradeOrderIds::<T>::try_mutate(from.clone(), |list| match list {
Some(list) => {
list.remove(&order_id);
Ok(())
}
None => Err(Error::<T>::Unexpected),
})?;
if !RevokedOrderIds::<T>::contains_key(&from) {
RevokedOrderIds::<T>::insert(from.clone(), BTreeSet::<OrderId>::new());
}
RevokedOrderIds::<T>::try_mutate(from.clone(), |list| match list {
Some(list) => {
list.insert(order_id);
Ok(())
}
None => Err(Error::<T>::Unexpected),
})?;
Self::deposit_event(Event::OrderRevoked(order_id, from));
Ok(().into())
}
#[pallet::weight(1_000)]
pub fn clinch_order(
origin: OriginFor<T>,
#[pallet::compact] order_id: OrderId,
) -> DispatchResultWithPostInfo {
let order_info = Self::order_info(order_id).ok_or(Error::<T>::NotFindOrderInfo)?;
// Check OrderState
ensure!(
order_info.order_state == OrderState::InTrade,
Error::<T>::ForbidClinchOrderNotInTrade
);
Self::partial_clinch_order(origin, order_id, order_info.remain)?;
Ok(().into())
}
#[pallet::weight(1_000)]
pub fn partial_clinch_order(
origin: OriginFor<T>,
#[pallet::compact] order_id: OrderId,
#[pallet::compact] quantity: BalanceOf<T>,
) -> DispatchResultWithPostInfo {
// Check Zero
if quantity.is_zero() {
return Ok(().into());
}
// Check origin
let buyer = ensure_signed(origin)?;
// Check OrderInfo
let order_info = Self::order_info(order_id).ok_or(Error::<T>::NotFindOrderInfo)?;
// Check OrderState
ensure!(
order_info.order_state == OrderState::InTrade,
Error::<T>::ForbidClinchOrderNotInTrade
);
// Check OrderOwner
ensure!(order_info.owner != buyer, Error::<T>::ForbidClinchOrderWithinOwnership);
// Calculate the real quantity to clinch
let quantity_clinchd = min(order_info.remain, quantity);
// Calculate the total price that buyer need to pay
let total_price = Self::total_price(quantity_clinchd, order_info.unit_price);
// Check the balance of buyer
T::MultiCurrency::ensure_can_withdraw(T::InvoicingCurrency::get(), &buyer, total_price)
.map_err(|_| Error::<T>::CantPayThePrice)?;
// Get the new OrderInfo
let new_order_info = if quantity_clinchd == order_info.remain {
OrderInfo { remain: Zero::zero(), order_state: OrderState::Clinchd, ..order_info }
} else {
OrderInfo {
remain: order_info.remain.saturating_sub(quantity_clinchd),
..order_info
}
};
// Unreserve the balance of vsbond to transfer
let reserved_balance =
T::MultiCurrency::reserved_balance(new_order_info.vsbond, &new_order_info.owner);
ensure!(reserved_balance >= quantity_clinchd, Error::<T>::NotEnoughBalanceToUnreserve);
T::MultiCurrency::unreserve(
new_order_info.vsbond,
&new_order_info.owner,
quantity_clinchd,
);
// Exchange: Transfer vsbond from owner to buyer
T::MultiCurrency::transfer(
new_order_info.vsbond,
&new_order_info.owner,
&buyer,
quantity_clinchd,
)?;
// Exchange: Transfer token from buyer to owner
T::MultiCurrency::transfer(
T::InvoicingCurrency::get(),
&buyer,
&new_order_info.owner,
total_price,
)?;
// Move order_id from InTrade to Clinchd if meets condition
if new_order_info.order_state == OrderState::Clinchd {
InTradeOrderIds::<T>::try_mutate(
new_order_info.owner.clone(),
|list| match list {
Some(list) => {
list.remove(&order_id);
Ok(())
}
None => Err(Error::<T>::Unexpected),
},
)?;
if !ClinchdOrderIds::<T>::contains_key(&new_order_info.owner) {
ClinchdOrderIds::<T>::insert(
new_order_info.owner.clone(),
BTreeSet::<OrderId>::new(),
);
}
ClinchdOrderIds::<T>::try_mutate(
new_order_info.owner.clone(),
|list| match list {
Some(list) => {
list.insert(order_id);
Ok(())
}
None => Err(Error::<T>::Unexpected),
},
)?;
}
// Change the OrderInfo in Storage
TotalOrderInfos::<T>::insert(order_id, new_order_info.clone());
Self::deposit_event(Event::<T>::OrderClinchd(
order_id,
new_order_info.owner,
buyer,
quantity_clinchd,
));
Ok(().into())
}
}
impl<T: Config> Pallet<T> {
pub(crate) fn next_order_id() -> OrderId {
let next_order_id = Self::order_id();
NextOrderId::<T>::mutate(|current| *current += 1);
next_order_id
}
pub(crate) fn total_price(quantity: BalanceOf<T>, unit_price: U64F64) -> BalanceOf<T> {
let quantity: u128 = quantity.saturated_into();
let total_price = u128::from_fixed((unit_price * quantity).ceil());
BalanceOf::<T>::saturated_from(total_price)
}
}
}
// TODO: Maybe impl Auction trait for vsbond-auction