mirror of
https://github.com/serai-dex/serai.git
synced 2025-12-08 12:19:24 +00:00
Restore the coins pallet to the runtime
This commit is contained in:
@@ -22,30 +22,26 @@ workspace = true
|
||||
scale = { package = "parity-scale-codec", version = "3", default-features = false, features = ["derive"] }
|
||||
scale-info = { version = "2", default-features = false, features = ["derive"] }
|
||||
|
||||
frame-system = { git = "https://github.com/serai-dex/polkadot-sdk", branch = "serai-next", default-features = false }
|
||||
frame-support = { git = "https://github.com/serai-dex/polkadot-sdk", branch = "serai-next", default-features = false }
|
||||
|
||||
sp-core = { git = "https://github.com/serai-dex/polkadot-sdk", branch = "serai-next", default-features = false }
|
||||
sp-std = { git = "https://github.com/serai-dex/polkadot-sdk", branch = "serai-next", default-features = false }
|
||||
sp-runtime = { git = "https://github.com/serai-dex/polkadot-sdk", branch = "serai-next", default-features = false }
|
||||
|
||||
pallet-transaction-payment = { git = "https://github.com/serai-dex/polkadot-sdk", branch = "serai-next", default-features = false }
|
||||
frame-system = { git = "https://github.com/serai-dex/polkadot-sdk", branch = "serai-next", default-features = false }
|
||||
frame-support = { git = "https://github.com/serai-dex/polkadot-sdk", branch = "serai-next", default-features = false }
|
||||
|
||||
serai-primitives = { path = "../primitives", default-features = false }
|
||||
serai-primitives = { path = "../primitives", default-features = false, features = ["serde", "non_canonical_scale_derivations"] }
|
||||
|
||||
[dev-dependencies]
|
||||
sp-io = { git = "https://github.com/serai-dex/polkadot-sdk", branch = "serai-next", default-features = false, features = ["std"] }
|
||||
|
||||
[features]
|
||||
std = [
|
||||
"frame-system/std",
|
||||
"frame-support/std",
|
||||
|
||||
"sp-core/std",
|
||||
"sp-std/std",
|
||||
"sp-runtime/std",
|
||||
|
||||
"pallet-transaction-payment/std",
|
||||
"frame-system/std",
|
||||
"frame-support/std",
|
||||
|
||||
"serai-primitives/std",
|
||||
]
|
||||
@@ -53,8 +49,6 @@ std = [
|
||||
try-runtime = [
|
||||
"frame-system/try-runtime",
|
||||
"frame-support/try-runtime",
|
||||
|
||||
"sp-runtime/try-runtime",
|
||||
]
|
||||
|
||||
runtime-benchmarks = [
|
||||
|
||||
3
substrate/coins/README.md
Normal file
3
substrate/coins/README.md
Normal file
@@ -0,0 +1,3 @@
|
||||
# Coins Pallet
|
||||
|
||||
Pallet implementing the necessary coins logic for the Serai protocol.
|
||||
@@ -1,109 +1,150 @@
|
||||
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
|
||||
#![doc = include_str!("../README.md")]
|
||||
#![deny(missing_docs)]
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
|
||||
extern crate alloc;
|
||||
|
||||
#[cfg(test)]
|
||||
mod mock;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use serai_primitives::{Balance, Coin, ExternalBalance, SubstrateAmount};
|
||||
use serai_primitives::balance::ExternalBalance;
|
||||
|
||||
/// The decider for if a mint is allowed or not.
|
||||
pub trait AllowMint {
|
||||
/// Whether or not the mint of the specified coins is allowed.
|
||||
fn is_allowed(balance: &ExternalBalance) -> bool;
|
||||
}
|
||||
|
||||
impl AllowMint for () {
|
||||
/// An `AllowMint` implementor which always returns true.
|
||||
pub struct AlwaysAllowMint;
|
||||
impl AllowMint for AlwaysAllowMint {
|
||||
fn is_allowed(_: &ExternalBalance) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Investigate why Substrate generates this
|
||||
#[allow(unreachable_patterns, clippy::cast_possible_truncation)]
|
||||
#[allow(clippy::cast_possible_truncation)]
|
||||
#[frame_support::pallet]
|
||||
pub mod pallet {
|
||||
use super::*;
|
||||
use sp_std::{vec::Vec, any::TypeId};
|
||||
mod pallet {
|
||||
use core::any::TypeId;
|
||||
use alloc::vec::Vec;
|
||||
|
||||
use sp_core::sr25519::Public;
|
||||
use sp_runtime::{
|
||||
traits::{DispatchInfoOf, PostDispatchInfoOf},
|
||||
transaction_validity::{TransactionValidityError, InvalidTransaction},
|
||||
};
|
||||
|
||||
use frame_system::pallet_prelude::*;
|
||||
use frame_support::pallet_prelude::*;
|
||||
|
||||
use pallet_transaction_payment::{Config as TpConfig, OnChargeTransaction};
|
||||
use serai_primitives::{coin::*, balance::*, instructions::OutInstructionWithBalance};
|
||||
|
||||
use serai_primitives::*;
|
||||
pub use coins_primitives as primitives;
|
||||
use primitives::*;
|
||||
use super::*;
|
||||
|
||||
type LiquidityTokensInstance = crate::Instance1;
|
||||
/// The instance used to represent coins on the Serai network.
|
||||
///
|
||||
/// This would either be SRI itself or the sriXYZ coins swappable via pools.
|
||||
pub struct CoinsInstance;
|
||||
/// The instance used to represent liquidity tokens on the Serai network.
|
||||
///
|
||||
/// Coin::XYZ would be considered as the liquidity token for the Coin::SRI - Coin::XYZ pool.
|
||||
pub struct LiquidityTokensInstance;
|
||||
|
||||
/// The configuration of this pallet.
|
||||
#[pallet::config]
|
||||
pub trait Config<I: 'static = ()>: frame_system::Config<AccountId = Public> {
|
||||
/// The event type.
|
||||
type RuntimeEvent: From<Event<Self, I>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
|
||||
/// What decides if mints are allowed.
|
||||
type AllowMint: AllowMint;
|
||||
}
|
||||
|
||||
/// The genesis state to use for this pallet.
|
||||
#[pallet::genesis_config]
|
||||
#[derive(Clone, PartialEq, Eq, Debug, Encode, Decode)]
|
||||
pub struct GenesisConfig<T: Config<I>, I: 'static = ()> {
|
||||
/// The balances to initiate the state with.
|
||||
///
|
||||
/// This is useful for test networks where it's desirable to have some coins available
|
||||
/// immediately.
|
||||
pub accounts: Vec<(T::AccountId, Balance)>,
|
||||
pub _ignore: PhantomData<I>,
|
||||
/// PhantomData to bind `I`.
|
||||
pub _instance: PhantomData<I>,
|
||||
}
|
||||
|
||||
impl<T: Config<I>, I: 'static> Default for GenesisConfig<T, I> {
|
||||
fn default() -> Self {
|
||||
GenesisConfig { accounts: Default::default(), _ignore: Default::default() }
|
||||
GenesisConfig { accounts: Default::default(), _instance: Default::default() }
|
||||
}
|
||||
}
|
||||
|
||||
/// An error incurred.
|
||||
#[pallet::error]
|
||||
pub enum Error<T, I = ()> {
|
||||
AmountOverflowed,
|
||||
NotEnoughCoins,
|
||||
BurnWithInstructionNotAllowed,
|
||||
/// The mint wasn't allowed.
|
||||
MintNotAllowed,
|
||||
/// The amount an account had overflowed.
|
||||
AmountOverflowed,
|
||||
/// The account didn't have enough coins for this operation.
|
||||
NotEnoughCoins,
|
||||
/// An Instruction was specified with a Burn when that's unsupported.
|
||||
BurnWithInstructionNotAllowed,
|
||||
}
|
||||
|
||||
/// An event emitted.
|
||||
#[pallet::event]
|
||||
#[pallet::generate_deposit(fn deposit_event)]
|
||||
pub enum Event<T: Config<I>, I: 'static = ()> {
|
||||
Mint { to: Public, balance: Balance },
|
||||
Burn { from: Public, balance: Balance },
|
||||
BurnWithInstruction { from: Public, instruction: OutInstructionWithBalance },
|
||||
Transfer { from: Public, to: Public, balance: Balance },
|
||||
/// Coins were minted.
|
||||
Mint {
|
||||
/// The account minted to.
|
||||
to: Public,
|
||||
/// The balance minted.
|
||||
balance: Balance,
|
||||
},
|
||||
/// Coins were transferred.
|
||||
Transfer {
|
||||
/// The account transferred from.
|
||||
from: Public,
|
||||
/// The account transferred to.
|
||||
to: Public,
|
||||
/// The balance transferred.
|
||||
balance: Balance,
|
||||
},
|
||||
/// Coins were burnt.
|
||||
Burn {
|
||||
/// The account burnt from.
|
||||
from: Public,
|
||||
/// The balance burnt.
|
||||
balance: Balance,
|
||||
},
|
||||
/// Coins were burnt with an instruction.
|
||||
BurnWithInstruction {
|
||||
/// The account burnt from.
|
||||
from: Public,
|
||||
/// The instruction, and associated balance.
|
||||
instruction: OutInstructionWithBalance,
|
||||
},
|
||||
}
|
||||
|
||||
/// The Pallet struct.
|
||||
#[pallet::pallet]
|
||||
pub struct Pallet<T, I = ()>(_);
|
||||
|
||||
/// The amount of coins each account has.
|
||||
// Identity is used as the second key's hasher due to it being a non-manipulatable fixed-space
|
||||
// ID.
|
||||
// Identity is used as the second key's hasher due to Coin being a small, fixed-space ID.
|
||||
#[pallet::storage]
|
||||
#[pallet::getter(fn balances)]
|
||||
pub type Balances<T: Config<I>, I: 'static = ()> =
|
||||
StorageDoubleMap<_, Blake2_128Concat, Public, Identity, Coin, SubstrateAmount, ValueQuery>;
|
||||
type Balances<T: Config<I>, I: 'static = ()> =
|
||||
StorageDoubleMap<_, Blake2_128Concat, Public, Identity, Coin, Amount, ValueQuery>;
|
||||
|
||||
/// The total supply of each coin.
|
||||
// We use Identity type here again due to reasons stated in the Balances Storage.
|
||||
#[pallet::storage]
|
||||
#[pallet::getter(fn supply)]
|
||||
pub type Supply<T: Config<I>, I: 'static = ()> =
|
||||
StorageMap<_, Identity, Coin, SubstrateAmount, ValueQuery>;
|
||||
type Supply<T: Config<I>, I: 'static = ()> = StorageMap<_, Identity, Coin, Amount, ValueQuery>;
|
||||
|
||||
#[pallet::genesis_build]
|
||||
impl<T: Config<I>, I: 'static> BuildGenesisConfig for GenesisConfig<T, I> {
|
||||
fn build(&self) {
|
||||
// initialize the supply of the coins
|
||||
// TODO: Don't use COINS yet GenesisConfig so we can safely expand COINS
|
||||
for c in &COINS {
|
||||
Supply::<T, I>::set(c, 0);
|
||||
}
|
||||
|
||||
// initialize the genesis accounts
|
||||
for (account, balance) in &self.accounts {
|
||||
Pallet::<T, I>::mint(*account, *balance).unwrap();
|
||||
@@ -111,36 +152,29 @@ pub mod pallet {
|
||||
}
|
||||
}
|
||||
|
||||
#[pallet::hooks]
|
||||
impl<T: Config<I>, I: 'static> Hooks<BlockNumberFor<T>> for Pallet<T, I> {
|
||||
fn on_initialize(_: BlockNumberFor<T>) -> Weight {
|
||||
// burn the fees collected previous block
|
||||
let coin = Coin::Serai;
|
||||
let amount = Self::balance(FEE_ACCOUNT.into(), coin);
|
||||
// we can unwrap, we are not burning more then what we have
|
||||
// If this errors, it'll halt the runtime however (due to being called at the start of every
|
||||
// block), requiring extra care when reviewing
|
||||
Self::burn_internal(FEE_ACCOUNT.into(), Balance { coin, amount }).unwrap();
|
||||
Weight::zero() // TODO
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Config<I>, I: 'static> Pallet<T, I> {
|
||||
/// Returns the balance of a given account for `coin`.
|
||||
pub fn balance(of: Public, coin: Coin) -> Amount {
|
||||
Amount(Self::balances(of, coin))
|
||||
/// Returns the balance of `coin` for the specified account.
|
||||
pub fn balance(
|
||||
of: impl scale::EncodeLike<Public>,
|
||||
coin: impl scale::EncodeLike<Coin>,
|
||||
) -> Amount {
|
||||
Balances::<T, I>::get(of, coin)
|
||||
}
|
||||
|
||||
/// Returns the supply of `coin`.
|
||||
pub fn supply(coin: impl scale::EncodeLike<Coin>) -> Amount {
|
||||
Supply::<T, I>::get(coin)
|
||||
}
|
||||
|
||||
fn decrease_balance_internal(from: Public, balance: Balance) -> Result<(), Error<T, I>> {
|
||||
let coin = &balance.coin;
|
||||
|
||||
// sub amount from account
|
||||
let new_amount = Self::balances(from, coin)
|
||||
.checked_sub(balance.amount.0)
|
||||
.ok_or(Error::<T, I>::NotEnoughCoins)?;
|
||||
let new_amount =
|
||||
(Self::balance(from, coin) - balance.amount).ok_or(Error::<T, I>::NotEnoughCoins)?;
|
||||
|
||||
// save
|
||||
if new_amount == 0 {
|
||||
if new_amount == Amount(0) {
|
||||
Balances::<T, I>::remove(from, coin);
|
||||
} else {
|
||||
Balances::<T, I>::set(from, coin, new_amount);
|
||||
@@ -152,9 +186,8 @@ pub mod pallet {
|
||||
let coin = &balance.coin;
|
||||
|
||||
// add amount to account
|
||||
let new_amount = Self::balances(to, coin)
|
||||
.checked_add(balance.amount.0)
|
||||
.ok_or(Error::<T, I>::AmountOverflowed)?;
|
||||
let new_amount =
|
||||
(Self::balance(to, coin) + balance.amount).ok_or(Error::<T, I>::AmountOverflowed)?;
|
||||
|
||||
// save
|
||||
Balances::<T, I>::set(to, coin, new_amount);
|
||||
@@ -165,21 +198,22 @@ pub mod pallet {
|
||||
///
|
||||
/// Errors if any amount overflows.
|
||||
pub fn mint(to: Public, balance: Balance) -> Result<(), Error<T, I>> {
|
||||
// If the coin isn't Serai, which we're always allowed to mint, and the mint isn't explicitly
|
||||
// allowed, error
|
||||
if !ExternalCoin::try_from(balance.coin)
|
||||
.map(|coin| T::AllowMint::is_allowed(&ExternalBalance { coin, amount: balance.amount }))
|
||||
.unwrap_or(true)
|
||||
{
|
||||
Err(Error::<T, I>::MintNotAllowed)?;
|
||||
// If this is an external coin, check if we can mint it
|
||||
let external_balance = ExternalBalance::try_from(balance);
|
||||
let can_mint_external = external_balance.as_ref().map(T::AllowMint::is_allowed);
|
||||
// If it was native to the Serai network, we can always mint it
|
||||
let can_mint = can_mint_external.unwrap_or(true);
|
||||
if !can_mint {
|
||||
Err(Error::<T, I>::MintNotAllowed)?;
|
||||
}
|
||||
}
|
||||
|
||||
// update the balance
|
||||
Self::increase_balance_internal(to, balance)?;
|
||||
|
||||
// update the supply
|
||||
let new_supply = Self::supply(balance.coin)
|
||||
.checked_add(balance.amount.0)
|
||||
let new_supply = (Supply::<T, I>::get(balance.coin) + balance.amount)
|
||||
.ok_or(Error::<T, I>::AmountOverflowed)?;
|
||||
Supply::<T, I>::set(balance.coin, new_supply);
|
||||
|
||||
@@ -189,27 +223,25 @@ pub mod pallet {
|
||||
|
||||
/// Burn `balance` from the specified account.
|
||||
fn burn_internal(from: Public, balance: Balance) -> Result<(), Error<T, I>> {
|
||||
// don't waste time if amount == 0
|
||||
if balance.amount.0 == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// update the balance
|
||||
Self::decrease_balance_internal(from, balance)?;
|
||||
|
||||
// update the supply
|
||||
let new_supply = Self::supply(balance.coin).checked_sub(balance.amount.0).unwrap();
|
||||
Supply::<T, I>::set(balance.coin, new_supply);
|
||||
Supply::<T, I>::mutate(balance.coin, |supply| {
|
||||
// We can unwrap here as we're burning an amount legitimately in the system (per successful
|
||||
// decrease), so the supply must be greater than this value
|
||||
let new_supply = (*supply - balance.amount).unwrap();
|
||||
*supply = new_supply;
|
||||
});
|
||||
|
||||
// We don't emit the event here, but rather at the call-site, due to being unsure if we
|
||||
// should emit `Burn` or `BurnWithInstruction`
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Transfer `balance` from `from` to `to`.
|
||||
pub fn transfer_internal(
|
||||
from: Public,
|
||||
to: Public,
|
||||
balance: Balance,
|
||||
) -> Result<(), Error<T, I>> {
|
||||
fn transfer_internal(from: Public, to: Public, balance: Balance) -> Result<(), Error<T, I>> {
|
||||
// update balances of accounts
|
||||
Self::decrease_balance_internal(from, balance)?;
|
||||
Self::increase_balance_internal(to, balance)?;
|
||||
@@ -220,6 +252,7 @@ pub mod pallet {
|
||||
|
||||
#[pallet::call]
|
||||
impl<T: Config<I>, I: 'static> Pallet<T, I> {
|
||||
/// Transfer `balance` from the signer to `to`.
|
||||
#[pallet::call_index(0)]
|
||||
#[pallet::weight((0, DispatchClass::Normal))] // TODO
|
||||
pub fn transfer(origin: OriginFor<T>, to: Public, balance: Balance) -> DispatchResult {
|
||||
@@ -228,7 +261,7 @@ pub mod pallet {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Burn `balance` from the caller.
|
||||
/// Burn `balance` from the signer.
|
||||
#[pallet::call_index(1)]
|
||||
#[pallet::weight((0, DispatchClass::Normal))] // TODO
|
||||
pub fn burn(origin: OriginFor<T>, balance: Balance) -> DispatchResult {
|
||||
@@ -238,14 +271,15 @@ pub mod pallet {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Burn `balance` with `OutInstructionWithBalance` from the caller.
|
||||
/// Burn `balance` from the signer with `instruction`.
|
||||
#[pallet::call_index(2)]
|
||||
#[pallet::weight((0, DispatchClass::Normal))] // TODO
|
||||
pub fn burn_with_instruction(
|
||||
origin: OriginFor<T>,
|
||||
instruction: OutInstructionWithBalance,
|
||||
) -> DispatchResult {
|
||||
if TypeId::of::<I>() == TypeId::of::<LiquidityTokensInstance>() {
|
||||
// Only allow specifying an instruction if this is Coins, not LiquidityTokens
|
||||
if TypeId::of::<I>() != TypeId::of::<CoinsInstance>() {
|
||||
Err(Error::<T, I>::BurnWithInstructionNotAllowed)?;
|
||||
}
|
||||
|
||||
@@ -255,49 +289,6 @@ pub mod pallet {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Config> OnChargeTransaction<T> for Pallet<T>
|
||||
where
|
||||
T: TpConfig,
|
||||
{
|
||||
type Balance = SubstrateAmount;
|
||||
type LiquidityInfo = Option<SubstrateAmount>;
|
||||
|
||||
fn withdraw_fee(
|
||||
who: &Public,
|
||||
_call: &T::RuntimeCall,
|
||||
_dispatch_info: &DispatchInfoOf<T::RuntimeCall>,
|
||||
fee: Self::Balance,
|
||||
_tip: Self::Balance,
|
||||
) -> Result<Self::LiquidityInfo, TransactionValidityError> {
|
||||
if fee == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let balance = Balance { coin: Coin::Serai, amount: Amount(fee) };
|
||||
match Self::transfer_internal(*who, FEE_ACCOUNT.into(), balance) {
|
||||
Err(_) => Err(InvalidTransaction::Payment)?,
|
||||
Ok(()) => Ok(Some(fee)),
|
||||
}
|
||||
}
|
||||
|
||||
fn correct_and_deposit_fee(
|
||||
who: &Public,
|
||||
_dispatch_info: &DispatchInfoOf<T::RuntimeCall>,
|
||||
_post_info: &PostDispatchInfoOf<T::RuntimeCall>,
|
||||
corrected_fee: Self::Balance,
|
||||
_tip: Self::Balance,
|
||||
already_withdrawn: Self::LiquidityInfo,
|
||||
) -> Result<(), TransactionValidityError> {
|
||||
if let Some(paid) = already_withdrawn {
|
||||
let refund_amount = paid.saturating_sub(corrected_fee);
|
||||
let balance = Balance { coin: Coin::Serai, amount: Amount(refund_amount) };
|
||||
Self::transfer_internal(FEE_ACCOUNT.into(), *who, balance)
|
||||
.map_err(|_| TransactionValidityError::Invalid(InvalidTransaction::Payment))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub use pallet::*;
|
||||
|
||||
@@ -1,70 +1,37 @@
|
||||
//! Test environment for Coins pallet.
|
||||
|
||||
use super::*;
|
||||
use sp_runtime::BuildStorage;
|
||||
|
||||
use frame_support::{
|
||||
construct_runtime,
|
||||
traits::{ConstU32, ConstU64},
|
||||
};
|
||||
use frame_support::{derive_impl, construct_runtime};
|
||||
|
||||
use sp_core::{H256, sr25519::Public};
|
||||
use sp_runtime::{
|
||||
traits::{BlakeTwo256, IdentityLookup},
|
||||
BuildStorage,
|
||||
};
|
||||
|
||||
use crate as coins;
|
||||
|
||||
type Block = frame_system::mocking::MockBlock<Test>;
|
||||
use crate::{self as coins, CoinsInstance};
|
||||
|
||||
construct_runtime!(
|
||||
pub enum Test
|
||||
{
|
||||
System: frame_system,
|
||||
Coins: coins,
|
||||
Coins: coins::<CoinsInstance>,
|
||||
}
|
||||
);
|
||||
|
||||
#[derive_impl(frame_system::config_preludes::TestDefaultConfig)]
|
||||
impl frame_system::Config for Test {
|
||||
type BaseCallFilter = frame_support::traits::Everything;
|
||||
type BlockWeights = ();
|
||||
type BlockLength = ();
|
||||
type RuntimeOrigin = RuntimeOrigin;
|
||||
type RuntimeCall = RuntimeCall;
|
||||
type Nonce = u64;
|
||||
type Hash = H256;
|
||||
type Hashing = BlakeTwo256;
|
||||
type AccountId = Public;
|
||||
type Lookup = IdentityLookup<Self::AccountId>;
|
||||
type Block = Block;
|
||||
type RuntimeEvent = RuntimeEvent;
|
||||
type BlockHashCount = ConstU64<250>;
|
||||
type DbWeight = ();
|
||||
type Version = ();
|
||||
type PalletInfo = PalletInfo;
|
||||
type AccountData = ();
|
||||
type OnNewAccount = ();
|
||||
type OnKilledAccount = ();
|
||||
type SystemWeightInfo = ();
|
||||
type SS58Prefix = ();
|
||||
type OnSetCode = ();
|
||||
type MaxConsumers = ConstU32<16>;
|
||||
type AccountId = sp_core::sr25519::Public;
|
||||
type Lookup = sp_runtime::traits::IdentityLookup<Self::AccountId>;
|
||||
type Block = frame_system::mocking::MockBlock<Test>;
|
||||
}
|
||||
|
||||
impl Config for Test {
|
||||
impl crate::Config<CoinsInstance> for Test {
|
||||
type RuntimeEvent = RuntimeEvent;
|
||||
|
||||
type AllowMint = ();
|
||||
type AllowMint = crate::AlwaysAllowMint;
|
||||
}
|
||||
|
||||
pub(crate) fn new_test_ext() -> sp_io::TestExternalities {
|
||||
let mut t = frame_system::GenesisConfig::<Test>::default().build_storage().unwrap();
|
||||
let mut storage = frame_system::GenesisConfig::<Test>::default().build_storage().unwrap();
|
||||
|
||||
crate::GenesisConfig::<Test> { accounts: vec![], _ignore: Default::default() }
|
||||
.assimilate_storage(&mut t)
|
||||
crate::GenesisConfig::<Test, CoinsInstance> { accounts: vec![], _instance: Default::default() }
|
||||
.assimilate_storage(&mut storage)
|
||||
.unwrap();
|
||||
|
||||
let mut ext = sp_io::TestExternalities::new(t);
|
||||
ext.execute_with(|| System::set_block_number(0));
|
||||
ext
|
||||
storage.into()
|
||||
}
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
use crate::{mock::*, primitives::*};
|
||||
|
||||
use sp_core::{Pair as _, sr25519::Pair};
|
||||
use frame_system::RawOrigin;
|
||||
use sp_core::Pair;
|
||||
|
||||
use serai_primitives::*;
|
||||
use serai_primitives::{coin::*, balance::*, address::*, instructions::*};
|
||||
|
||||
pub type CoinsEvent = crate::Event<Test, ()>;
|
||||
use crate::mock::*;
|
||||
|
||||
pub type CoinsEvent = crate::Event<Test, crate::CoinsInstance>;
|
||||
|
||||
#[test]
|
||||
fn mint() {
|
||||
new_test_ext().execute_with(|| {
|
||||
// minting u64::MAX should work
|
||||
let coin = Coin::Serai;
|
||||
let to = insecure_pair_from_name("random1").public();
|
||||
let to = Pair::generate().0.public();
|
||||
let balance = Balance { coin, amount: Amount(u64::MAX) };
|
||||
|
||||
Coins::mint(to, balance).unwrap();
|
||||
@@ -22,7 +22,7 @@ fn mint() {
|
||||
assert!(Coins::mint(to, Balance { coin, amount: Amount(1) }).is_err());
|
||||
|
||||
// supply now should be equal to sum of the accounts balance sum
|
||||
assert_eq!(Coins::supply(coin), balance.amount.0);
|
||||
assert_eq!(Coins::supply(coin), balance.amount);
|
||||
|
||||
// test events
|
||||
let mint_events = System::events()
|
||||
@@ -49,19 +49,19 @@ fn burn_with_instruction() {
|
||||
new_test_ext().execute_with(|| {
|
||||
// mint some coin
|
||||
let coin = Coin::External(ExternalCoin::Bitcoin);
|
||||
let to = insecure_pair_from_name("random1").public();
|
||||
let to = Pair::generate().0.public();
|
||||
let balance = Balance { coin, amount: Amount(10 * 10u64.pow(coin.decimals())) };
|
||||
|
||||
Coins::mint(to, balance).unwrap();
|
||||
assert_eq!(Coins::balance(to, coin), balance.amount);
|
||||
assert_eq!(Coins::supply(coin), balance.amount.0);
|
||||
assert_eq!(Coins::supply(coin), balance.amount);
|
||||
|
||||
// we shouldn't be able to burn more than what we have
|
||||
let mut instruction = OutInstructionWithBalance {
|
||||
instruction: OutInstruction { address: ExternalAddress::new(vec![]).unwrap() },
|
||||
instruction: OutInstruction::Transfer(ExternalAddress::try_from(vec![]).unwrap()),
|
||||
balance: ExternalBalance {
|
||||
coin: coin.try_into().unwrap(),
|
||||
amount: Amount(balance.amount.0 + 1),
|
||||
amount: (balance.amount + Amount(1)).unwrap(),
|
||||
},
|
||||
};
|
||||
assert!(
|
||||
@@ -74,7 +74,7 @@ fn burn_with_instruction() {
|
||||
|
||||
// balance & supply now should be back to 0
|
||||
assert_eq!(Coins::balance(to, coin), Amount(0));
|
||||
assert_eq!(Coins::supply(coin), 0);
|
||||
assert_eq!(Coins::supply(coin), Amount(0));
|
||||
|
||||
let burn_events = System::events()
|
||||
.iter()
|
||||
@@ -100,19 +100,19 @@ fn transfer() {
|
||||
new_test_ext().execute_with(|| {
|
||||
// mint some coin
|
||||
let coin = Coin::External(ExternalCoin::Bitcoin);
|
||||
let from = insecure_pair_from_name("random1").public();
|
||||
let from = Pair::generate().0.public();
|
||||
let balance = Balance { coin, amount: Amount(10 * 10u64.pow(coin.decimals())) };
|
||||
|
||||
Coins::mint(from, balance).unwrap();
|
||||
assert_eq!(Coins::balance(from, coin), balance.amount);
|
||||
assert_eq!(Coins::supply(coin), balance.amount.0);
|
||||
assert_eq!(Coins::supply(coin), balance.amount);
|
||||
|
||||
// we can't send more than what we have
|
||||
let to = insecure_pair_from_name("random2").public();
|
||||
let to = Pair::generate().0.public();
|
||||
assert!(Coins::transfer(
|
||||
RawOrigin::Signed(from).into(),
|
||||
to,
|
||||
Balance { coin, amount: Amount(balance.amount.0 + 1) }
|
||||
Balance { coin, amount: (balance.amount + Amount(1)).unwrap() }
|
||||
)
|
||||
.is_err());
|
||||
|
||||
@@ -124,6 +124,6 @@ fn transfer() {
|
||||
assert_eq!(Coins::balance(to, coin), balance.amount);
|
||||
|
||||
// supply shouldn't change
|
||||
assert_eq!(Coins::supply(coin), balance.amount.0);
|
||||
assert_eq!(Coins::supply(coin), balance.amount);
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user