-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.rs
662 lines (573 loc) · 18.8 KB
/
lib.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
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
//! # Double Auction
//!
//! ## Overview
//!
//! This module provides a basic implement for order-book style on-chain double auctioning.
//!
//! This is the matching layer of a decentralized marketplace for electrical energy.
//! Sellers are categorized based on how much electricity they intend to sell.
//! Buyers are also categorized based on how much electricity they intend to buy.
//!
//! The highest bidding buyer in the same category with a seller is matched
//! when the auction period of a seller is over.
//!
//! The seller has the benefit of getting the best price at a given point in time for their
//! category, while the buyer can choose a margin of safety for every buy.
//!
//! Auctions are executed in the auction execution queue based on their ending time
//!
//! NOTE: this mocdule does not implement how payment is handled.
//!
//! `Data`:
//! -- AuctionData<AccountId, BlockNumber, Bid, Tier> {
//! pub auction_id: AuctionId,
//! pub seller_id: AccountId,
//! pub quantity: u128,
//! pub starting_bid: Bid,
//! pub bids: Vec<Bid>,
//! pub auction_period: BlockNumber,
//! pub auction_status: AuctionStatus,
//! pub start_at: BlockNumber,
//! pub end_at: BlockNumber,
//! pub highest_bid: Bid,
//! pub auction_category: Tier,
//! }
//! -- AuctionInfoo<AccountId, PartyType> {
//! pub participant_id: Option<AccountId>,
//! pub party_type: PartyType,
//! pub auctions: Vec<u64>, // Maximum of 5 auction id
//! }
//! -- AuctionsExecutionQueue: { (execution_block, auction_id) -> () }
//! -- Tier: u128, // 0, 1, 2, ...
//! -- Auctions { auction_id -> AuctionData }
//! -- AuctionsOf { account_id -> AuctionInfo }
//!
//! `Interface`:
//! -- new(...)
//! -- bid(...)
//! -- cancel(...)
//!
//! `Hooks`:
//! -- on_auction_ended
//!
//! `RPC`:
#![cfg_attr(not(feature = "std"), no_std)]
pub use pallet::*;
#[cfg(test)]
mod mock;
#[cfg(test)]
mod tests;
#[cfg(feature = "runtime-benchmarks")]
mod benchmarking;
// pub mod weights;
// pub use weights::*;
#[frame_support::pallet]
pub mod pallet {
use super::*;
use crate::pallet::sp_runtime::{traits::AtLeast32BitUnsigned, FixedPointOperand};
use frame_support::{
dispatch::{fmt::Debug, Codec, EncodeLike},
pallet_prelude::*,
sp_runtime,
};
use frame_system::pallet_prelude::*;
use scale_info::prelude::{vec, vec::Vec};
/// The current storage version.
const STORAGE_VERSION: frame_support::traits::StorageVersion =
frame_support::traits::StorageVersion::new(1);
#[pallet::pallet]
#[pallet::without_storage_info]
#[pallet::storage_version(STORAGE_VERSION)]
pub struct Pallet<T, I = ()>(PhantomData<(T, I)>);
/// Configure the pallet by specifying the parameters and types on which it depends.
#[pallet::config]
pub trait Config<I: 'static = ()>: frame_system::Config {
/// Because this pallet emits events, it depends on the runtime's definition of an event.
type RuntimeEvent: From<Event<Self, I>>
+ IsType<<Self as frame_system::Config>::RuntimeEvent>;
// /// Type representing the weight of this pallet
// type WeightInfo: WeightInfo;
// Unique auction identifier
type AuctionId: Parameter
+ Member
+ AtLeast32BitUnsigned
+ Codec
+ Default
+ Copy
+ MaybeSerializeDeserialize
+ Debug
+ MaxEncodedLen
+ EncodeLike<u64>
+ TypeInfo
+ FixedPointOperand
+ From<u64>;
}
//////////////////////
// Storage types //
/////////////////////
// Buyers bid
#[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, TypeInfo)]
pub struct Bid<AccountId> {
bidder: AccountId,
bid: u128,
}
// Status of an auction, live auctions accepts bids
#[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, TypeInfo)]
pub enum AuctionStatus {
Open,
Closed,
}
impl Default for AuctionStatus {
fn default() -> Self {
AuctionStatus::Open
}
}
// Essential data for an auction
#[derive(Clone, Encode, Decode, Default, Eq, PartialEq, RuntimeDebug, TypeInfo)]
pub struct AuctionData<AccountId, BlockNumber, Bid, Tier, AuctionId> {
pub auction_id: AuctionId,
pub seller_id: AccountId,
pub quantity: u128,
pub starting_bid: Bid,
pub bids: Vec<Bid>,
pub auction_period: BlockNumber,
pub auction_status: AuctionStatus,
pub start_at: BlockNumber,
pub end_at: BlockNumber,
pub highest_bid: Bid,
pub auction_category: Tier,
}
// Tier of an auction sale
// Higher quantity of energy for sale leads to higher tier
#[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, TypeInfo)]
pub struct Tier {
pub level: u32,
}
impl Default for Tier {
fn default() -> Self {
Tier { level: 1 }
}
}
#[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, TypeInfo)]
pub enum PartyType {
Seller,
Buyer,
}
impl Default for PartyType {
fn default() -> Self {
PartyType::Seller
}
}
// Auctions linked to an auction participant
#[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, TypeInfo)]
pub struct AuctionInfo<AccountId, BlockNumber, Bid, Tier, AuctionId, PartyType> {
pub participant_id: Option<AccountId>,
pub party_type: PartyType,
pub auctions: Vec<AuctionData<AccountId, BlockNumber, Bid, Tier, AuctionId>>, /* Maximum* length of 5 */
}
impl<AccountId, BlockNumber, AuctionId> Default
for AuctionInfo<AccountId, BlockNumber, Bid<AccountId>, Tier, AuctionId, PartyType>
{
fn default() -> Self {
AuctionInfo { participant_id: None, party_type: PartyType::Seller, auctions: vec![] }
}
}
//////////////////////
// Storage item //
/////////////////////
#[pallet::storage]
#[pallet::getter(fn auctions_index)]
pub(super) type AuctionIndex<T: Config<I>, I: 'static = ()> = StorageValue<_, T::AuctionId>;
/// Stores on-going and future auctions of participants
/// Maximum of 5 auction cachesd at a time
// TODO: use BoundedVec
#[pallet::storage]
#[pallet::getter(fn auctions_of)]
pub(super) type AuctionsOf<T: Config<I>, I: 'static = ()> = StorageMap<
_,
Twox64Concat,
T::AccountId,
AuctionInfo<
T::AccountId,
BlockNumberFor<T>,
Bid<T::AccountId>,
Tier,
T::AuctionId,
PartyType,
>,
OptionQuery,
>;
/// Stores on-going and future auctions of participants
/// Closed auction are removed to optimize on-chain storage
#[pallet::storage]
#[pallet::getter(fn auctions)]
pub(super) type Auctions<T: Config<I>, I: 'static = ()> = StorageMap<
_,
Twox64Concat,
T::AuctionId,
AuctionData<T::AccountId, BlockNumberFor<T>, Bid<T::AccountId>, Tier, T::AuctionId>,
OptionQuery,
>;
/// Index auctions by end time.
#[pallet::storage]
#[pallet::getter(fn auction_end_time)]
pub(super) type AuctionsExecutionQueue<T: Config<I>, I: 'static = ()> = StorageDoubleMap<
_,
Twox64Concat,
BlockNumberFor<T>,
Blake2_128Concat,
T::AuctionId,
(),
OptionQuery,
>;
/////////////////////
// Genesis config //
////////////////////
#[pallet::genesis_config]
pub struct GenesisConfig<T: Config<I>, I: 'static = ()> {
pub auction_index: T::AuctionId,
}
impl<T: Config<I>, I: 'static> Default for GenesisConfig<T, I> {
fn default() -> Self {
Self { auction_index: Default::default() }
}
}
#[pallet::genesis_build]
impl<T: Config<I>, I: 'static> BuildGenesisConfig for GenesisConfig<T, I> {
fn build(&self) {
let initial_id = self.auction_index;
<AuctionIndex<T, I>>::put(initial_id);
}
}
///////////////////
// Pallet hooks //
//////////////////
#[pallet::hooks]
impl<T: Config<I>, I: 'static> Hooks<BlockNumberFor<T>> for Pallet<T, I> {
fn on_initialize(_now: BlockNumberFor<T>) -> Weight {
// T::WeightInfo::on_finalize(AuctionsExecutionQueue::<T>::iter_prefix(now).count() as
// u32)
Weight::from_all(100_000_000u64)
}
fn on_finalize(now: BlockNumberFor<T>) {
// get auction ready for execution
for (auction_id, _) in AuctionsExecutionQueue::<T, I>::drain_prefix(now) {
if let Some(auction) = Auctions::<T, I>::take(auction_id) {
// handle auction execution
Self::on_auction_ended(auction.auction_id);
}
}
}
}
//////////////////////
// Runtime events //
/////////////////////
// runtime event for important runtime actions
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config<I>, I: 'static = ()> {
AuctionCreated {
auction_id: T::AuctionId,
seller_id: T::AccountId,
energy_quantity: u128,
starting_price: u128,
},
AuctionBidAdded {
auction_id: T::AuctionId,
seller_id: T::AccountId,
energy_quantity: u128,
bid: Bid<T::AccountId>,
},
AuctionMatched {
auction_id: T::AuctionId,
seller_id: T::AccountId,
energy_quantity: u128,
starting_price: u128,
highest_bid: Bid<T::AccountId>,
matched_at: BlockNumberFor<T>,
},
AuctionExecuted {
auction_id: T::AuctionId,
seller_id: T::AccountId,
buyer_id: T::AccountId,
energy_quantity: u128,
starting_price: u128,
highest_bid: u128,
executed_at: BlockNumberFor<T>,
},
AuctionCanceled {
auction_id: T::AuctionId,
seller_id: T::AccountId,
energy_quantity: u128,
starting_price: u128,
},
}
//////////////////////
// Pallet errors //
/////////////////////
// Errors inform users that something went wrong.
#[pallet::error]
pub enum Error<T, I = ()> {
AuctionDoesNotExist,
AuctionIsOver,
InsuffficientAttachedDeposit,
}
///////////////////////////
// Pallet extrinsics //
//////////////////////////
#[pallet::call]
impl<T: Config<I>, I: 'static> Pallet<T, I> {
#[pallet::call_index(0)]
#[pallet::weight(100_000_000)]
pub fn new_auction(
origin: OriginFor<T>,
energy_quantity: u128, // in KWH
starting_price: u128, // in parachain native token
auction_period: u16, // in minutes
) -> DispatchResult {
// Check that the extrinsic was signed by seller or return error.
let seller = ensure_signed(origin)?;
// get current_auction_id
let current_auction_id = AuctionIndex::<T, I>::get().expect("current auction id");
// Calculate auction period
// convert minutes to seconds and
// divide by 6 (assumming each blocktime is 6 seconds)
let auction_period_in_block_number =
(auction_period.checked_mul(60).unwrap()).checked_div(6).unwrap().into();
// Get current block number from the FRAME System pallet.
let starting_block_number = <frame_system::Pallet<T>>::block_number();
let ending_block_number = starting_block_number + auction_period_in_block_number;
// Create starting bid
let starting_bid = Bid::<T::AccountId> { bidder: seller.clone(), bid: starting_price };
// Categorize auction
let category;
if energy_quantity < 5 {
category = Tier::default()
} else {
category = Tier { level: 2 }
}
// Create auction data
let auction_data = AuctionData {
auction_id: current_auction_id,
seller_id: seller.clone(),
quantity: energy_quantity,
starting_bid: starting_bid.clone(),
bids: vec![],
auction_period: auction_period_in_block_number,
auction_status: AuctionStatus::default(),
start_at: starting_block_number,
end_at: ending_block_number,
highest_bid: starting_bid,
auction_category: category,
};
// Get seller's auction information
let mut seller_auction_info =
AuctionsOf::<T, I>::get(seller.clone()).unwrap_or_default();
// Ensure cached autions are less than 5
// remove oldest auction
if seller_auction_info.auctions.len() > 5 {
seller_auction_info.auctions.pop();
}
// Update seller's auctions
seller_auction_info.auctions.push(auction_data.clone());
// Store seller's auction into storage
seller_auction_info = AuctionInfo {
participant_id: Some(seller.clone()),
party_type: PartyType::Seller,
auctions: seller_auction_info.auctions,
};
AuctionsOf::<T, I>::insert(&seller, seller_auction_info);
// Add auction to execution queue
AuctionsExecutionQueue::<T, I>::insert(
auction_data.end_at,
auction_data.auction_id,
(),
);
// Store globalauction to storage
Auctions::<T, I>::insert(&auction_data.auction_id, auction_data.clone());
// update auction id
let next_id = current_auction_id + T::AuctionId::from(1u64);
AuctionIndex::<T, I>::set(Some(next_id));
// Emit an event that the auction was created.
Self::deposit_event(Event::AuctionCreated {
auction_id: auction_data.auction_id,
seller_id: seller,
energy_quantity,
starting_price,
});
Ok(())
}
#[pallet::call_index(1)]
#[pallet::weight(100_000_000)]
pub fn cancel(origin: OriginFor<T>, auction_id: T::AuctionId) -> DispatchResult {
// Check that the extrinsic was signed by seller or return error.
let _signer = ensure_signed(origin)?;
// Check auction is exist
ensure!(Auctions::<T, I>::contains_key(auction_id), Error::<T, I>::AuctionDoesNotExist);
// Get auction from global auction
let mut auction_data =
Auctions::<T, I>::get(auction_id).expect("data for auction with specified id");
// Check auction is live
ensure!(
matches!(auction_data.auction_status, AuctionStatus::Open),
Error::<T, I>::AuctionIsOver
);
// Close auction
auction_data.auction_status = AuctionStatus::Closed;
// Remove auction from global auctions
Auctions::<T, I>::remove(auction_data.auction_id);
// Get seller's auction info
let mut sellers_auction_info = AuctionsOf::<T, I>::get(auction_data.seller_id.clone())
.expect("information of seller with specified id");
// Remove auction from seller's auctions
for (index, auction) in sellers_auction_info.auctions.clone().into_iter().enumerate() {
// get matching auction(s)
if auction.auction_id == auction_id {
sellers_auction_info.auctions.remove(index);
}
}
// Remove auction from execution queue
AuctionsExecutionQueue::<T, I>::remove(auction_data.end_at, auction_data.auction_id);
// Emit an event that the auction was canceled.
Self::deposit_event(Event::AuctionCanceled {
auction_id: auction_data.auction_id,
seller_id: auction_data.seller_id,
energy_quantity: auction_data.quantity,
starting_price: auction_data.starting_bid.bid,
});
Ok(())
}
#[pallet::call_index(2)]
#[pallet::weight(100_000_000)]
pub fn bid(origin: OriginFor<T>, auction_id: T::AuctionId, bid: u128) -> DispatchResult {
// Check that the extrinsic was signed by buyer or return error.
let buyer_id = ensure_signed(origin)?;
// Check auction is exist
ensure!(Auctions::<T, I>::contains_key(auction_id), Error::<T, I>::AuctionDoesNotExist);
// Get auction from global auction
let mut auction_data =
Auctions::<T, I>::get(auction_id).expect("data for auction with specified id");
// Check auction is live
ensure!(
matches!(auction_data.auction_status, AuctionStatus::Open),
Error::<T, I>::AuctionIsOver
);
// Create new bid
let new_bid = Bid::<T::AccountId> { bidder: buyer_id.clone(), bid };
// check if bid is highest bid
if new_bid.bid > auction_data.bids.first().expect("seller's starting bid").bid {
// add to top of auction bids
auction_data.bids.insert(0, new_bid.clone());
}
// get buyer's auction information
let buyer_auction_info = AuctionsOf::<T, I>::get(buyer_id.clone());
match buyer_auction_info {
// if buyer info already initialized, update info
Some(mut auction_info) => {
for (index, auction) in auction_info.auctions.clone().into_iter().enumerate() {
// Ensure auction is within limit
if auction_info.auctions.len() >= 5 {
auction_info.auctions.pop();
}
// get matching auction
if auction.auction_id == auction_id {
// insert new auction
auction_info.auctions.insert(index, auction_data.clone());
// update runtime storage
AuctionsOf::<T, I>::insert(
&buyer_id,
AuctionInfo {
participant_id: Some(buyer_id.clone()),
party_type: PartyType::Seller,
auctions: auction_info.auctions.clone(),
},
)
}
}
},
// initialized and update information
None => {
// Assign default information
let mut auction_info =
AuctionsOf::<T, I>::get(buyer_id.clone()).unwrap_or_default();
// Add auction to buyers information
auction_info.auctions.push(auction_data.clone());
// update runtime storage
AuctionsOf::<T, I>::insert(
&buyer_id,
AuctionInfo {
participant_id: Some(buyer_id.clone()),
party_type: PartyType::Seller,
auctions: auction_info.auctions.clone(),
},
)
},
}
// Get seller's auction information
let mut seller_auction_info = AuctionsOf::<T, I>::get(auction_data.clone().seller_id)
.expect("information of seller with specified id");
// Update seller's auction information
for (index, auction) in seller_auction_info.auctions.clone().into_iter().enumerate() {
// Ensure auction is within limit
if seller_auction_info.auctions.len() >= 5 {
seller_auction_info.auctions.pop();
}
// get matching auction
if auction.auction_id == auction_id {
// insert new auction
seller_auction_info.auctions.insert(index, auction_data.clone());
// update runtime storage
AuctionsOf::<T, I>::insert(
&buyer_id,
AuctionInfo {
participant_id: Some(buyer_id.clone()),
party_type: PartyType::Seller,
auctions: seller_auction_info.auctions.clone(),
},
)
}
}
// Update global auction
Auctions::<T, I>::insert(&auction_data.auction_id, auction_data.clone());
// Emit an event that the bid was created.
Self::deposit_event(Event::AuctionBidAdded {
auction_id: auction_data.auction_id,
seller_id: auction_data.seller_id,
energy_quantity: auction_data.quantity,
bid: new_bid,
});
Ok(())
}
}
///////////////////////
/// auction handler //
//////////////////////
impl<T: Config<I>, I: 'static> Pallet<T, I> {
fn on_auction_ended(auction_id: T::AuctionId) {
// Get auction data
let auction_data =
Auctions::<T, I>::get(auction_id).expect("data for auction with specified id");
let now = <frame_system::Pallet<T>>::block_number();
// emit event that auction is matched
Self::deposit_event(Event::AuctionMatched {
auction_id: auction_data.auction_id,
seller_id: auction_data.seller_id.clone(),
energy_quantity: auction_data.quantity,
starting_price: auction_data.starting_bid.bid,
highest_bid: auction_data.highest_bid.clone(),
matched_at: now,
});
// -------------Some logic can be added here
// emit evnt that auction has be executed
Self::deposit_event(Event::AuctionExecuted {
auction_id: auction_data.auction_id,
seller_id: auction_data.seller_id,
buyer_id: auction_data.highest_bid.bidder,
energy_quantity: auction_data.quantity,
starting_price: auction_data.starting_bid.bid,
highest_bid: auction_data.highest_bid.bid,
executed_at: now,
});
}
}
}