use crate::{
slot_range::SlotRange,
traits::{AuctionStatus, Auctioneer, LeaseError, Leaser, Registrar},
};
use alloc::{vec, vec::Vec};
use codec::Decode;
use core::mem::swap;
use frame_support::{
dispatch::DispatchResult,
ensure,
traits::{Currency, Get, Randomness, ReservableCurrency},
weights::Weight,
};
use frame_system::pallet_prelude::BlockNumberFor;
pub use pallet::*;
use polkadot_primitives::Id as ParaId;
use sp_runtime::traits::{CheckedSub, One, Saturating, Zero};
type CurrencyOf<T> = <<T as Config>::Leaser as Leaser<BlockNumberFor<T>>>::Currency;
type BalanceOf<T> = <<<T as Config>::Leaser as Leaser<BlockNumberFor<T>>>::Currency as Currency<
<T as frame_system::Config>::AccountId,
>>::Balance;
pub trait WeightInfo {
fn new_auction() -> Weight;
fn bid() -> Weight;
fn cancel_auction() -> Weight;
fn on_initialize() -> Weight;
}
pub struct TestWeightInfo;
impl WeightInfo for TestWeightInfo {
fn new_auction() -> Weight {
Weight::zero()
}
fn bid() -> Weight {
Weight::zero()
}
fn cancel_auction() -> Weight {
Weight::zero()
}
fn on_initialize() -> Weight {
Weight::zero()
}
}
pub type AuctionIndex = u32;
type LeasePeriodOf<T> = <<T as Config>::Leaser as Leaser<BlockNumberFor<T>>>::LeasePeriod;
type WinningData<T> = [Option<(<T as frame_system::Config>::AccountId, ParaId, BalanceOf<T>)>;
SlotRange::SLOT_RANGE_COUNT];
type WinnersData<T> =
Vec<(<T as frame_system::Config>::AccountId, ParaId, BalanceOf<T>, SlotRange)>;
#[frame_support::pallet]
pub mod pallet {
use super::*;
use frame_support::{dispatch::DispatchClass, pallet_prelude::*, traits::EnsureOrigin};
use frame_system::{ensure_root, ensure_signed, pallet_prelude::*};
#[pallet::pallet]
pub struct Pallet<T>(_);
#[pallet::config]
pub trait Config: frame_system::Config {
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
type Leaser: Leaser<
BlockNumberFor<Self>,
AccountId = Self::AccountId,
LeasePeriod = BlockNumberFor<Self>,
>;
type Registrar: Registrar<AccountId = Self::AccountId>;
#[pallet::constant]
type EndingPeriod: Get<BlockNumberFor<Self>>;
#[pallet::constant]
type SampleLength: Get<BlockNumberFor<Self>>;
type Randomness: Randomness<Self::Hash, BlockNumberFor<Self>>;
type InitiateOrigin: EnsureOrigin<Self::RuntimeOrigin>;
type WeightInfo: WeightInfo;
}
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
AuctionStarted {
auction_index: AuctionIndex,
lease_period: LeasePeriodOf<T>,
ending: BlockNumberFor<T>,
},
AuctionClosed { auction_index: AuctionIndex },
Reserved { bidder: T::AccountId, extra_reserved: BalanceOf<T>, total_amount: BalanceOf<T> },
Unreserved { bidder: T::AccountId, amount: BalanceOf<T> },
ReserveConfiscated { para_id: ParaId, leaser: T::AccountId, amount: BalanceOf<T> },
BidAccepted {
bidder: T::AccountId,
para_id: ParaId,
amount: BalanceOf<T>,
first_slot: LeasePeriodOf<T>,
last_slot: LeasePeriodOf<T>,
},
WinningOffset { auction_index: AuctionIndex, block_number: BlockNumberFor<T> },
}
#[pallet::error]
pub enum Error<T> {
AuctionInProgress,
LeasePeriodInPast,
ParaNotRegistered,
NotCurrentAuction,
NotAuction,
AuctionEnded,
AlreadyLeasedOut,
}
#[pallet::storage]
pub type AuctionCounter<T> = StorageValue<_, AuctionIndex, ValueQuery>;
#[pallet::storage]
pub type AuctionInfo<T: Config> = StorageValue<_, (LeasePeriodOf<T>, BlockNumberFor<T>)>;
#[pallet::storage]
pub type ReservedAmounts<T: Config> =
StorageMap<_, Twox64Concat, (T::AccountId, ParaId), BalanceOf<T>>;
#[pallet::storage]
pub type Winning<T: Config> = StorageMap<_, Twox64Concat, BlockNumberFor<T>, WinningData<T>>;
#[pallet::extra_constants]
impl<T: Config> Pallet<T> {
#[pallet::constant_name(SlotRangeCount)]
fn slot_range_count() -> u32 {
SlotRange::SLOT_RANGE_COUNT as u32
}
#[pallet::constant_name(LeasePeriodsPerSlot)]
fn lease_periods_per_slot() -> u32 {
SlotRange::LEASE_PERIODS_PER_SLOT as u32
}
}
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
fn on_initialize(n: BlockNumberFor<T>) -> Weight {
let mut weight = T::DbWeight::get().reads(1);
if let AuctionStatus::EndingPeriod(offset, _sub_sample) = Self::auction_status(n) {
weight = weight.saturating_add(T::DbWeight::get().reads(1));
if !Winning::<T>::contains_key(&offset) {
weight = weight.saturating_add(T::DbWeight::get().writes(1));
let winning_data = offset
.checked_sub(&One::one())
.and_then(Winning::<T>::get)
.unwrap_or([Self::EMPTY; SlotRange::SLOT_RANGE_COUNT]);
Winning::<T>::insert(offset, winning_data);
}
}
if let Some((winning_ranges, auction_lease_period_index)) = Self::check_auction_end(n) {
Self::manage_auction_end(auction_lease_period_index, winning_ranges);
weight = weight.saturating_add(T::WeightInfo::on_initialize());
}
weight
}
}
#[pallet::call]
impl<T: Config> Pallet<T> {
#[pallet::call_index(0)]
#[pallet::weight((T::WeightInfo::new_auction(), DispatchClass::Operational))]
pub fn new_auction(
origin: OriginFor<T>,
#[pallet::compact] duration: BlockNumberFor<T>,
#[pallet::compact] lease_period_index: LeasePeriodOf<T>,
) -> DispatchResult {
T::InitiateOrigin::ensure_origin(origin)?;
Self::do_new_auction(duration, lease_period_index)
}
#[pallet::call_index(1)]
#[pallet::weight(T::WeightInfo::bid())]
pub fn bid(
origin: OriginFor<T>,
#[pallet::compact] para: ParaId,
#[pallet::compact] auction_index: AuctionIndex,
#[pallet::compact] first_slot: LeasePeriodOf<T>,
#[pallet::compact] last_slot: LeasePeriodOf<T>,
#[pallet::compact] amount: BalanceOf<T>,
) -> DispatchResult {
let who = ensure_signed(origin)?;
Self::handle_bid(who, para, auction_index, first_slot, last_slot, amount)?;
Ok(())
}
#[pallet::call_index(2)]
#[pallet::weight(T::WeightInfo::cancel_auction())]
pub fn cancel_auction(origin: OriginFor<T>) -> DispatchResult {
ensure_root(origin)?;
for ((bidder, _), amount) in ReservedAmounts::<T>::drain() {
CurrencyOf::<T>::unreserve(&bidder, amount);
}
#[allow(deprecated)]
Winning::<T>::remove_all(None);
AuctionInfo::<T>::kill();
Ok(())
}
}
}
impl<T: Config> Auctioneer<BlockNumberFor<T>> for Pallet<T> {
type AccountId = T::AccountId;
type LeasePeriod = BlockNumberFor<T>;
type Currency = CurrencyOf<T>;
fn new_auction(
duration: BlockNumberFor<T>,
lease_period_index: LeasePeriodOf<T>,
) -> DispatchResult {
Self::do_new_auction(duration, lease_period_index)
}
fn auction_status(now: BlockNumberFor<T>) -> AuctionStatus<BlockNumberFor<T>> {
let early_end = match AuctionInfo::<T>::get() {
Some((_, early_end)) => early_end,
None => return AuctionStatus::NotStarted,
};
let after_early_end = match now.checked_sub(&early_end) {
Some(after_early_end) => after_early_end,
None => return AuctionStatus::StartingPeriod,
};
let ending_period = T::EndingPeriod::get();
if after_early_end < ending_period {
let sample_length = T::SampleLength::get().max(One::one());
let sample = after_early_end / sample_length;
let sub_sample = after_early_end % sample_length;
return AuctionStatus::EndingPeriod(sample, sub_sample)
} else {
return AuctionStatus::VrfDelay(after_early_end - ending_period)
}
}
fn place_bid(
bidder: T::AccountId,
para: ParaId,
first_slot: LeasePeriodOf<T>,
last_slot: LeasePeriodOf<T>,
amount: BalanceOf<T>,
) -> DispatchResult {
Self::handle_bid(bidder, para, AuctionCounter::<T>::get(), first_slot, last_slot, amount)
}
fn lease_period_index(b: BlockNumberFor<T>) -> Option<(Self::LeasePeriod, bool)> {
T::Leaser::lease_period_index(b)
}
#[cfg(any(feature = "runtime-benchmarks", test))]
fn lease_period_length() -> (BlockNumberFor<T>, BlockNumberFor<T>) {
T::Leaser::lease_period_length()
}
fn has_won_an_auction(para: ParaId, bidder: &T::AccountId) -> bool {
!T::Leaser::deposit_held(para, bidder).is_zero()
}
}
impl<T: Config> Pallet<T> {
const EMPTY: Option<(<T as frame_system::Config>::AccountId, ParaId, BalanceOf<T>)> = None;
fn do_new_auction(
duration: BlockNumberFor<T>,
lease_period_index: LeasePeriodOf<T>,
) -> DispatchResult {
let maybe_auction = AuctionInfo::<T>::get();
ensure!(maybe_auction.is_none(), Error::<T>::AuctionInProgress);
let now = frame_system::Pallet::<T>::block_number();
if let Some((current_lease_period, _)) = T::Leaser::lease_period_index(now) {
ensure!(lease_period_index >= current_lease_period, Error::<T>::LeasePeriodInPast);
}
let n = AuctionCounter::<T>::mutate(|n| {
*n += 1;
*n
});
let ending = frame_system::Pallet::<T>::block_number().saturating_add(duration);
AuctionInfo::<T>::put((lease_period_index, ending));
Self::deposit_event(Event::<T>::AuctionStarted {
auction_index: n,
lease_period: lease_period_index,
ending,
});
Ok(())
}
pub fn handle_bid(
bidder: T::AccountId,
para: ParaId,
auction_index: u32,
first_slot: LeasePeriodOf<T>,
last_slot: LeasePeriodOf<T>,
amount: BalanceOf<T>,
) -> DispatchResult {
ensure!(T::Registrar::is_registered(para), Error::<T>::ParaNotRegistered);
ensure!(auction_index == AuctionCounter::<T>::get(), Error::<T>::NotCurrentAuction);
let (first_lease_period, _) = AuctionInfo::<T>::get().ok_or(Error::<T>::NotAuction)?;
let auction_status = Self::auction_status(frame_system::Pallet::<T>::block_number());
let offset = match auction_status {
AuctionStatus::NotStarted => return Err(Error::<T>::AuctionEnded.into()),
AuctionStatus::StartingPeriod => Zero::zero(),
AuctionStatus::EndingPeriod(o, _) => o,
AuctionStatus::VrfDelay(_) => return Err(Error::<T>::AuctionEnded.into()),
};
ensure!(
!T::Leaser::already_leased(para, first_slot, last_slot),
Error::<T>::AlreadyLeasedOut
);
let range = SlotRange::new_bounded(first_lease_period, first_slot, last_slot)?;
let range_index = range as u8 as usize;
let mut current_winning = Winning::<T>::get(offset)
.or_else(|| offset.checked_sub(&One::one()).and_then(Winning::<T>::get))
.unwrap_or([Self::EMPTY; SlotRange::SLOT_RANGE_COUNT]);
if current_winning[range_index].as_ref().map_or(true, |last| amount > last.2) {
let existing_lease_deposit = T::Leaser::deposit_held(para, &bidder);
let reserve_required = amount.saturating_sub(existing_lease_deposit);
let bidder_para = (bidder.clone(), para);
let already_reserved = ReservedAmounts::<T>::get(&bidder_para).unwrap_or_default();
if let Some(additional) = reserve_required.checked_sub(&already_reserved) {
CurrencyOf::<T>::reserve(&bidder, additional)?;
ReservedAmounts::<T>::insert(&bidder_para, reserve_required);
Self::deposit_event(Event::<T>::Reserved {
bidder: bidder.clone(),
extra_reserved: additional,
total_amount: reserve_required,
});
}
let mut outgoing_winner = Some((bidder.clone(), para, amount));
swap(&mut current_winning[range_index], &mut outgoing_winner);
if let Some((who, para, _amount)) = outgoing_winner {
if auction_status.is_starting() &&
current_winning
.iter()
.filter_map(Option::as_ref)
.all(|&(ref other, other_para, _)| other != &who || other_para != para)
{
if let Some(amount) = ReservedAmounts::<T>::take(&(who.clone(), para)) {
let err_amt = CurrencyOf::<T>::unreserve(&who, amount);
debug_assert!(err_amt.is_zero());
Self::deposit_event(Event::<T>::Unreserved { bidder: who, amount });
}
}
}
Winning::<T>::insert(offset, ¤t_winning);
Self::deposit_event(Event::<T>::BidAccepted {
bidder,
para_id: para,
amount,
first_slot,
last_slot,
});
}
Ok(())
}
fn check_auction_end(now: BlockNumberFor<T>) -> Option<(WinningData<T>, LeasePeriodOf<T>)> {
if let Some((lease_period_index, early_end)) = AuctionInfo::<T>::get() {
let ending_period = T::EndingPeriod::get();
let late_end = early_end.saturating_add(ending_period);
let is_ended = now >= late_end;
if is_ended {
let (raw_offset, known_since) = T::Randomness::random(&b"para_auction"[..]);
if late_end <= known_since {
let raw_offset_block_number = <BlockNumberFor<T>>::decode(
&mut raw_offset.as_ref(),
)
.expect("secure hashes should always be bigger than the block number; qed");
let offset = (raw_offset_block_number % ending_period) /
T::SampleLength::get().max(One::one());
let auction_counter = AuctionCounter::<T>::get();
Self::deposit_event(Event::<T>::WinningOffset {
auction_index: auction_counter,
block_number: offset,
});
let res = Winning::<T>::get(offset)
.unwrap_or([Self::EMPTY; SlotRange::SLOT_RANGE_COUNT]);
#[allow(deprecated)]
Winning::<T>::remove_all(None);
AuctionInfo::<T>::kill();
return Some((res, lease_period_index))
}
}
}
None
}
fn manage_auction_end(
auction_lease_period_index: LeasePeriodOf<T>,
winning_ranges: WinningData<T>,
) {
for ((bidder, _), amount) in ReservedAmounts::<T>::drain() {
CurrencyOf::<T>::unreserve(&bidder, amount);
}
let winners = Self::calculate_winners(winning_ranges);
for (leaser, para, amount, range) in winners.into_iter() {
let begin_offset = LeasePeriodOf::<T>::from(range.as_pair().0 as u32);
let period_begin = auction_lease_period_index + begin_offset;
let period_count = LeasePeriodOf::<T>::from(range.len() as u32);
match T::Leaser::lease_out(para, &leaser, amount, period_begin, period_count) {
Err(LeaseError::ReserveFailed) |
Err(LeaseError::AlreadyEnded) |
Err(LeaseError::NoLeasePeriod) => {
},
Err(LeaseError::AlreadyLeased) => {
if CurrencyOf::<T>::reserve(&leaser, amount).is_ok() {
Self::deposit_event(Event::<T>::ReserveConfiscated {
para_id: para,
leaser,
amount,
});
}
},
Ok(()) => {}, }
}
Self::deposit_event(Event::<T>::AuctionClosed {
auction_index: AuctionCounter::<T>::get(),
});
}
fn calculate_winners(mut winning: WinningData<T>) -> WinnersData<T> {
let winning_ranges = {
let mut best_winners_ending_at: [(Vec<SlotRange>, BalanceOf<T>);
SlotRange::LEASE_PERIODS_PER_SLOT] = Default::default();
let best_bid = |range: SlotRange| {
winning[range as u8 as usize]
.as_ref()
.map(|(_, _, amount)| *amount * (range.len() as u32).into())
};
for i in 0..SlotRange::LEASE_PERIODS_PER_SLOT {
let r = SlotRange::new_bounded(0, 0, i as u32).expect("`i < LPPS`; qed");
if let Some(bid) = best_bid(r) {
best_winners_ending_at[i] = (vec![r], bid);
}
for j in 0..i {
let r = SlotRange::new_bounded(0, j as u32 + 1, i as u32)
.expect("`i < LPPS`; `j < i`; `j + 1 < LPPS`; qed");
if let Some(mut bid) = best_bid(r) {
bid += best_winners_ending_at[j].1;
if bid > best_winners_ending_at[i].1 {
let mut new_winners = best_winners_ending_at[j].0.clone();
new_winners.push(r);
best_winners_ending_at[i] = (new_winners, bid);
}
} else {
if best_winners_ending_at[j].1 > best_winners_ending_at[i].1 {
best_winners_ending_at[i] = best_winners_ending_at[j].clone();
}
}
}
}
best_winners_ending_at[SlotRange::LEASE_PERIODS_PER_SLOT - 1].0.clone()
};
winning_ranges
.into_iter()
.filter_map(|range| {
winning[range as u8 as usize]
.take()
.map(|(bidder, para, amount)| (bidder, para, amount, range))
})
.collect::<Vec<_>>()
}
}
#[cfg(test)]
mod mock;
#[cfg(test)]
mod tests;
#[cfg(feature = "runtime-benchmarks")]
mod benchmarking;