use alloc::vec::Vec;
use codec::{Decode, Encode};
use frame_support::{
pallet_prelude::*,
traits::{Currency, EnsureOrigin, ExistenceRequirement, Get, VestingSchedule},
};
use frame_system::pallet_prelude::*;
pub use pallet::*;
use scale_info::TypeInfo;
use sp_core::sr25519;
use sp_runtime::{
traits::{CheckedAdd, Saturating, Verify, Zero},
AnySignature, DispatchError, DispatchResult, Permill, RuntimeDebug,
};
type BalanceOf<T> =
<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
#[derive(Encode, Decode, Clone, Copy, Eq, PartialEq, RuntimeDebug, TypeInfo)]
pub enum AccountValidity {
Invalid,
Initiated,
Pending,
ValidLow,
ValidHigh,
Completed,
}
impl Default for AccountValidity {
fn default() -> Self {
AccountValidity::Invalid
}
}
impl AccountValidity {
fn is_valid(&self) -> bool {
match self {
Self::Invalid => false,
Self::Initiated => false,
Self::Pending => false,
Self::ValidLow => true,
Self::ValidHigh => true,
Self::Completed => false,
}
}
}
#[derive(Encode, Decode, Default, Clone, Eq, PartialEq, RuntimeDebug, TypeInfo)]
pub struct AccountStatus<Balance> {
validity: AccountValidity,
free_balance: Balance,
locked_balance: Balance,
signature: Vec<u8>,
vat: Permill,
}
#[frame_support::pallet]
pub mod pallet {
use super::*;
#[pallet::pallet]
#[pallet::without_storage_info]
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 Currency: Currency<Self::AccountId>;
type VestingSchedule: VestingSchedule<
Self::AccountId,
Moment = BlockNumberFor<Self>,
Currency = Self::Currency,
>;
type ValidityOrigin: EnsureOrigin<Self::RuntimeOrigin>;
type ConfigurationOrigin: EnsureOrigin<Self::RuntimeOrigin>;
#[pallet::constant]
type MaxStatementLength: Get<u32>;
#[pallet::constant]
type UnlockedProportion: Get<Permill>;
#[pallet::constant]
type MaxUnlocked: Get<BalanceOf<Self>>;
}
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
AccountCreated { who: T::AccountId },
ValidityUpdated { who: T::AccountId, validity: AccountValidity },
BalanceUpdated { who: T::AccountId, free: BalanceOf<T>, locked: BalanceOf<T> },
PaymentComplete { who: T::AccountId, free: BalanceOf<T>, locked: BalanceOf<T> },
PaymentAccountSet { who: T::AccountId },
StatementUpdated,
UnlockBlockUpdated { block_number: BlockNumberFor<T> },
}
#[pallet::error]
pub enum Error<T> {
InvalidAccount,
ExistingAccount,
InvalidSignature,
AlreadyCompleted,
Overflow,
InvalidStatement,
InvalidUnlockBlock,
VestingScheduleExists,
}
#[pallet::storage]
pub(super) type Accounts<T: Config> =
StorageMap<_, Blake2_128Concat, T::AccountId, AccountStatus<BalanceOf<T>>, ValueQuery>;
#[pallet::storage]
pub(super) type PaymentAccount<T: Config> = StorageValue<_, T::AccountId, OptionQuery>;
#[pallet::storage]
pub(super) type Statement<T> = StorageValue<_, Vec<u8>, ValueQuery>;
#[pallet::storage]
pub(super) type UnlockBlock<T: Config> = StorageValue<_, BlockNumberFor<T>, ValueQuery>;
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {}
#[pallet::call]
impl<T: Config> Pallet<T> {
#[pallet::call_index(0)]
#[pallet::weight(Weight::from_parts(200_000_000, 0) + T::DbWeight::get().reads_writes(4, 1))]
pub fn create_account(
origin: OriginFor<T>,
who: T::AccountId,
signature: Vec<u8>,
) -> DispatchResult {
T::ValidityOrigin::ensure_origin(origin)?;
ensure!(!Accounts::<T>::contains_key(&who), Error::<T>::ExistingAccount);
ensure!(
T::VestingSchedule::vesting_balance(&who).is_none(),
Error::<T>::VestingScheduleExists
);
Self::verify_signature(&who, &signature)?;
let status = AccountStatus {
validity: AccountValidity::Initiated,
signature,
free_balance: Zero::zero(),
locked_balance: Zero::zero(),
vat: Permill::zero(),
};
Accounts::<T>::insert(&who, status);
Self::deposit_event(Event::<T>::AccountCreated { who });
Ok(())
}
#[pallet::call_index(1)]
#[pallet::weight(T::DbWeight::get().reads_writes(1, 1))]
pub fn update_validity_status(
origin: OriginFor<T>,
who: T::AccountId,
validity: AccountValidity,
) -> DispatchResult {
T::ValidityOrigin::ensure_origin(origin)?;
ensure!(Accounts::<T>::contains_key(&who), Error::<T>::InvalidAccount);
Accounts::<T>::try_mutate(
&who,
|status: &mut AccountStatus<BalanceOf<T>>| -> DispatchResult {
ensure!(
status.validity != AccountValidity::Completed,
Error::<T>::AlreadyCompleted
);
status.validity = validity;
Ok(())
},
)?;
Self::deposit_event(Event::<T>::ValidityUpdated { who, validity });
Ok(())
}
#[pallet::call_index(2)]
#[pallet::weight(T::DbWeight::get().reads_writes(2, 1))]
pub fn update_balance(
origin: OriginFor<T>,
who: T::AccountId,
free_balance: BalanceOf<T>,
locked_balance: BalanceOf<T>,
vat: Permill,
) -> DispatchResult {
T::ValidityOrigin::ensure_origin(origin)?;
Accounts::<T>::try_mutate(
&who,
|status: &mut AccountStatus<BalanceOf<T>>| -> DispatchResult {
ensure!(status.validity.is_valid(), Error::<T>::InvalidAccount);
free_balance.checked_add(&locked_balance).ok_or(Error::<T>::Overflow)?;
status.free_balance = free_balance;
status.locked_balance = locked_balance;
status.vat = vat;
Ok(())
},
)?;
Self::deposit_event(Event::<T>::BalanceUpdated {
who,
free: free_balance,
locked: locked_balance,
});
Ok(())
}
#[pallet::call_index(3)]
#[pallet::weight(T::DbWeight::get().reads_writes(4, 2))]
pub fn payout(origin: OriginFor<T>, who: T::AccountId) -> DispatchResult {
let payment_account = ensure_signed(origin)?;
let test_against = PaymentAccount::<T>::get().ok_or(DispatchError::BadOrigin)?;
ensure!(payment_account == test_against, DispatchError::BadOrigin);
ensure!(
T::VestingSchedule::vesting_balance(&who).is_none(),
Error::<T>::VestingScheduleExists
);
Accounts::<T>::try_mutate(
&who,
|status: &mut AccountStatus<BalanceOf<T>>| -> DispatchResult {
ensure!(status.validity.is_valid(), Error::<T>::InvalidAccount);
let total_balance = status
.free_balance
.checked_add(&status.locked_balance)
.ok_or(Error::<T>::Overflow)?;
T::Currency::transfer(
&payment_account,
&who,
total_balance,
ExistenceRequirement::AllowDeath,
)?;
if !status.locked_balance.is_zero() {
let unlock_block = UnlockBlock::<T>::get();
let unlocked = (T::UnlockedProportion::get() * status.locked_balance)
.min(T::MaxUnlocked::get());
let locked = status.locked_balance.saturating_sub(unlocked);
let _ = T::VestingSchedule::add_vesting_schedule(
&who,
locked,
locked,
unlock_block,
);
}
status.validity = AccountValidity::Completed;
Self::deposit_event(Event::<T>::PaymentComplete {
who: who.clone(),
free: status.free_balance,
locked: status.locked_balance,
});
Ok(())
},
)?;
Ok(())
}
#[pallet::call_index(4)]
#[pallet::weight(T::DbWeight::get().writes(1))]
pub fn set_payment_account(origin: OriginFor<T>, who: T::AccountId) -> DispatchResult {
T::ConfigurationOrigin::ensure_origin(origin)?;
PaymentAccount::<T>::put(who.clone());
Self::deposit_event(Event::<T>::PaymentAccountSet { who });
Ok(())
}
#[pallet::call_index(5)]
#[pallet::weight(T::DbWeight::get().writes(1))]
pub fn set_statement(origin: OriginFor<T>, statement: Vec<u8>) -> DispatchResult {
T::ConfigurationOrigin::ensure_origin(origin)?;
ensure!(
(statement.len() as u32) < T::MaxStatementLength::get(),
Error::<T>::InvalidStatement
);
Statement::<T>::set(statement);
Self::deposit_event(Event::<T>::StatementUpdated);
Ok(())
}
#[pallet::call_index(6)]
#[pallet::weight(T::DbWeight::get().writes(1))]
pub fn set_unlock_block(
origin: OriginFor<T>,
unlock_block: BlockNumberFor<T>,
) -> DispatchResult {
T::ConfigurationOrigin::ensure_origin(origin)?;
ensure!(
unlock_block > frame_system::Pallet::<T>::block_number(),
Error::<T>::InvalidUnlockBlock
);
UnlockBlock::<T>::set(unlock_block);
Self::deposit_event(Event::<T>::UnlockBlockUpdated { block_number: unlock_block });
Ok(())
}
}
}
impl<T: Config> Pallet<T> {
fn verify_signature(who: &T::AccountId, signature: &[u8]) -> Result<(), DispatchError> {
let signature: AnySignature = sr25519::Signature::try_from(signature)
.map_err(|_| Error::<T>::InvalidSignature)?
.into();
let account_bytes: [u8; 32] = account_to_bytes(who)?;
let public_key = sr25519::Public::from_raw(account_bytes);
let message = Statement::<T>::get();
match signature.verify(message.as_slice(), &public_key) {
true => Ok(()),
false => Err(Error::<T>::InvalidSignature)?,
}
}
}
fn account_to_bytes<AccountId>(account: &AccountId) -> Result<[u8; 32], DispatchError>
where
AccountId: Encode,
{
let account_vec = account.encode();
ensure!(account_vec.len() == 32, "AccountId must be 32 bytes.");
let mut bytes = [0u8; 32];
bytes.copy_from_slice(&account_vec);
Ok(bytes)
}
pub fn remove_pallet<T>() -> frame_support::weights::Weight
where
T: frame_system::Config,
{
#[allow(deprecated)]
use frame_support::migration::remove_storage_prefix;
#[allow(deprecated)]
remove_storage_prefix(b"Purchase", b"Accounts", b"");
#[allow(deprecated)]
remove_storage_prefix(b"Purchase", b"PaymentAccount", b"");
#[allow(deprecated)]
remove_storage_prefix(b"Purchase", b"Statement", b"");
#[allow(deprecated)]
remove_storage_prefix(b"Purchase", b"UnlockBlock", b"");
<T as frame_system::Config>::BlockWeights::get().max_block
}
#[cfg(test)]
mod mock;
#[cfg(test)]
mod tests;