Skip to content
This repository has been archived by the owner on Nov 15, 2023. It is now read-only.

pallet-lottery: add generate_storage_info #10594

Merged
merged 14 commits into from
Jan 11, 2022
Merged
33 changes: 23 additions & 10 deletions frame/lottery/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
//! users to make those calls on your network. An example of how this could be
//! used is to set validator nominations as a valid lottery call. If the lottery
//! is set to repeat every month, then users would be encouraged to re-nominate
//! validators every month. A user can ony purchase one ticket per valid call
//! validators every month. A user can only purchase one ticket per valid call
//! per lottery.
//!
//! This pallet can be configured to use dynamically set calls or statically set
Expand Down Expand Up @@ -58,6 +58,8 @@ use codec::{Decode, Encode};
use frame_support::{
dispatch::{DispatchResult, Dispatchable, GetDispatchInfo},
ensure,
pallet_prelude::MaxEncodedLen,
storage::bounded_vec::BoundedVec,
traits::{Currency, ExistenceRequirement::KeepAlive, Get, Randomness, ReservableCurrency},
PalletId, RuntimeDebug,
};
Expand All @@ -76,7 +78,9 @@ type BalanceOf<T> =
// We use this to uniquely match someone's incoming call with the calls configured for the lottery.
type CallIndex = (u8, u8);

#[derive(Encode, Decode, Default, Eq, PartialEq, RuntimeDebug, scale_info::TypeInfo)]
#[derive(
Encode, Decode, Default, Eq, PartialEq, RuntimeDebug, scale_info::TypeInfo, MaxEncodedLen,
)]
pub struct LotteryConfig<BlockNumber, Balance> {
/// Price per entry.
price: Balance,
Expand Down Expand Up @@ -120,6 +124,7 @@ pub mod pallet {

#[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
#[pallet::generate_storage_info]
pub struct Pallet<T>(_);

/// The pallet's config trait.
Expand Down Expand Up @@ -209,8 +214,13 @@ pub mod pallet {

/// Users who have purchased a ticket. (Lottery Index, Tickets Purchased)
#[pallet::storage]
pub(crate) type Participants<T: Config> =
StorageMap<_, Twox64Concat, T::AccountId, (u32, Vec<CallIndex>), ValueQuery>;
pub(crate) type Participants<T: Config> = StorageMap<
_,
Twox64Concat,
T::AccountId,
(u32, BoundedVec<CallIndex, T::MaxCalls>),
ValueQuery,
>;

/// Total number of tickets sold.
#[pallet::storage]
Expand All @@ -226,7 +236,8 @@ pub mod pallet {
/// The calls stored in this pallet to be used in an active lottery if configured
/// by `Config::ValidateCall`.
#[pallet::storage]
pub(crate) type CallIndices<T> = StorageValue<_, Vec<CallIndex>, ValueQuery>;
pub(crate) type CallIndices<T: Config> =
StorageValue<_, BoundedVec<CallIndex, T::MaxCalls>, ValueQuery>;

#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
Expand Down Expand Up @@ -395,11 +406,13 @@ impl<T: Config> Pallet<T> {
}

// Converts a vector of calls into a vector of call indices.
fn calls_to_indices(calls: &[<T as Config>::Call]) -> Result<Vec<CallIndex>, DispatchError> {
let mut indices = Vec::with_capacity(calls.len());
fn calls_to_indices(
calls: &[<T as Config>::Call],
) -> Result<BoundedVec<CallIndex, T::MaxCalls>, DispatchError> {
let mut indices = BoundedVec::<CallIndex, T::MaxCalls>::default();
ggwpez marked this conversation as resolved.
Show resolved Hide resolved
for c in calls.iter() {
let index = Self::call_to_index(c)?;
indices.push(index)
indices.try_push(index).map_err(|_| Error::<T>::TooManyCalls)?;
}
Ok(indices)
}
Expand Down Expand Up @@ -433,7 +446,7 @@ impl<T: Config> Pallet<T> {
let index = LotteryIndex::<T>::get();
// If lottery index doesn't match, then reset participating calls and index.
if *lottery_index != index {
*participating_calls = Vec::new();
*participating_calls = Default::default();
*lottery_index = index;
} else {
// Check that user is not already participating under this call.
Expand All @@ -442,12 +455,12 @@ impl<T: Config> Pallet<T> {
Error::<T>::AlreadyParticipating
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using a BoundedSet here would make matters easier, but I'm not sure if it is worth the refactor rn.

);
}
participating_calls.try_push(call_index).map_err(|_| Error::<T>::TooManyCalls)?;
ggwpez marked this conversation as resolved.
Show resolved Hide resolved
// Check user has enough funds and send it to the Lottery account.
T::Currency::transfer(caller, &Self::account_id(), config.price, KeepAlive)?;
shawntabrizi marked this conversation as resolved.
Show resolved Hide resolved
// Create a new ticket.
TicketsCount::<T>::put(new_ticket_count);
Tickets::<T>::insert(ticket_count, caller.clone());
participating_calls.push(call_index);
shawntabrizi marked this conversation as resolved.
Show resolved Hide resolved
Ok(())
},
)?;
Expand Down
70 changes: 69 additions & 1 deletion frame/lottery/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ fn initial_state() {
new_test_ext().execute_with(|| {
assert_eq!(Balances::free_balance(Lottery::account_id()), 0);
assert!(crate::Lottery::<Test>::get().is_none());
assert_eq!(Participants::<Test>::get(&1), (0, vec![]));
shawntabrizi marked this conversation as resolved.
Show resolved Hide resolved
assert_eq!(Participants::<Test>::get(&1), (0, Default::default()));
assert_eq!(TicketsCount::<Test>::get(), 0);
assert!(Tickets::<Test>::get(0).is_none());
});
Expand Down Expand Up @@ -90,6 +90,37 @@ fn basic_end_to_end_works() {
});
}

/// Only the manager can stop the Lottery from repeating via `stop_repeat`.
#[test]
fn stop_repeat_works() {
new_test_ext().execute_with(|| {
let price = 10;
let length = 20;
let delay = 5;

// Set no calls for the lottery.
assert_ok!(Lottery::set_calls(Origin::root(), vec![]));
// Start lottery, it repeats.
assert_ok!(Lottery::start_lottery(Origin::root(), price, length, delay, true));

// Non-manager fails to `stop_repeat`.
assert_noop!(Lottery::stop_repeat(Origin::signed(1)), DispatchError::BadOrigin);
// Manager can `stop_repeat`, even twice.
assert_ok!(Lottery::stop_repeat(Origin::root()));
assert_ok!(Lottery::stop_repeat(Origin::root()));

// Lottery still exists.
assert!(crate::Lottery::<Test>::get().is_some());
// End and pick a winner.
run_to_block(length + delay);
shawntabrizi marked this conversation as resolved.
Show resolved Hide resolved

// Lottery stays dead and does not repeat.
assert!(crate::Lottery::<Test>::get().is_none());
run_to_block(length + delay + 1);
assert!(crate::Lottery::<Test>::get().is_none());
});
}

#[test]
fn set_calls_works() {
new_test_ext().execute_with(|| {
Expand Down Expand Up @@ -120,6 +151,27 @@ fn set_calls_works() {
});
}

#[test]
fn call_to_indices_works() {
new_test_ext().execute_with(|| {
let calls = vec![
Call::Balances(BalancesCall::force_transfer { source: 0, dest: 0, value: 0 }),
Call::Balances(BalancesCall::transfer { dest: 0, value: 0 }),
];
let indices = Lottery::calls_to_indices(&calls).unwrap().into_inner();
// Only comparing the length since it is otherwise dependant on the API
// of `BalancesCall`.
assert_eq!(indices.len(), calls.len());

let too_many_calls = vec![
Call::Balances(BalancesCall::force_transfer { source: 0, dest: 0, value: 0 }),
Call::Balances(BalancesCall::transfer { dest: 0, value: 0 }),
Call::System(SystemCall::remark { remark: vec![] }),
];
assert_noop!(Lottery::calls_to_indices(&too_many_calls), Error::<Test>::TooManyCalls);
});
}

#[test]
fn start_lottery_works() {
new_test_ext().execute_with(|| {
Expand Down Expand Up @@ -239,6 +291,22 @@ fn buy_ticket_works() {
});
}

/// Test that `do_buy_ticket` returns an `AlreadyParticipating` error.
/// Errors of `do_buy_ticket` are ignored by `buy_ticket`, therefore this white-box test.
#[test]
fn do_buy_ticket_already_participating() {
new_test_ext().execute_with(|| {
let calls = vec![Call::Balances(BalancesCall::transfer { dest: 0, value: 0 })];
assert_ok!(Lottery::set_calls(Origin::root(), calls.clone()));
assert_ok!(Lottery::start_lottery(Origin::root(), 1, 10, 10, false));

// Buying once works.
assert_ok!(Lottery::do_buy_ticket(&1, &calls[0]));
// Buying the same ticket again fails.
assert_noop!(Lottery::do_buy_ticket(&1, &calls[0]), Error::<Test>::AlreadyParticipating);
});
}

#[test]
fn start_lottery_will_create_account() {
new_test_ext().execute_with(|| {
Expand Down