mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-04-27 01:07:57 +00:00
Run cargo fmt on the whole code base (#9394)
* Run cargo fmt on the whole code base * Second run * Add CI check * Fix compilation * More unnecessary braces * Handle weights * Use --all * Use correct attributes... * Fix UI tests * AHHHHHHHHH * 🤦 * Docs * Fix compilation * 🤷 * Please stop * 🤦 x 2 * More * make rustfmt.toml consistent with polkadot Co-authored-by: André Silva <andrerfosilva@gmail.com>
This commit is contained in:
@@ -32,11 +32,15 @@ pub enum AllowAll {}
|
||||
pub enum DenyAll {}
|
||||
|
||||
impl<T> Filter<T> for AllowAll {
|
||||
fn filter(_: &T) -> bool { true }
|
||||
fn filter(_: &T) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Filter<T> for DenyAll {
|
||||
fn filter(_: &T) -> bool { false }
|
||||
fn filter(_: &T) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Trait to add a constraint onto the filter.
|
||||
@@ -101,17 +105,28 @@ pub trait InstanceFilter<T>: Sized + Send + Sync {
|
||||
fn filter(&self, _: &T) -> bool;
|
||||
|
||||
/// Determines whether `self` matches at least everything that `_o` does.
|
||||
fn is_superset(&self, _o: &Self) -> bool { false }
|
||||
fn is_superset(&self, _o: &Self) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> InstanceFilter<T> for () {
|
||||
fn filter(&self, _: &T) -> bool { true }
|
||||
fn is_superset(&self, _o: &Self) -> bool { true }
|
||||
fn filter(&self, _: &T) -> bool {
|
||||
true
|
||||
}
|
||||
fn is_superset(&self, _o: &Self) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-expected for the macro.
|
||||
#[doc(hidden)]
|
||||
pub use sp_std::{mem::{swap, take}, cell::RefCell, vec::Vec, boxed::Box};
|
||||
pub use sp_std::{
|
||||
boxed::Box,
|
||||
cell::RefCell,
|
||||
mem::{swap, take},
|
||||
vec::Vec,
|
||||
};
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! impl_filter_stack {
|
||||
@@ -206,7 +221,9 @@ pub mod test_impl_filter_stack {
|
||||
pub struct IsCallable;
|
||||
pub struct BaseFilter;
|
||||
impl Filter<u32> for BaseFilter {
|
||||
fn filter(x: &u32) -> bool { x % 2 == 0 }
|
||||
fn filter(x: &u32) -> bool {
|
||||
x % 2 == 0
|
||||
}
|
||||
}
|
||||
impl_filter_stack!(
|
||||
crate::traits::filter::test_impl_filter_stack::IsCallable,
|
||||
|
||||
@@ -17,9 +17,9 @@
|
||||
|
||||
//! Traits for hooking tasks to events in a blockchain's lifecycle.
|
||||
|
||||
use impl_trait_for_tuples::impl_for_tuples;
|
||||
use sp_arithmetic::traits::Saturating;
|
||||
use sp_runtime::traits::MaybeSerializeDeserialize;
|
||||
use impl_trait_for_tuples::impl_for_tuples;
|
||||
|
||||
/// The block initialization trait.
|
||||
///
|
||||
@@ -33,7 +33,9 @@ pub trait OnInitialize<BlockNumber> {
|
||||
/// NOTE: This function is called BEFORE ANY extrinsic in a block is applied,
|
||||
/// including inherent extrinsics. Hence for instance, if you runtime includes
|
||||
/// `pallet_timestamp`, the `timestamp` is not yet up to date at this point.
|
||||
fn on_initialize(_n: BlockNumber) -> crate::weights::Weight { 0 }
|
||||
fn on_initialize(_n: BlockNumber) -> crate::weights::Weight {
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
#[impl_for_tuples(30)]
|
||||
@@ -71,7 +73,7 @@ pub trait OnIdle<BlockNumber> {
|
||||
/// in a block are applied but before `on_finalize` is executed.
|
||||
fn on_idle(
|
||||
_n: BlockNumber,
|
||||
_remaining_weight: crate::weights::Weight
|
||||
_remaining_weight: crate::weights::Weight,
|
||||
) -> crate::weights::Weight {
|
||||
0
|
||||
}
|
||||
@@ -79,7 +81,7 @@ pub trait OnIdle<BlockNumber> {
|
||||
|
||||
#[impl_for_tuples(30)]
|
||||
impl<BlockNumber: Clone> OnIdle<BlockNumber> for Tuple {
|
||||
fn on_idle(n: BlockNumber, remaining_weight: crate::weights::Weight) -> crate::weights::Weight {
|
||||
fn on_idle(n: BlockNumber, remaining_weight: crate::weights::Weight) -> crate::weights::Weight {
|
||||
let mut weight = 0;
|
||||
for_tuples!( #(
|
||||
let adjusted_remaining_weight = remaining_weight.saturating_sub(weight);
|
||||
@@ -170,13 +172,17 @@ pub trait OnRuntimeUpgrade {
|
||||
///
|
||||
/// This hook is never meant to be executed on-chain but is meant to be used by testing tools.
|
||||
#[cfg(feature = "try-runtime")]
|
||||
fn pre_upgrade() -> Result<(), &'static str> { Ok(()) }
|
||||
fn pre_upgrade() -> Result<(), &'static str> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Execute some post-checks after a runtime upgrade.
|
||||
///
|
||||
/// This hook is never meant to be executed on-chain but is meant to be used by testing tools.
|
||||
#[cfg(feature = "try-runtime")]
|
||||
fn post_upgrade() -> Result<(), &'static str> { Ok(()) }
|
||||
fn post_upgrade() -> Result<(), &'static str> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[impl_for_tuples(30)]
|
||||
@@ -214,7 +220,7 @@ pub trait Hooks<BlockNumber> {
|
||||
/// and pass the result to the next `on_idle` hook if it exists.
|
||||
fn on_idle(
|
||||
_n: BlockNumber,
|
||||
_remaining_weight: crate::weights::Weight
|
||||
_remaining_weight: crate::weights::Weight,
|
||||
) -> crate::weights::Weight {
|
||||
0
|
||||
}
|
||||
@@ -222,7 +228,9 @@ pub trait Hooks<BlockNumber> {
|
||||
/// The block is being initialized. Implement to have something happen.
|
||||
///
|
||||
/// Return the non-negotiable weight consumed in the block.
|
||||
fn on_initialize(_n: BlockNumber) -> crate::weights::Weight { 0 }
|
||||
fn on_initialize(_n: BlockNumber) -> crate::weights::Weight {
|
||||
0
|
||||
}
|
||||
|
||||
/// Perform a module upgrade.
|
||||
///
|
||||
@@ -238,7 +246,9 @@ pub trait Hooks<BlockNumber> {
|
||||
/// block local data are not accessible.
|
||||
///
|
||||
/// Return the non-negotiable weight consumed for runtime upgrade.
|
||||
fn on_runtime_upgrade() -> crate::weights::Weight { 0 }
|
||||
fn on_runtime_upgrade() -> crate::weights::Weight {
|
||||
0
|
||||
}
|
||||
|
||||
/// Execute some pre-checks prior to a runtime upgrade.
|
||||
///
|
||||
@@ -282,7 +292,7 @@ pub trait Hooks<BlockNumber> {
|
||||
/// A trait to define the build function of a genesis config, T and I are placeholder for pallet
|
||||
/// trait and pallet instance.
|
||||
#[cfg(feature = "std")]
|
||||
pub trait GenesisBuild<T, I=()>: Default + MaybeSerializeDeserialize {
|
||||
pub trait GenesisBuild<T, I = ()>: Default + MaybeSerializeDeserialize {
|
||||
/// The build function is called within an externalities allowing storage APIs.
|
||||
/// Thus one can write to storage using regular pallet storages.
|
||||
fn build(&self);
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
|
||||
//! Traits for dealing with the idea of membership.
|
||||
|
||||
use sp_std::{prelude::*, marker::PhantomData};
|
||||
use sp_std::{marker::PhantomData, prelude::*};
|
||||
|
||||
/// A trait for querying whether a type can be said to "contain" a value.
|
||||
pub trait Contains<T> {
|
||||
@@ -28,7 +28,9 @@ pub trait Contains<T> {
|
||||
/// A `Contains` implementation which always returns `true`.
|
||||
pub struct All<T>(PhantomData<T>);
|
||||
impl<T> Contains<T> for All<T> {
|
||||
fn contains(_: &T) -> bool { true }
|
||||
fn contains(_: &T) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
#[impl_trait_for_tuples::impl_for_tuples(30)]
|
||||
@@ -77,32 +79,46 @@ pub trait SortedMembers<T: Ord> {
|
||||
fn sorted_members() -> Vec<T>;
|
||||
|
||||
/// Return `true` if this "contains" the given value `t`.
|
||||
fn contains(t: &T) -> bool { Self::sorted_members().binary_search(t).is_ok() }
|
||||
fn contains(t: &T) -> bool {
|
||||
Self::sorted_members().binary_search(t).is_ok()
|
||||
}
|
||||
|
||||
/// Get the number of items in the set.
|
||||
fn count() -> usize { Self::sorted_members().len() }
|
||||
fn count() -> usize {
|
||||
Self::sorted_members().len()
|
||||
}
|
||||
|
||||
/// Add an item that would satisfy `contains`. It does not make sure any other
|
||||
/// state is correctly maintained or generated.
|
||||
///
|
||||
/// **Should be used for benchmarking only!!!**
|
||||
#[cfg(feature = "runtime-benchmarks")]
|
||||
fn add(_t: &T) { unimplemented!() }
|
||||
fn add(_t: &T) {
|
||||
unimplemented!()
|
||||
}
|
||||
}
|
||||
|
||||
/// Adapter struct for turning an `OrderedMembership` impl into a `Contains` impl.
|
||||
pub struct AsContains<OM>(PhantomData<(OM,)>);
|
||||
impl<T: Ord + Eq, OM: SortedMembers<T>> Contains<T> for AsContains<OM> {
|
||||
fn contains(t: &T) -> bool { OM::contains(t) }
|
||||
fn contains(t: &T) -> bool {
|
||||
OM::contains(t)
|
||||
}
|
||||
}
|
||||
|
||||
/// Trivial utility for implementing `Contains`/`OrderedMembership` with a `Vec`.
|
||||
pub struct IsInVec<T>(PhantomData<T>);
|
||||
impl<X: Eq, T: super::Get<Vec<X>>> Contains<X> for IsInVec<T> {
|
||||
fn contains(t: &X) -> bool { T::get().contains(t) }
|
||||
fn contains(t: &X) -> bool {
|
||||
T::get().contains(t)
|
||||
}
|
||||
}
|
||||
impl<X: Ord + PartialOrd, T: super::Get<Vec<X>>> SortedMembers<X> for IsInVec<T> {
|
||||
fn sorted_members() -> Vec<X> { let mut r = T::get(); r.sort(); r }
|
||||
fn sorted_members() -> Vec<X> {
|
||||
let mut r = T::get();
|
||||
r.sort();
|
||||
r
|
||||
}
|
||||
}
|
||||
|
||||
/// A trait for querying bound for the length of an implementation of `Contains`
|
||||
@@ -174,19 +190,19 @@ pub trait ChangeMembers<AccountId: Clone + Ord> {
|
||||
(Some(old), Some(new)) if old == new => {
|
||||
old_i = old_iter.next();
|
||||
new_i = new_iter.next();
|
||||
}
|
||||
},
|
||||
(Some(old), Some(new)) if old < new => {
|
||||
outgoing.push(old.clone());
|
||||
old_i = old_iter.next();
|
||||
}
|
||||
},
|
||||
(Some(old), None) => {
|
||||
outgoing.push(old.clone());
|
||||
old_i = old_iter.next();
|
||||
}
|
||||
},
|
||||
(_, Some(new)) => {
|
||||
incoming.push(new.clone());
|
||||
new_i = new_iter.next();
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
(incoming, outgoing)
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
|
||||
//! Traits for managing information attached to pallets and their constituents.
|
||||
|
||||
use codec::{Encode, Decode};
|
||||
use codec::{Decode, Encode};
|
||||
use sp_runtime::RuntimeDebug;
|
||||
|
||||
/// Provides information about the pallet setup in the runtime.
|
||||
@@ -91,11 +91,7 @@ pub struct PalletVersion {
|
||||
impl PalletVersion {
|
||||
/// Creates a new instance of `Self`.
|
||||
pub fn new(major: u16, minor: u8, patch: u8) -> Self {
|
||||
Self {
|
||||
major,
|
||||
minor,
|
||||
patch,
|
||||
}
|
||||
Self { major, minor, patch }
|
||||
}
|
||||
|
||||
/// Returns the storage key for a pallet version.
|
||||
@@ -139,13 +135,10 @@ impl PalletVersion {
|
||||
|
||||
impl sp_std::cmp::PartialOrd for PalletVersion {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<sp_std::cmp::Ordering> {
|
||||
let res = self.major
|
||||
let res = self
|
||||
.major
|
||||
.cmp(&other.major)
|
||||
.then_with(||
|
||||
self.minor
|
||||
.cmp(&other.minor)
|
||||
.then_with(|| self.patch.cmp(&other.patch)
|
||||
));
|
||||
.then_with(|| self.minor.cmp(&other.minor).then_with(|| self.patch.cmp(&other.patch)));
|
||||
|
||||
Some(res)
|
||||
}
|
||||
|
||||
@@ -17,9 +17,9 @@
|
||||
|
||||
//! Smaller traits used in FRAME which don't need their own file.
|
||||
|
||||
use sp_runtime::{traits::Block as BlockT, DispatchError};
|
||||
use sp_arithmetic::traits::AtLeast32Bit;
|
||||
use crate::dispatch::Parameter;
|
||||
use sp_arithmetic::traits::AtLeast32Bit;
|
||||
use sp_runtime::{traits::Block as BlockT, DispatchError};
|
||||
|
||||
/// Anything that can have a `::len()` method.
|
||||
pub trait Len {
|
||||
@@ -27,7 +27,10 @@ pub trait Len {
|
||||
fn len(&self) -> usize;
|
||||
}
|
||||
|
||||
impl<T: IntoIterator + Clone,> Len for T where <T as IntoIterator>::IntoIter: ExactSizeIterator {
|
||||
impl<T: IntoIterator + Clone> Len for T
|
||||
where
|
||||
<T as IntoIterator>::IntoIter: ExactSizeIterator,
|
||||
{
|
||||
fn len(&self) -> usize {
|
||||
self.clone().into_iter().len()
|
||||
}
|
||||
@@ -42,7 +45,9 @@ pub trait Get<T> {
|
||||
}
|
||||
|
||||
impl<T: Default> Get<T> for () {
|
||||
fn get() -> T { T::default() }
|
||||
fn get() -> T {
|
||||
T::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Implement Get by returning Default for any type that implements Default.
|
||||
@@ -123,7 +128,10 @@ impl<A, B> SameOrOther<A, B> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn same(self) -> Result<A, B> where A: Default {
|
||||
pub fn same(self) -> Result<A, B>
|
||||
where
|
||||
A: Default,
|
||||
{
|
||||
match self {
|
||||
SameOrOther::Same(a) => Ok(a),
|
||||
SameOrOther::None => Ok(A::default()),
|
||||
@@ -131,7 +139,10 @@ impl<A, B> SameOrOther<A, B> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn other(self) -> Result<B, A> where B: Default {
|
||||
pub fn other(self) -> Result<B, A>
|
||||
where
|
||||
B: Default,
|
||||
{
|
||||
match self {
|
||||
SameOrOther::Same(a) => Err(a),
|
||||
SameOrOther::None => Ok(B::default()),
|
||||
@@ -157,10 +168,14 @@ pub trait OnKilledAccount<AccountId> {
|
||||
/// A simple, generic one-parameter event notifier/handler.
|
||||
pub trait HandleLifetime<T> {
|
||||
/// An account was created.
|
||||
fn created(_t: &T) -> Result<(), DispatchError> { Ok(()) }
|
||||
fn created(_t: &T) -> Result<(), DispatchError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// An account was killed.
|
||||
fn killed(_t: &T) -> Result<(), DispatchError> { Ok(()) }
|
||||
fn killed(_t: &T) -> Result<(), DispatchError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> HandleLifetime<T> for () {}
|
||||
@@ -195,10 +210,18 @@ pub trait IsType<T>: Into<T> + From<T> {
|
||||
}
|
||||
|
||||
impl<T> IsType<T> for T {
|
||||
fn from_ref(t: &T) -> &Self { t }
|
||||
fn into_ref(&self) -> &T { self }
|
||||
fn from_mut(t: &mut T) -> &mut Self { t }
|
||||
fn into_mut(&mut self) -> &mut T { self }
|
||||
fn from_ref(t: &T) -> &Self {
|
||||
t
|
||||
}
|
||||
fn into_ref(&self) -> &T {
|
||||
self
|
||||
}
|
||||
fn from_mut(t: &mut T) -> &mut Self {
|
||||
t
|
||||
}
|
||||
fn into_mut(&mut self) -> &mut T {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Something that can be checked to be a of sub type `T`.
|
||||
@@ -300,8 +323,6 @@ pub trait GetBacking {
|
||||
fn get_backing(&self) -> Option<Backing>;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// A trait to ensure the inherent are before non-inherent in a block.
|
||||
///
|
||||
/// This is typically implemented on runtime, through `construct_runtime!`.
|
||||
@@ -319,7 +340,8 @@ pub trait ExtrinsicCall: sp_runtime::traits::Extrinsic {
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl<Call, Extra> ExtrinsicCall for sp_runtime::testing::TestXt<Call, Extra> where
|
||||
impl<Call, Extra> ExtrinsicCall for sp_runtime::testing::TestXt<Call, Extra>
|
||||
where
|
||||
Call: codec::Codec + Sync + Send,
|
||||
{
|
||||
fn call(&self) -> &Self::Call {
|
||||
@@ -328,7 +350,7 @@ impl<Call, Extra> ExtrinsicCall for sp_runtime::testing::TestXt<Call, Extra> whe
|
||||
}
|
||||
|
||||
impl<Address, Call, Signature, Extra> ExtrinsicCall
|
||||
for sp_runtime::generic::UncheckedExtrinsic<Address, Call, Signature, Extra>
|
||||
for sp_runtime::generic::UncheckedExtrinsic<Address, Call, Signature, Extra>
|
||||
where
|
||||
Extra: sp_runtime::traits::SignedExtension,
|
||||
{
|
||||
|
||||
@@ -17,9 +17,9 @@
|
||||
|
||||
//! Traits and associated utilities for scheduling dispatchables in FRAME.
|
||||
|
||||
use sp_std::{prelude::*, fmt::Debug};
|
||||
use codec::{Encode, Decode, Codec, EncodeLike};
|
||||
use sp_runtime::{RuntimeDebug, DispatchError};
|
||||
use codec::{Codec, Decode, Encode, EncodeLike};
|
||||
use sp_runtime::{DispatchError, RuntimeDebug};
|
||||
use sp_std::{fmt::Debug, prelude::*};
|
||||
|
||||
/// Information relating to the period of a scheduled task. First item is the length of the
|
||||
/// period and the second is the number of times it should be executed in total before the task
|
||||
@@ -61,7 +61,7 @@ pub trait Anon<BlockNumber, Call, Origin> {
|
||||
maybe_periodic: Option<Period<BlockNumber>>,
|
||||
priority: Priority,
|
||||
origin: Origin,
|
||||
call: Call
|
||||
call: Call,
|
||||
) -> Result<Self::Address, DispatchError>;
|
||||
|
||||
/// Cancel a scheduled task. If periodic, then it will cancel all further instances of that,
|
||||
@@ -107,7 +107,7 @@ pub trait Named<BlockNumber, Call, Origin> {
|
||||
maybe_periodic: Option<Period<BlockNumber>>,
|
||||
priority: Priority,
|
||||
origin: Origin,
|
||||
call: Call
|
||||
call: Call,
|
||||
) -> Result<Self::Address, ()>;
|
||||
|
||||
/// Cancel a scheduled, named task. If periodic, then it will cancel all further instances
|
||||
|
||||
@@ -17,10 +17,9 @@
|
||||
|
||||
//! Traits and associated datatypes for managing abstract stored values.
|
||||
|
||||
use crate::{storage::StorageMap, traits::misc::HandleLifetime};
|
||||
use codec::FullCodec;
|
||||
use sp_runtime::DispatchError;
|
||||
use crate::storage::StorageMap;
|
||||
use crate::traits::misc::HandleLifetime;
|
||||
|
||||
/// An abstraction of a value stored within storage, but possibly as part of a larger composite
|
||||
/// item.
|
||||
@@ -47,25 +46,26 @@ pub trait StoredMap<K, T: Default> {
|
||||
let r = f(&mut account);
|
||||
*x = Some(account);
|
||||
r
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/// Mutate the item, removing or resetting to default value if it has been mutated to `None`.
|
||||
///
|
||||
/// This is infallible as long as the value does not get destroyed.
|
||||
fn mutate_exists<R>(
|
||||
k: &K,
|
||||
f: impl FnOnce(&mut Option<T>) -> R,
|
||||
) -> Result<R, DispatchError> {
|
||||
fn mutate_exists<R>(k: &K, f: impl FnOnce(&mut Option<T>) -> R) -> Result<R, DispatchError> {
|
||||
Self::try_mutate_exists(k, |x| -> Result<R, DispatchError> { Ok(f(x)) })
|
||||
}
|
||||
|
||||
/// Set the item to something new.
|
||||
fn insert(k: &K, t: T) -> Result<(), DispatchError> { Self::mutate(k, |i| *i = t) }
|
||||
fn insert(k: &K, t: T) -> Result<(), DispatchError> {
|
||||
Self::mutate(k, |i| *i = t)
|
||||
}
|
||||
|
||||
/// Remove the item or otherwise replace it with its default value; we don't care which.
|
||||
fn remove(k: &K) -> Result<(), DispatchError> { Self::mutate_exists(k, |x| *x = None) }
|
||||
fn remove(k: &K) -> Result<(), DispatchError> {
|
||||
Self::mutate_exists(k, |x| *x = None)
|
||||
}
|
||||
}
|
||||
|
||||
/// A shim for placing around a storage item in order to use it as a `StoredValue`. Ideally this
|
||||
@@ -81,12 +81,15 @@ pub trait StoredMap<K, T: Default> {
|
||||
/// system module's `CallOnCreatedAccount` and `CallKillAccount`.
|
||||
pub struct StorageMapShim<S, L, K, T>(sp_std::marker::PhantomData<(S, L, K, T)>);
|
||||
impl<
|
||||
S: StorageMap<K, T, Query=T>,
|
||||
L: HandleLifetime<K>,
|
||||
K: FullCodec,
|
||||
T: FullCodec + Default,
|
||||
> StoredMap<K, T> for StorageMapShim<S, L, K, T> {
|
||||
fn get(k: &K) -> T { S::get(k) }
|
||||
S: StorageMap<K, T, Query = T>,
|
||||
L: HandleLifetime<K>,
|
||||
K: FullCodec,
|
||||
T: FullCodec + Default,
|
||||
> StoredMap<K, T> for StorageMapShim<S, L, K, T>
|
||||
{
|
||||
fn get(k: &K) -> T {
|
||||
S::get(k)
|
||||
}
|
||||
fn insert(k: &K, t: T) -> Result<(), DispatchError> {
|
||||
if !S::contains_key(&k) {
|
||||
L::created(k)?;
|
||||
|
||||
@@ -17,15 +17,15 @@
|
||||
|
||||
//! Traits for working with tokens and their associated datastructures.
|
||||
|
||||
pub mod currency;
|
||||
pub mod fungible;
|
||||
pub mod fungibles;
|
||||
pub mod currency;
|
||||
pub mod imbalance;
|
||||
mod misc;
|
||||
pub mod nonfungible;
|
||||
pub mod nonfungibles;
|
||||
mod misc;
|
||||
pub use misc::{
|
||||
BalanceConversion, BalanceStatus, DepositConsequence,
|
||||
ExistenceRequirement, WithdrawConsequence, WithdrawReasons,
|
||||
};
|
||||
pub use imbalance::Imbalance;
|
||||
pub use misc::{
|
||||
BalanceConversion, BalanceStatus, DepositConsequence, ExistenceRequirement,
|
||||
WithdrawConsequence, WithdrawReasons,
|
||||
};
|
||||
|
||||
@@ -17,17 +17,19 @@
|
||||
|
||||
//! The Currency trait and associated types.
|
||||
|
||||
use sp_std::fmt::Debug;
|
||||
use sp_runtime::traits::MaybeSerializeDeserialize;
|
||||
use crate::dispatch::{DispatchResult, DispatchError};
|
||||
use super::misc::{Balance, WithdrawReasons, ExistenceRequirement};
|
||||
use super::imbalance::{Imbalance, SignedImbalance};
|
||||
use super::{
|
||||
imbalance::{Imbalance, SignedImbalance},
|
||||
misc::{Balance, ExistenceRequirement, WithdrawReasons},
|
||||
};
|
||||
use crate::dispatch::{DispatchError, DispatchResult};
|
||||
use codec::MaxEncodedLen;
|
||||
use sp_runtime::traits::MaybeSerializeDeserialize;
|
||||
use sp_std::fmt::Debug;
|
||||
|
||||
mod reservable;
|
||||
pub use reservable::{ReservableCurrency, NamedReservableCurrency};
|
||||
pub use reservable::{NamedReservableCurrency, ReservableCurrency};
|
||||
mod lockable;
|
||||
pub use lockable::{LockableCurrency, VestingSchedule, LockIdentifier};
|
||||
pub use lockable::{LockIdentifier, LockableCurrency, VestingSchedule};
|
||||
|
||||
/// Abstraction over a fungible assets system.
|
||||
pub trait Currency<AccountId> {
|
||||
@@ -36,11 +38,11 @@ pub trait Currency<AccountId> {
|
||||
|
||||
/// The opaque token type for an imbalance. This is returned by unbalanced operations
|
||||
/// and must be dealt with. It may be dropped but cannot be cloned.
|
||||
type PositiveImbalance: Imbalance<Self::Balance, Opposite=Self::NegativeImbalance>;
|
||||
type PositiveImbalance: Imbalance<Self::Balance, Opposite = Self::NegativeImbalance>;
|
||||
|
||||
/// The opaque token type for an imbalance. This is returned by unbalanced operations
|
||||
/// and must be dealt with. It may be dropped but cannot be cloned.
|
||||
type NegativeImbalance: Imbalance<Self::Balance, Opposite=Self::PositiveImbalance>;
|
||||
type NegativeImbalance: Imbalance<Self::Balance, Opposite = Self::PositiveImbalance>;
|
||||
|
||||
// PUBLIC IMMUTABLES
|
||||
|
||||
@@ -123,17 +125,14 @@ pub trait Currency<AccountId> {
|
||||
///
|
||||
/// As much funds up to `value` will be deducted as possible. If this is less than `value`,
|
||||
/// then a non-zero second item will be returned.
|
||||
fn slash(
|
||||
who: &AccountId,
|
||||
value: Self::Balance
|
||||
) -> (Self::NegativeImbalance, Self::Balance);
|
||||
fn slash(who: &AccountId, value: Self::Balance) -> (Self::NegativeImbalance, Self::Balance);
|
||||
|
||||
/// Mints `value` to the free balance of `who`.
|
||||
///
|
||||
/// If `who` doesn't exist, nothing is done and an Err returned.
|
||||
fn deposit_into_existing(
|
||||
who: &AccountId,
|
||||
value: Self::Balance
|
||||
value: Self::Balance,
|
||||
) -> Result<Self::PositiveImbalance, DispatchError>;
|
||||
|
||||
/// Similar to deposit_creating, only accepts a `NegativeImbalance` and returns nothing on
|
||||
@@ -152,17 +151,11 @@ pub trait Currency<AccountId> {
|
||||
/// Adds up to `value` to the free balance of `who`. If `who` doesn't exist, it is created.
|
||||
///
|
||||
/// Infallible.
|
||||
fn deposit_creating(
|
||||
who: &AccountId,
|
||||
value: Self::Balance,
|
||||
) -> Self::PositiveImbalance;
|
||||
fn deposit_creating(who: &AccountId, value: Self::Balance) -> Self::PositiveImbalance;
|
||||
|
||||
/// Similar to deposit_creating, only accepts a `NegativeImbalance` and returns nothing on
|
||||
/// success.
|
||||
fn resolve_creating(
|
||||
who: &AccountId,
|
||||
value: Self::NegativeImbalance,
|
||||
) {
|
||||
fn resolve_creating(who: &AccountId, value: Self::NegativeImbalance) {
|
||||
let v = value.peek();
|
||||
drop(value.offset(Self::deposit_creating(who, v)));
|
||||
}
|
||||
|
||||
@@ -17,10 +17,8 @@
|
||||
|
||||
//! The lockable currency trait and some associated types.
|
||||
|
||||
use crate::dispatch::DispatchResult;
|
||||
use crate::traits::misc::Get;
|
||||
use super::Currency;
|
||||
use super::super::misc::WithdrawReasons;
|
||||
use super::{super::misc::WithdrawReasons, Currency};
|
||||
use crate::{dispatch::DispatchResult, traits::misc::Get};
|
||||
|
||||
/// An identifier for a lock. Used for disambiguating different locks so that
|
||||
/// they can be individually replaced or removed.
|
||||
@@ -63,10 +61,7 @@ pub trait LockableCurrency<AccountId>: Currency<AccountId> {
|
||||
);
|
||||
|
||||
/// Remove an existing lock.
|
||||
fn remove_lock(
|
||||
id: LockIdentifier,
|
||||
who: &AccountId,
|
||||
);
|
||||
fn remove_lock(id: LockIdentifier, who: &AccountId);
|
||||
}
|
||||
|
||||
/// A vesting schedule over a currency. This allows a particular currency to have vesting limits
|
||||
@@ -80,7 +75,8 @@ pub trait VestingSchedule<AccountId> {
|
||||
|
||||
/// Get the amount that is currently being vested and cannot be transferred out of this account.
|
||||
/// Returns `None` if the account has no vesting schedule.
|
||||
fn vesting_balance(who: &AccountId) -> Option<<Self::Currency as Currency<AccountId>>::Balance>;
|
||||
fn vesting_balance(who: &AccountId)
|
||||
-> Option<<Self::Currency as Currency<AccountId>>::Balance>;
|
||||
|
||||
/// Adds a vesting schedule to a given account.
|
||||
///
|
||||
|
||||
@@ -17,9 +17,8 @@
|
||||
|
||||
//! The reservable currency trait.
|
||||
|
||||
use super::Currency;
|
||||
use super::super::misc::BalanceStatus;
|
||||
use crate::dispatch::{DispatchResult, DispatchError};
|
||||
use super::{super::misc::BalanceStatus, Currency};
|
||||
use crate::dispatch::{DispatchError, DispatchResult};
|
||||
|
||||
/// A currency where funds can be reserved from the user.
|
||||
pub trait ReservableCurrency<AccountId>: Currency<AccountId> {
|
||||
@@ -33,7 +32,7 @@ pub trait ReservableCurrency<AccountId>: Currency<AccountId> {
|
||||
/// is less than `value`, then a non-zero second item will be returned.
|
||||
fn slash_reserved(
|
||||
who: &AccountId,
|
||||
value: Self::Balance
|
||||
value: Self::Balance,
|
||||
) -> (Self::NegativeImbalance, Self::Balance);
|
||||
|
||||
/// The amount of the balance of a given account that is externally reserved; this can still get
|
||||
@@ -94,7 +93,7 @@ pub trait NamedReservableCurrency<AccountId>: ReservableCurrency<AccountId> {
|
||||
fn slash_reserved_named(
|
||||
id: &Self::ReserveIdentifier,
|
||||
who: &AccountId,
|
||||
value: Self::Balance
|
||||
value: Self::Balance,
|
||||
) -> (Self::NegativeImbalance, Self::Balance);
|
||||
|
||||
/// The amount of the balance of a given account that is externally reserved; this can still get
|
||||
@@ -114,7 +113,11 @@ pub trait NamedReservableCurrency<AccountId>: ReservableCurrency<AccountId> {
|
||||
///
|
||||
/// If the free balance is lower than `value`, then no funds will be moved and an `Err` will
|
||||
/// be returned to notify of this. This is different behavior than `unreserve`.
|
||||
fn reserve_named(id: &Self::ReserveIdentifier, who: &AccountId, value: Self::Balance) -> DispatchResult;
|
||||
fn reserve_named(
|
||||
id: &Self::ReserveIdentifier,
|
||||
who: &AccountId,
|
||||
value: Self::Balance,
|
||||
) -> DispatchResult;
|
||||
|
||||
/// Moves up to `value` from reserved balance to free balance. This function cannot fail.
|
||||
///
|
||||
@@ -126,7 +129,11 @@ pub trait NamedReservableCurrency<AccountId>: ReservableCurrency<AccountId> {
|
||||
/// - This is different from `reserve`.
|
||||
/// - If the remaining reserved balance is less than `ExistentialDeposit`, it will
|
||||
/// invoke `on_reserved_too_low` and could reap the account.
|
||||
fn unreserve_named(id: &Self::ReserveIdentifier, who: &AccountId, value: Self::Balance) -> Self::Balance;
|
||||
fn unreserve_named(
|
||||
id: &Self::ReserveIdentifier,
|
||||
who: &AccountId,
|
||||
value: Self::Balance,
|
||||
) -> Self::Balance;
|
||||
|
||||
/// Moves up to `value` from reserved balance of account `slashed` to balance of account
|
||||
/// `beneficiary`. `beneficiary` must exist for this to succeed. If it does not, `Err` will be
|
||||
@@ -147,16 +154,21 @@ pub trait NamedReservableCurrency<AccountId>: ReservableCurrency<AccountId> {
|
||||
///
|
||||
/// This will reserve extra amount of current reserved balance is less than `value`.
|
||||
/// And unreserve if current reserved balance is greater than `value`.
|
||||
fn ensure_reserved_named(id: &Self::ReserveIdentifier, who: &AccountId, value: Self::Balance) -> DispatchResult {
|
||||
fn ensure_reserved_named(
|
||||
id: &Self::ReserveIdentifier,
|
||||
who: &AccountId,
|
||||
value: Self::Balance,
|
||||
) -> DispatchResult {
|
||||
let current = Self::reserved_balance_named(id, who);
|
||||
if current > value {
|
||||
if current > value {
|
||||
// we always have enough balance to unreserve here
|
||||
Self::unreserve_named(id, who, current - value);
|
||||
Ok(())
|
||||
} else if value > current {
|
||||
// we checked value > current
|
||||
Self::reserve_named(id, who, value - current)
|
||||
} else { // current == value
|
||||
} else {
|
||||
// current == value
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -173,7 +185,10 @@ pub trait NamedReservableCurrency<AccountId>: ReservableCurrency<AccountId> {
|
||||
/// Slash all the reserved balance, returning the negative imbalance created.
|
||||
///
|
||||
/// Is a no-op if the value to be slashed is zero.
|
||||
fn slash_all_reserved_named(id: &Self::ReserveIdentifier, who: &AccountId) -> Self::NegativeImbalance {
|
||||
fn slash_all_reserved_named(
|
||||
id: &Self::ReserveIdentifier,
|
||||
who: &AccountId,
|
||||
) -> Self::NegativeImbalance {
|
||||
let value = Self::reserved_balance_named(id, who);
|
||||
Self::slash_reserved_named(id, who, value).0
|
||||
}
|
||||
|
||||
@@ -17,16 +17,20 @@
|
||||
|
||||
//! The traits for dealing with a single fungible token class and any associated types.
|
||||
|
||||
use super::*;
|
||||
use super::{
|
||||
misc::{Balance, DepositConsequence, WithdrawConsequence},
|
||||
*,
|
||||
};
|
||||
use crate::{
|
||||
dispatch::{DispatchError, DispatchResult},
|
||||
traits::misc::Get,
|
||||
};
|
||||
use sp_runtime::traits::Saturating;
|
||||
use crate::traits::misc::Get;
|
||||
use crate::dispatch::{DispatchResult, DispatchError};
|
||||
use super::misc::{DepositConsequence, WithdrawConsequence, Balance};
|
||||
|
||||
mod balanced;
|
||||
mod imbalance;
|
||||
pub use balanced::{Balanced, Unbalanced};
|
||||
pub use imbalance::{Imbalance, HandleImbalanceDrop, DebtOf, CreditOf};
|
||||
pub use imbalance::{CreditOf, DebtOf, HandleImbalanceDrop, Imbalance};
|
||||
|
||||
/// Trait for providing balance-inspection access to a fungible asset.
|
||||
pub trait Inspect<AccountId> {
|
||||
@@ -84,7 +88,10 @@ pub trait Mutate<AccountId>: Inspect<AccountId> {
|
||||
let extra = Self::can_withdraw(&source, amount).into_result()?;
|
||||
Self::can_deposit(&dest, amount.saturating_add(extra)).into_result()?;
|
||||
let actual = Self::burn_from(source, amount)?;
|
||||
debug_assert!(actual == amount.saturating_add(extra), "can_withdraw must agree with withdraw; qed");
|
||||
debug_assert!(
|
||||
actual == amount.saturating_add(extra),
|
||||
"can_withdraw must agree with withdraw; qed"
|
||||
);
|
||||
match Self::mint_into(dest, actual) {
|
||||
Ok(_) => Ok(actual),
|
||||
Err(err) => {
|
||||
@@ -93,7 +100,7 @@ pub trait Mutate<AccountId>: Inspect<AccountId> {
|
||||
let revert = Self::mint_into(source, actual);
|
||||
debug_assert!(revert.is_ok(), "withdrew funds previously; qed");
|
||||
Err(err)
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -129,8 +136,11 @@ pub trait MutateHold<AccountId>: InspectHold<AccountId> + Transfer<AccountId> {
|
||||
///
|
||||
/// If `best_effort` is `true`, then the amount actually unreserved and returned as the inner
|
||||
/// value of `Ok` may be smaller than the `amount` passed.
|
||||
fn release(who: &AccountId, amount: Self::Balance, best_effort: bool)
|
||||
-> Result<Self::Balance, DispatchError>;
|
||||
fn release(
|
||||
who: &AccountId,
|
||||
amount: Self::Balance,
|
||||
best_effort: bool,
|
||||
) -> Result<Self::Balance, DispatchError>;
|
||||
|
||||
/// Transfer held funds into a destination account.
|
||||
///
|
||||
@@ -160,17 +170,17 @@ pub trait BalancedHold<AccountId>: Balanced<AccountId> + MutateHold<AccountId> {
|
||||
///
|
||||
/// As much funds that are on hold up to `amount` will be deducted as possible. If this is less
|
||||
/// than `amount`, then a non-zero second item will be returned.
|
||||
fn slash_held(who: &AccountId, amount: Self::Balance)
|
||||
-> (CreditOf<AccountId, Self>, Self::Balance);
|
||||
fn slash_held(
|
||||
who: &AccountId,
|
||||
amount: Self::Balance,
|
||||
) -> (CreditOf<AccountId, Self>, Self::Balance);
|
||||
}
|
||||
|
||||
impl<
|
||||
AccountId,
|
||||
T: Balanced<AccountId> + MutateHold<AccountId>,
|
||||
> BalancedHold<AccountId> for T {
|
||||
fn slash_held(who: &AccountId, amount: Self::Balance)
|
||||
-> (CreditOf<AccountId, Self>, Self::Balance)
|
||||
{
|
||||
impl<AccountId, T: Balanced<AccountId> + MutateHold<AccountId>> BalancedHold<AccountId> for T {
|
||||
fn slash_held(
|
||||
who: &AccountId,
|
||||
amount: Self::Balance,
|
||||
) -> (CreditOf<AccountId, Self>, Self::Balance) {
|
||||
let actual = match Self::release(who, amount, true) {
|
||||
Ok(x) => x,
|
||||
Err(_) => return (Imbalance::default(), amount),
|
||||
@@ -185,15 +195,14 @@ pub struct ItemOf<
|
||||
F: fungibles::Inspect<AccountId>,
|
||||
A: Get<<F as fungibles::Inspect<AccountId>>::AssetId>,
|
||||
AccountId,
|
||||
>(
|
||||
sp_std::marker::PhantomData<(F, A, AccountId)>
|
||||
);
|
||||
>(sp_std::marker::PhantomData<(F, A, AccountId)>);
|
||||
|
||||
impl<
|
||||
F: fungibles::Inspect<AccountId>,
|
||||
A: Get<<F as fungibles::Inspect<AccountId>>::AssetId>,
|
||||
AccountId,
|
||||
> Inspect<AccountId> for ItemOf<F, A, AccountId> {
|
||||
F: fungibles::Inspect<AccountId>,
|
||||
A: Get<<F as fungibles::Inspect<AccountId>>::AssetId>,
|
||||
AccountId,
|
||||
> Inspect<AccountId> for ItemOf<F, A, AccountId>
|
||||
{
|
||||
type Balance = <F as fungibles::Inspect<AccountId>>::Balance;
|
||||
fn total_issuance() -> Self::Balance {
|
||||
<F as fungibles::Inspect<AccountId>>::total_issuance(A::get())
|
||||
@@ -216,10 +225,11 @@ impl<
|
||||
}
|
||||
|
||||
impl<
|
||||
F: fungibles::Mutate<AccountId>,
|
||||
A: Get<<F as fungibles::Inspect<AccountId>>::AssetId>,
|
||||
AccountId,
|
||||
> Mutate<AccountId> for ItemOf<F, A, AccountId> {
|
||||
F: fungibles::Mutate<AccountId>,
|
||||
A: Get<<F as fungibles::Inspect<AccountId>>::AssetId>,
|
||||
AccountId,
|
||||
> Mutate<AccountId> for ItemOf<F, A, AccountId>
|
||||
{
|
||||
fn mint_into(who: &AccountId, amount: Self::Balance) -> DispatchResult {
|
||||
<F as fungibles::Mutate<AccountId>>::mint_into(A::get(), who, amount)
|
||||
}
|
||||
@@ -229,22 +239,27 @@ impl<
|
||||
}
|
||||
|
||||
impl<
|
||||
F: fungibles::Transfer<AccountId>,
|
||||
A: Get<<F as fungibles::Inspect<AccountId>>::AssetId>,
|
||||
AccountId,
|
||||
> Transfer<AccountId> for ItemOf<F, A, AccountId> {
|
||||
fn transfer(source: &AccountId, dest: &AccountId, amount: Self::Balance, keep_alive: bool)
|
||||
-> Result<Self::Balance, DispatchError>
|
||||
{
|
||||
F: fungibles::Transfer<AccountId>,
|
||||
A: Get<<F as fungibles::Inspect<AccountId>>::AssetId>,
|
||||
AccountId,
|
||||
> Transfer<AccountId> for ItemOf<F, A, AccountId>
|
||||
{
|
||||
fn transfer(
|
||||
source: &AccountId,
|
||||
dest: &AccountId,
|
||||
amount: Self::Balance,
|
||||
keep_alive: bool,
|
||||
) -> Result<Self::Balance, DispatchError> {
|
||||
<F as fungibles::Transfer<AccountId>>::transfer(A::get(), source, dest, amount, keep_alive)
|
||||
}
|
||||
}
|
||||
|
||||
impl<
|
||||
F: fungibles::InspectHold<AccountId>,
|
||||
A: Get<<F as fungibles::Inspect<AccountId>>::AssetId>,
|
||||
AccountId,
|
||||
> InspectHold<AccountId> for ItemOf<F, A, AccountId> {
|
||||
F: fungibles::InspectHold<AccountId>,
|
||||
A: Get<<F as fungibles::Inspect<AccountId>>::AssetId>,
|
||||
AccountId,
|
||||
> InspectHold<AccountId> for ItemOf<F, A, AccountId>
|
||||
{
|
||||
fn balance_on_hold(who: &AccountId) -> Self::Balance {
|
||||
<F as fungibles::InspectHold<AccountId>>::balance_on_hold(A::get(), who)
|
||||
}
|
||||
@@ -254,16 +269,19 @@ impl<
|
||||
}
|
||||
|
||||
impl<
|
||||
F: fungibles::MutateHold<AccountId>,
|
||||
A: Get<<F as fungibles::Inspect<AccountId>>::AssetId>,
|
||||
AccountId,
|
||||
> MutateHold<AccountId> for ItemOf<F, A, AccountId> {
|
||||
F: fungibles::MutateHold<AccountId>,
|
||||
A: Get<<F as fungibles::Inspect<AccountId>>::AssetId>,
|
||||
AccountId,
|
||||
> MutateHold<AccountId> for ItemOf<F, A, AccountId>
|
||||
{
|
||||
fn hold(who: &AccountId, amount: Self::Balance) -> DispatchResult {
|
||||
<F as fungibles::MutateHold<AccountId>>::hold(A::get(), who, amount)
|
||||
}
|
||||
fn release(who: &AccountId, amount: Self::Balance, best_effort: bool)
|
||||
-> Result<Self::Balance, DispatchError>
|
||||
{
|
||||
fn release(
|
||||
who: &AccountId,
|
||||
amount: Self::Balance,
|
||||
best_effort: bool,
|
||||
) -> Result<Self::Balance, DispatchError> {
|
||||
<F as fungibles::MutateHold<AccountId>>::release(A::get(), who, amount, best_effort)
|
||||
}
|
||||
fn transfer_held(
|
||||
@@ -285,23 +303,30 @@ impl<
|
||||
}
|
||||
|
||||
impl<
|
||||
F: fungibles::Unbalanced<AccountId>,
|
||||
A: Get<<F as fungibles::Inspect<AccountId>>::AssetId>,
|
||||
AccountId,
|
||||
> Unbalanced<AccountId> for ItemOf<F, A, AccountId> {
|
||||
F: fungibles::Unbalanced<AccountId>,
|
||||
A: Get<<F as fungibles::Inspect<AccountId>>::AssetId>,
|
||||
AccountId,
|
||||
> Unbalanced<AccountId> for ItemOf<F, A, AccountId>
|
||||
{
|
||||
fn set_balance(who: &AccountId, amount: Self::Balance) -> DispatchResult {
|
||||
<F as fungibles::Unbalanced<AccountId>>::set_balance(A::get(), who, amount)
|
||||
}
|
||||
fn set_total_issuance(amount: Self::Balance) -> () {
|
||||
<F as fungibles::Unbalanced<AccountId>>::set_total_issuance(A::get(), amount)
|
||||
}
|
||||
fn decrease_balance(who: &AccountId, amount: Self::Balance) -> Result<Self::Balance, DispatchError> {
|
||||
fn decrease_balance(
|
||||
who: &AccountId,
|
||||
amount: Self::Balance,
|
||||
) -> Result<Self::Balance, DispatchError> {
|
||||
<F as fungibles::Unbalanced<AccountId>>::decrease_balance(A::get(), who, amount)
|
||||
}
|
||||
fn decrease_balance_at_most(who: &AccountId, amount: Self::Balance) -> Self::Balance {
|
||||
<F as fungibles::Unbalanced<AccountId>>::decrease_balance_at_most(A::get(), who, amount)
|
||||
}
|
||||
fn increase_balance(who: &AccountId, amount: Self::Balance) -> Result<Self::Balance, DispatchError> {
|
||||
fn increase_balance(
|
||||
who: &AccountId,
|
||||
amount: Self::Balance,
|
||||
) -> Result<Self::Balance, DispatchError> {
|
||||
<F as fungibles::Unbalanced<AccountId>>::increase_balance(A::get(), who, amount)
|
||||
}
|
||||
fn increase_balance_at_most(who: &AccountId, amount: Self::Balance) -> Self::Balance {
|
||||
|
||||
@@ -18,12 +18,16 @@
|
||||
//! The trait and associated types for sets of fungible tokens that manage total issuance without
|
||||
//! requiring atomic balanced operations.
|
||||
|
||||
use super::*;
|
||||
use super::{super::Imbalance as ImbalanceT, *};
|
||||
use crate::{
|
||||
dispatch::{DispatchError, DispatchResult},
|
||||
traits::misc::{SameOrOther, TryDrop},
|
||||
};
|
||||
use sp_runtime::{
|
||||
traits::{CheckedAdd, Zero},
|
||||
ArithmeticError, TokenError,
|
||||
};
|
||||
use sp_std::marker::PhantomData;
|
||||
use sp_runtime::{TokenError, ArithmeticError, traits::{CheckedAdd, Zero}};
|
||||
use super::super::Imbalance as ImbalanceT;
|
||||
use crate::traits::misc::{SameOrOther, TryDrop};
|
||||
use crate::dispatch::{DispatchResult, DispatchError};
|
||||
|
||||
/// A fungible token class where any creation and deletion of tokens is semi-explicit and where the
|
||||
/// total supply is maintained automatically.
|
||||
@@ -65,10 +69,7 @@ pub trait Balanced<AccountId>: Inspect<AccountId> {
|
||||
///
|
||||
/// As much funds up to `value` will be deducted as possible. If this is less than `value`,
|
||||
/// then a non-zero second item will be returned.
|
||||
fn slash(
|
||||
who: &AccountId,
|
||||
amount: Self::Balance,
|
||||
) -> (CreditOf<AccountId, Self>, Self::Balance);
|
||||
fn slash(who: &AccountId, amount: Self::Balance) -> (CreditOf<AccountId, Self>, Self::Balance);
|
||||
|
||||
/// Mints exactly `value` into the account of `who`.
|
||||
///
|
||||
@@ -90,7 +91,7 @@ pub trait Balanced<AccountId>: Inspect<AccountId> {
|
||||
fn withdraw(
|
||||
who: &AccountId,
|
||||
value: Self::Balance,
|
||||
//TODO: liveness: ExistenceRequirement,
|
||||
// TODO: liveness: ExistenceRequirement,
|
||||
) -> Result<CreditOf<AccountId, Self>, DispatchError>;
|
||||
|
||||
/// The balance of `who` is increased in order to counter `credit`. If the whole of `credit`
|
||||
@@ -119,7 +120,7 @@ pub trait Balanced<AccountId>: Inspect<AccountId> {
|
||||
fn settle(
|
||||
who: &AccountId,
|
||||
debt: DebtOf<AccountId, Self>,
|
||||
//TODO: liveness: ExistenceRequirement,
|
||||
// TODO: liveness: ExistenceRequirement,
|
||||
) -> Result<CreditOf<AccountId, Self>, DebtOf<AccountId, Self>> {
|
||||
let amount = debt.peek();
|
||||
let credit = match Self::withdraw(who, amount) {
|
||||
@@ -132,7 +133,7 @@ pub trait Balanced<AccountId>: Inspect<AccountId> {
|
||||
SameOrOther::Other(rest) => {
|
||||
debug_assert!(false, "ok withdraw return must be at least debt value; qed");
|
||||
Err(rest)
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -158,9 +159,10 @@ pub trait Unbalanced<AccountId>: Inspect<AccountId> {
|
||||
///
|
||||
/// Minimum balance will be respected and the returned imbalance may be up to
|
||||
/// `Self::minimum_balance() - 1` greater than `amount`.
|
||||
fn decrease_balance(who: &AccountId, amount: Self::Balance)
|
||||
-> Result<Self::Balance, DispatchError>
|
||||
{
|
||||
fn decrease_balance(
|
||||
who: &AccountId,
|
||||
amount: Self::Balance,
|
||||
) -> Result<Self::Balance, DispatchError> {
|
||||
let old_balance = Self::balance(who);
|
||||
let (mut new_balance, mut amount) = if old_balance < amount {
|
||||
Err(TokenError::NoFunds)?
|
||||
@@ -182,9 +184,7 @@ pub trait Unbalanced<AccountId>: Inspect<AccountId> {
|
||||
/// `Self::minimum_balance() - 1` greater than `amount`.
|
||||
///
|
||||
/// Return the imbalance by which the account was reduced.
|
||||
fn decrease_balance_at_most(who: &AccountId, amount: Self::Balance)
|
||||
-> Self::Balance
|
||||
{
|
||||
fn decrease_balance_at_most(who: &AccountId, amount: Self::Balance) -> Self::Balance {
|
||||
let old_balance = Self::balance(who);
|
||||
let (mut new_balance, mut amount) = if old_balance < amount {
|
||||
(Zero::zero(), old_balance)
|
||||
@@ -217,9 +217,10 @@ pub trait Unbalanced<AccountId>: Inspect<AccountId> {
|
||||
///
|
||||
/// Minimum balance will be respected and an error will be returned if
|
||||
/// `amount < Self::minimum_balance()` when the account of `who` is zero.
|
||||
fn increase_balance(who: &AccountId, amount: Self::Balance)
|
||||
-> Result<Self::Balance, DispatchError>
|
||||
{
|
||||
fn increase_balance(
|
||||
who: &AccountId,
|
||||
amount: Self::Balance,
|
||||
) -> Result<Self::Balance, DispatchError> {
|
||||
let old_balance = Self::balance(who);
|
||||
let new_balance = old_balance.checked_add(&amount).ok_or(ArithmeticError::Overflow)?;
|
||||
if new_balance < Self::minimum_balance() {
|
||||
@@ -237,9 +238,7 @@ pub trait Unbalanced<AccountId>: Inspect<AccountId> {
|
||||
/// `amount < Self::minimum_balance()`.
|
||||
///
|
||||
/// Return the imbalance by which the account was increased.
|
||||
fn increase_balance_at_most(who: &AccountId, amount: Self::Balance)
|
||||
-> Self::Balance
|
||||
{
|
||||
fn increase_balance_at_most(who: &AccountId, amount: Self::Balance) -> Self::Balance {
|
||||
let old_balance = Self::balance(who);
|
||||
let mut new_balance = old_balance.saturating_add(amount);
|
||||
let mut amount = new_balance - old_balance;
|
||||
@@ -300,16 +299,12 @@ type Debt<AccountId, U> = Imbalance<
|
||||
>;
|
||||
|
||||
/// Create some `Credit` item. Only for internal use.
|
||||
fn credit<AccountId, U: Unbalanced<AccountId>>(
|
||||
amount: U::Balance,
|
||||
) -> Credit<AccountId, U> {
|
||||
fn credit<AccountId, U: Unbalanced<AccountId>>(amount: U::Balance) -> Credit<AccountId, U> {
|
||||
Imbalance::new(amount)
|
||||
}
|
||||
|
||||
/// Create some `Debt` item. Only for internal use.
|
||||
fn debt<AccountId, U: Unbalanced<AccountId>>(
|
||||
amount: U::Balance,
|
||||
) -> Debt<AccountId, U> {
|
||||
fn debt<AccountId, U: Unbalanced<AccountId>>(amount: U::Balance) -> Debt<AccountId, U> {
|
||||
Imbalance::new(amount)
|
||||
}
|
||||
|
||||
@@ -328,10 +323,7 @@ impl<AccountId, U: Unbalanced<AccountId>> Balanced<AccountId> for U {
|
||||
U::set_total_issuance(new);
|
||||
credit(new - old)
|
||||
}
|
||||
fn slash(
|
||||
who: &AccountId,
|
||||
amount: Self::Balance,
|
||||
) -> (Credit<AccountId, Self>, Self::Balance) {
|
||||
fn slash(who: &AccountId, amount: Self::Balance) -> (Credit<AccountId, Self>, Self::Balance) {
|
||||
let slashed = U::decrease_balance_at_most(who, amount);
|
||||
// `slashed` could be less than, greater than or equal to `amount`.
|
||||
// If slashed == amount, it means the account had at least amount in it and it could all be
|
||||
@@ -344,7 +336,7 @@ impl<AccountId, U: Unbalanced<AccountId>> Balanced<AccountId> for U {
|
||||
}
|
||||
fn deposit(
|
||||
who: &AccountId,
|
||||
amount: Self::Balance
|
||||
amount: Self::Balance,
|
||||
) -> Result<Debt<AccountId, Self>, DispatchError> {
|
||||
let increase = U::increase_balance(who, amount)?;
|
||||
Ok(debt(increase))
|
||||
@@ -352,7 +344,7 @@ impl<AccountId, U: Unbalanced<AccountId>> Balanced<AccountId> for U {
|
||||
fn withdraw(
|
||||
who: &AccountId,
|
||||
amount: Self::Balance,
|
||||
//TODO: liveness: ExistenceRequirement,
|
||||
// TODO: liveness: ExistenceRequirement,
|
||||
) -> Result<Credit<AccountId, Self>, DispatchError> {
|
||||
let decrease = U::decrease_balance(who, amount)?;
|
||||
Ok(credit(decrease))
|
||||
|
||||
@@ -18,13 +18,10 @@
|
||||
//! The imbalance type and its associates, which handles keeps everything adding up properly with
|
||||
//! unbalanced operations.
|
||||
|
||||
use super::*;
|
||||
use super::{super::Imbalance as ImbalanceT, balanced::Balanced, misc::Balance, *};
|
||||
use crate::traits::misc::{SameOrOther, TryDrop};
|
||||
use sp_runtime::{traits::Zero, RuntimeDebug};
|
||||
use sp_std::marker::PhantomData;
|
||||
use sp_runtime::{RuntimeDebug, traits::Zero};
|
||||
use super::misc::Balance;
|
||||
use super::balanced::Balanced;
|
||||
use crate::traits::misc::{TryDrop, SameOrOther};
|
||||
use super::super::Imbalance as ImbalanceT;
|
||||
|
||||
/// Handler for when an imbalance gets dropped. This could handle either a credit (negative) or
|
||||
/// debt (positive) imbalance.
|
||||
@@ -49,11 +46,9 @@ pub struct Imbalance<
|
||||
_phantom: PhantomData<(OnDrop, OppositeOnDrop)>,
|
||||
}
|
||||
|
||||
impl<
|
||||
B: Balance,
|
||||
OnDrop: HandleImbalanceDrop<B>,
|
||||
OppositeOnDrop: HandleImbalanceDrop<B>
|
||||
> Drop for Imbalance<B, OnDrop, OppositeOnDrop> {
|
||||
impl<B: Balance, OnDrop: HandleImbalanceDrop<B>, OppositeOnDrop: HandleImbalanceDrop<B>> Drop
|
||||
for Imbalance<B, OnDrop, OppositeOnDrop>
|
||||
{
|
||||
fn drop(&mut self) {
|
||||
if !self.amount.is_zero() {
|
||||
OnDrop::handle(self.amount)
|
||||
@@ -61,42 +56,34 @@ impl<
|
||||
}
|
||||
}
|
||||
|
||||
impl<
|
||||
B: Balance,
|
||||
OnDrop: HandleImbalanceDrop<B>,
|
||||
OppositeOnDrop: HandleImbalanceDrop<B>,
|
||||
> TryDrop for Imbalance<B, OnDrop, OppositeOnDrop> {
|
||||
impl<B: Balance, OnDrop: HandleImbalanceDrop<B>, OppositeOnDrop: HandleImbalanceDrop<B>> TryDrop
|
||||
for Imbalance<B, OnDrop, OppositeOnDrop>
|
||||
{
|
||||
/// Drop an instance cleanly. Only works if its value represents "no-operation".
|
||||
fn try_drop(self) -> Result<(), Self> {
|
||||
self.drop_zero()
|
||||
}
|
||||
}
|
||||
|
||||
impl<
|
||||
B: Balance,
|
||||
OnDrop: HandleImbalanceDrop<B>,
|
||||
OppositeOnDrop: HandleImbalanceDrop<B>,
|
||||
> Default for Imbalance<B, OnDrop, OppositeOnDrop> {
|
||||
impl<B: Balance, OnDrop: HandleImbalanceDrop<B>, OppositeOnDrop: HandleImbalanceDrop<B>> Default
|
||||
for Imbalance<B, OnDrop, OppositeOnDrop>
|
||||
{
|
||||
fn default() -> Self {
|
||||
Self::zero()
|
||||
}
|
||||
}
|
||||
|
||||
impl<
|
||||
B: Balance,
|
||||
OnDrop: HandleImbalanceDrop<B>,
|
||||
OppositeOnDrop: HandleImbalanceDrop<B>,
|
||||
> Imbalance<B, OnDrop, OppositeOnDrop> {
|
||||
impl<B: Balance, OnDrop: HandleImbalanceDrop<B>, OppositeOnDrop: HandleImbalanceDrop<B>>
|
||||
Imbalance<B, OnDrop, OppositeOnDrop>
|
||||
{
|
||||
pub(crate) fn new(amount: B) -> Self {
|
||||
Self { amount, _phantom: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
impl<
|
||||
B: Balance,
|
||||
OnDrop: HandleImbalanceDrop<B>,
|
||||
OppositeOnDrop: HandleImbalanceDrop<B>,
|
||||
> ImbalanceT<B> for Imbalance<B, OnDrop, OppositeOnDrop> {
|
||||
impl<B: Balance, OnDrop: HandleImbalanceDrop<B>, OppositeOnDrop: HandleImbalanceDrop<B>>
|
||||
ImbalanceT<B> for Imbalance<B, OnDrop, OppositeOnDrop>
|
||||
{
|
||||
type Opposite = Imbalance<B, OppositeOnDrop, OnDrop>;
|
||||
|
||||
fn zero() -> Self {
|
||||
@@ -127,9 +114,10 @@ impl<
|
||||
self.amount = self.amount.saturating_add(other.amount);
|
||||
sp_std::mem::forget(other);
|
||||
}
|
||||
fn offset(self, other: Imbalance<B, OppositeOnDrop, OnDrop>)
|
||||
-> SameOrOther<Self, Imbalance<B, OppositeOnDrop, OnDrop>>
|
||||
{
|
||||
fn offset(
|
||||
self,
|
||||
other: Imbalance<B, OppositeOnDrop, OnDrop>,
|
||||
) -> SameOrOther<Self, Imbalance<B, OppositeOnDrop, OnDrop>> {
|
||||
let (a, b) = (self.amount, other.amount);
|
||||
sp_std::mem::forget((self, other));
|
||||
|
||||
|
||||
@@ -17,15 +17,17 @@
|
||||
|
||||
//! The traits for sets of fungible tokens and any associated types.
|
||||
|
||||
use super::*;
|
||||
use super::{
|
||||
misc::{AssetId, Balance},
|
||||
*,
|
||||
};
|
||||
use crate::dispatch::{DispatchError, DispatchResult};
|
||||
use super::misc::{AssetId, Balance};
|
||||
use sp_runtime::traits::Saturating;
|
||||
|
||||
mod balanced;
|
||||
pub use balanced::{Balanced, Unbalanced};
|
||||
mod imbalance;
|
||||
pub use imbalance::{Imbalance, HandleImbalanceDrop, DebtOf, CreditOf};
|
||||
pub use imbalance::{CreditOf, DebtOf, HandleImbalanceDrop, Imbalance};
|
||||
|
||||
/// Trait for providing balance-inspection access to a set of named fungible assets.
|
||||
pub trait Inspect<AccountId> {
|
||||
@@ -48,8 +50,11 @@ pub trait Inspect<AccountId> {
|
||||
fn reducible_balance(asset: Self::AssetId, who: &AccountId, keep_alive: bool) -> Self::Balance;
|
||||
|
||||
/// Returns `true` if the `asset` balance of `who` may be increased by `amount`.
|
||||
fn can_deposit(asset: Self::AssetId, who: &AccountId, amount: Self::Balance)
|
||||
-> DepositConsequence;
|
||||
fn can_deposit(
|
||||
asset: Self::AssetId,
|
||||
who: &AccountId,
|
||||
amount: Self::Balance,
|
||||
) -> DepositConsequence;
|
||||
|
||||
/// Returns `Failed` if the `asset` balance of `who` may not be decreased by `amount`, otherwise
|
||||
/// the consequence.
|
||||
@@ -87,8 +92,11 @@ pub trait Mutate<AccountId>: Inspect<AccountId> {
|
||||
/// Due to minimum balance requirements, it's possible that the amount withdrawn could be up to
|
||||
/// `Self::minimum_balance() - 1` more than the `amount`. The total amount withdrawn is returned
|
||||
/// in an `Ok` result. This may be safely ignored if you don't mind the overall supply reducing.
|
||||
fn burn_from(asset: Self::AssetId, who: &AccountId, amount: Self::Balance)
|
||||
-> Result<Self::Balance, DispatchError>;
|
||||
fn burn_from(
|
||||
asset: Self::AssetId,
|
||||
who: &AccountId,
|
||||
amount: Self::Balance,
|
||||
) -> Result<Self::Balance, DispatchError>;
|
||||
|
||||
/// Attempt to reduce the `asset` balance of `who` by as much as possible up to `amount`, and
|
||||
/// possibly slightly more due to minimum_balance requirements. If no decrease is possible then
|
||||
@@ -97,9 +105,11 @@ pub trait Mutate<AccountId>: Inspect<AccountId> {
|
||||
///
|
||||
/// The default implementation just uses `withdraw` along with `reducible_balance` to ensure
|
||||
/// that is doesn't fail.
|
||||
fn slash(asset: Self::AssetId, who: &AccountId, amount: Self::Balance)
|
||||
-> Result<Self::Balance, DispatchError>
|
||||
{
|
||||
fn slash(
|
||||
asset: Self::AssetId,
|
||||
who: &AccountId,
|
||||
amount: Self::Balance,
|
||||
) -> Result<Self::Balance, DispatchError> {
|
||||
Self::burn_from(asset, who, Self::reducible_balance(asset, who, false).min(amount))
|
||||
}
|
||||
|
||||
@@ -114,7 +124,10 @@ pub trait Mutate<AccountId>: Inspect<AccountId> {
|
||||
let extra = Self::can_withdraw(asset, &source, amount).into_result()?;
|
||||
Self::can_deposit(asset, &dest, amount.saturating_add(extra)).into_result()?;
|
||||
let actual = Self::burn_from(asset, source, amount)?;
|
||||
debug_assert!(actual == amount.saturating_add(extra), "can_withdraw must agree with withdraw; qed");
|
||||
debug_assert!(
|
||||
actual == amount.saturating_add(extra),
|
||||
"can_withdraw must agree with withdraw; qed"
|
||||
);
|
||||
match Self::mint_into(asset, dest, actual) {
|
||||
Ok(_) => Ok(actual),
|
||||
Err(err) => {
|
||||
@@ -123,7 +136,7 @@ pub trait Mutate<AccountId>: Inspect<AccountId> {
|
||||
let revert = Self::mint_into(asset, source, actual);
|
||||
debug_assert!(revert.is_ok(), "withdrew funds previously; qed");
|
||||
Err(err)
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -158,8 +171,12 @@ pub trait MutateHold<AccountId>: InspectHold<AccountId> + Transfer<AccountId> {
|
||||
///
|
||||
/// If `best_effort` is `true`, then the amount actually released and returned as the inner
|
||||
/// value of `Ok` may be smaller than the `amount` passed.
|
||||
fn release(asset: Self::AssetId, who: &AccountId, amount: Self::Balance, best_effort: bool)
|
||||
-> Result<Self::Balance, DispatchError>;
|
||||
fn release(
|
||||
asset: Self::AssetId,
|
||||
who: &AccountId,
|
||||
amount: Self::Balance,
|
||||
best_effort: bool,
|
||||
) -> Result<Self::Balance, DispatchError>;
|
||||
|
||||
/// Transfer held funds into a destination account.
|
||||
///
|
||||
@@ -190,17 +207,19 @@ pub trait BalancedHold<AccountId>: Balanced<AccountId> + MutateHold<AccountId> {
|
||||
///
|
||||
/// As much funds up to `amount` will be deducted as possible. If this is less than `amount`,
|
||||
/// then a non-zero second item will be returned.
|
||||
fn slash_held(asset: Self::AssetId, who: &AccountId, amount: Self::Balance)
|
||||
-> (CreditOf<AccountId, Self>, Self::Balance);
|
||||
fn slash_held(
|
||||
asset: Self::AssetId,
|
||||
who: &AccountId,
|
||||
amount: Self::Balance,
|
||||
) -> (CreditOf<AccountId, Self>, Self::Balance);
|
||||
}
|
||||
|
||||
impl<
|
||||
AccountId,
|
||||
T: Balanced<AccountId> + MutateHold<AccountId>,
|
||||
> BalancedHold<AccountId> for T {
|
||||
fn slash_held(asset: Self::AssetId, who: &AccountId, amount: Self::Balance)
|
||||
-> (CreditOf<AccountId, Self>, Self::Balance)
|
||||
{
|
||||
impl<AccountId, T: Balanced<AccountId> + MutateHold<AccountId>> BalancedHold<AccountId> for T {
|
||||
fn slash_held(
|
||||
asset: Self::AssetId,
|
||||
who: &AccountId,
|
||||
amount: Self::Balance,
|
||||
) -> (CreditOf<AccountId, Self>, Self::Balance) {
|
||||
let actual = match Self::release(asset, who, amount, true) {
|
||||
Ok(x) => x,
|
||||
Err(_) => return (Imbalance::zero(asset), amount),
|
||||
|
||||
@@ -19,11 +19,16 @@
|
||||
//! requiring atomic balanced operations.
|
||||
|
||||
use super::*;
|
||||
use sp_std::marker::PhantomData;
|
||||
use sp_runtime::{ArithmeticError, TokenError, traits::{Zero, CheckedAdd}};
|
||||
use crate::{
|
||||
dispatch::{DispatchError, DispatchResult},
|
||||
traits::misc::{SameOrOther, TryDrop},
|
||||
};
|
||||
use sp_arithmetic::traits::Saturating;
|
||||
use crate::dispatch::{DispatchError, DispatchResult};
|
||||
use crate::traits::misc::{SameOrOther, TryDrop};
|
||||
use sp_runtime::{
|
||||
traits::{CheckedAdd, Zero},
|
||||
ArithmeticError, TokenError,
|
||||
};
|
||||
use sp_std::marker::PhantomData;
|
||||
|
||||
/// A fungible token class where any creation and deletion of tokens is semi-explicit and where the
|
||||
/// total supply is maintained automatically.
|
||||
@@ -55,9 +60,10 @@ pub trait Balanced<AccountId>: Inspect<AccountId> {
|
||||
///
|
||||
/// This is just the same as burning and issuing the same amount and has no effect on the
|
||||
/// total issuance.
|
||||
fn pair(asset: Self::AssetId, amount: Self::Balance)
|
||||
-> (DebtOf<AccountId, Self>, CreditOf<AccountId, Self>)
|
||||
{
|
||||
fn pair(
|
||||
asset: Self::AssetId,
|
||||
amount: Self::Balance,
|
||||
) -> (DebtOf<AccountId, Self>, CreditOf<AccountId, Self>) {
|
||||
(Self::rescind(asset, amount), Self::issue(asset, amount))
|
||||
}
|
||||
|
||||
@@ -96,7 +102,7 @@ pub trait Balanced<AccountId>: Inspect<AccountId> {
|
||||
asset: Self::AssetId,
|
||||
who: &AccountId,
|
||||
value: Self::Balance,
|
||||
//TODO: liveness: ExistenceRequirement,
|
||||
// TODO: liveness: ExistenceRequirement,
|
||||
) -> Result<CreditOf<AccountId, Self>, DispatchError>;
|
||||
|
||||
/// The balance of `who` is increased in order to counter `credit`. If the whole of `credit`
|
||||
@@ -129,7 +135,7 @@ pub trait Balanced<AccountId>: Inspect<AccountId> {
|
||||
fn settle(
|
||||
who: &AccountId,
|
||||
debt: DebtOf<AccountId, Self>,
|
||||
//TODO: liveness: ExistenceRequirement,
|
||||
// TODO: liveness: ExistenceRequirement,
|
||||
) -> Result<CreditOf<AccountId, Self>, DebtOf<AccountId, Self>> {
|
||||
let amount = debt.peek();
|
||||
let asset = debt.asset();
|
||||
@@ -143,11 +149,11 @@ pub trait Balanced<AccountId>: Inspect<AccountId> {
|
||||
Ok(SameOrOther::Other(rest)) => {
|
||||
debug_assert!(false, "ok withdraw return must be at least debt value; qed");
|
||||
Err(rest)
|
||||
}
|
||||
},
|
||||
Err(_) => {
|
||||
debug_assert!(false, "debt.asset is credit.asset; qed");
|
||||
Ok(CreditOf::<AccountId, Self>::zero(asset))
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -173,9 +179,11 @@ pub trait Unbalanced<AccountId>: Inspect<AccountId> {
|
||||
///
|
||||
/// Minimum balance will be respected and the returned imbalance may be up to
|
||||
/// `Self::minimum_balance() - 1` greater than `amount`.
|
||||
fn decrease_balance(asset: Self::AssetId, who: &AccountId, amount: Self::Balance)
|
||||
-> Result<Self::Balance, DispatchError>
|
||||
{
|
||||
fn decrease_balance(
|
||||
asset: Self::AssetId,
|
||||
who: &AccountId,
|
||||
amount: Self::Balance,
|
||||
) -> Result<Self::Balance, DispatchError> {
|
||||
let old_balance = Self::balance(asset, who);
|
||||
let (mut new_balance, mut amount) = if old_balance < amount {
|
||||
Err(TokenError::NoFunds)?
|
||||
@@ -197,9 +205,11 @@ pub trait Unbalanced<AccountId>: Inspect<AccountId> {
|
||||
/// `Self::minimum_balance() - 1` greater than `amount`.
|
||||
///
|
||||
/// Return the imbalance by which the account was reduced.
|
||||
fn decrease_balance_at_most(asset: Self::AssetId, who: &AccountId, amount: Self::Balance)
|
||||
-> Self::Balance
|
||||
{
|
||||
fn decrease_balance_at_most(
|
||||
asset: Self::AssetId,
|
||||
who: &AccountId,
|
||||
amount: Self::Balance,
|
||||
) -> Self::Balance {
|
||||
let old_balance = Self::balance(asset, who);
|
||||
let (mut new_balance, mut amount) = if old_balance < amount {
|
||||
(Zero::zero(), old_balance)
|
||||
@@ -232,9 +242,11 @@ pub trait Unbalanced<AccountId>: Inspect<AccountId> {
|
||||
///
|
||||
/// Minimum balance will be respected and an error will be returned if
|
||||
/// `amount < Self::minimum_balance()` when the account of `who` is zero.
|
||||
fn increase_balance(asset: Self::AssetId, who: &AccountId, amount: Self::Balance)
|
||||
-> Result<Self::Balance, DispatchError>
|
||||
{
|
||||
fn increase_balance(
|
||||
asset: Self::AssetId,
|
||||
who: &AccountId,
|
||||
amount: Self::Balance,
|
||||
) -> Result<Self::Balance, DispatchError> {
|
||||
let old_balance = Self::balance(asset, who);
|
||||
let new_balance = old_balance.checked_add(&amount).ok_or(ArithmeticError::Overflow)?;
|
||||
if new_balance < Self::minimum_balance(asset) {
|
||||
@@ -252,9 +264,11 @@ pub trait Unbalanced<AccountId>: Inspect<AccountId> {
|
||||
/// `amount < Self::minimum_balance()`.
|
||||
///
|
||||
/// Return the imbalance by which the account was increased.
|
||||
fn increase_balance_at_most(asset: Self::AssetId, who: &AccountId, amount: Self::Balance)
|
||||
-> Self::Balance
|
||||
{
|
||||
fn increase_balance_at_most(
|
||||
asset: Self::AssetId,
|
||||
who: &AccountId,
|
||||
amount: Self::Balance,
|
||||
) -> Self::Balance {
|
||||
let old_balance = Self::balance(asset, who);
|
||||
let mut new_balance = old_balance.saturating_add(amount);
|
||||
let mut amount = new_balance - old_balance;
|
||||
@@ -361,7 +375,7 @@ impl<AccountId, U: Unbalanced<AccountId>> Balanced<AccountId> for U {
|
||||
fn deposit(
|
||||
asset: Self::AssetId,
|
||||
who: &AccountId,
|
||||
amount: Self::Balance
|
||||
amount: Self::Balance,
|
||||
) -> Result<Debt<AccountId, Self>, DispatchError> {
|
||||
let increase = U::increase_balance(asset, who, amount)?;
|
||||
Ok(debt(asset, increase))
|
||||
@@ -370,7 +384,7 @@ impl<AccountId, U: Unbalanced<AccountId>> Balanced<AccountId> for U {
|
||||
asset: Self::AssetId,
|
||||
who: &AccountId,
|
||||
amount: Self::Balance,
|
||||
//TODO: liveness: ExistenceRequirement,
|
||||
// TODO: liveness: ExistenceRequirement,
|
||||
) -> Result<Credit<AccountId, Self>, DispatchError> {
|
||||
let decrease = U::decrease_balance(asset, who, amount)?;
|
||||
Ok(credit(asset, decrease))
|
||||
|
||||
@@ -18,12 +18,14 @@
|
||||
//! The imbalance type and its associates, which handles keeps everything adding up properly with
|
||||
//! unbalanced operations.
|
||||
|
||||
use super::*;
|
||||
use super::{
|
||||
balanced::Balanced,
|
||||
fungibles::{AssetId, Balance},
|
||||
*,
|
||||
};
|
||||
use crate::traits::misc::{SameOrOther, TryDrop};
|
||||
use sp_runtime::{traits::Zero, RuntimeDebug};
|
||||
use sp_std::marker::PhantomData;
|
||||
use sp_runtime::{RuntimeDebug, traits::Zero};
|
||||
use super::fungibles::{AssetId, Balance};
|
||||
use super::balanced::Balanced;
|
||||
use crate::traits::misc::{TryDrop, SameOrOther};
|
||||
|
||||
/// Handler for when an imbalance gets dropped. This could handle either a credit (negative) or
|
||||
/// debt (positive) imbalance.
|
||||
@@ -50,11 +52,12 @@ pub struct Imbalance<
|
||||
}
|
||||
|
||||
impl<
|
||||
A: AssetId,
|
||||
B: Balance,
|
||||
OnDrop: HandleImbalanceDrop<A, B>,
|
||||
OppositeOnDrop: HandleImbalanceDrop<A, B>
|
||||
> Drop for Imbalance<A, B, OnDrop, OppositeOnDrop> {
|
||||
A: AssetId,
|
||||
B: Balance,
|
||||
OnDrop: HandleImbalanceDrop<A, B>,
|
||||
OppositeOnDrop: HandleImbalanceDrop<A, B>,
|
||||
> Drop for Imbalance<A, B, OnDrop, OppositeOnDrop>
|
||||
{
|
||||
fn drop(&mut self) {
|
||||
if !self.amount.is_zero() {
|
||||
OnDrop::handle(self.asset, self.amount)
|
||||
@@ -63,11 +66,12 @@ impl<
|
||||
}
|
||||
|
||||
impl<
|
||||
A: AssetId,
|
||||
B: Balance,
|
||||
OnDrop: HandleImbalanceDrop<A, B>,
|
||||
OppositeOnDrop: HandleImbalanceDrop<A, B>,
|
||||
> TryDrop for Imbalance<A, B, OnDrop, OppositeOnDrop> {
|
||||
A: AssetId,
|
||||
B: Balance,
|
||||
OnDrop: HandleImbalanceDrop<A, B>,
|
||||
OppositeOnDrop: HandleImbalanceDrop<A, B>,
|
||||
> TryDrop for Imbalance<A, B, OnDrop, OppositeOnDrop>
|
||||
{
|
||||
/// Drop an instance cleanly. Only works if its value represents "no-operation".
|
||||
fn try_drop(self) -> Result<(), Self> {
|
||||
self.drop_zero()
|
||||
@@ -75,11 +79,12 @@ impl<
|
||||
}
|
||||
|
||||
impl<
|
||||
A: AssetId,
|
||||
B: Balance,
|
||||
OnDrop: HandleImbalanceDrop<A, B>,
|
||||
OppositeOnDrop: HandleImbalanceDrop<A, B>,
|
||||
> Imbalance<A, B, OnDrop, OppositeOnDrop> {
|
||||
A: AssetId,
|
||||
B: Balance,
|
||||
OnDrop: HandleImbalanceDrop<A, B>,
|
||||
OppositeOnDrop: HandleImbalanceDrop<A, B>,
|
||||
> Imbalance<A, B, OnDrop, OppositeOnDrop>
|
||||
{
|
||||
pub fn zero(asset: A) -> Self {
|
||||
Self { asset, amount: Zero::zero(), _phantom: PhantomData }
|
||||
}
|
||||
@@ -122,7 +127,10 @@ impl<
|
||||
Err(other)
|
||||
}
|
||||
}
|
||||
pub fn offset(self, other: Imbalance<A, B, OppositeOnDrop, OnDrop>) -> Result<
|
||||
pub fn offset(
|
||||
self,
|
||||
other: Imbalance<A, B, OppositeOnDrop, OnDrop>,
|
||||
) -> Result<
|
||||
SameOrOther<Self, Imbalance<A, B, OppositeOnDrop, OnDrop>>,
|
||||
(Self, Imbalance<A, B, OppositeOnDrop, OnDrop>),
|
||||
> {
|
||||
|
||||
@@ -18,16 +18,16 @@
|
||||
//! The imbalance trait type and its associates, which handles keeps everything adding up properly
|
||||
//! with unbalanced operations.
|
||||
|
||||
use sp_std::ops::Div;
|
||||
use crate::traits::misc::{SameOrOther, TryDrop};
|
||||
use sp_runtime::traits::Saturating;
|
||||
use crate::traits::misc::{TryDrop, SameOrOther};
|
||||
use sp_std::ops::Div;
|
||||
|
||||
mod split_two_ways;
|
||||
mod signed_imbalance;
|
||||
mod on_unbalanced;
|
||||
pub use split_two_ways::SplitTwoWays;
|
||||
pub use signed_imbalance::SignedImbalance;
|
||||
mod signed_imbalance;
|
||||
mod split_two_ways;
|
||||
pub use on_unbalanced::OnUnbalanced;
|
||||
pub use signed_imbalance::SignedImbalance;
|
||||
pub use split_two_ways::SplitTwoWays;
|
||||
|
||||
/// A trait for a not-quite Linear Type that tracks an imbalance.
|
||||
///
|
||||
@@ -78,10 +78,13 @@ pub trait Imbalance<Balance>: Sized + TryDrop + Default {
|
||||
/// NOTE: This requires up to `first + second` room for a multiply, and `first + second` should
|
||||
/// fit into a `u32`. Overflow will safely saturate in both cases.
|
||||
fn ration(self, first: u32, second: u32) -> (Self, Self)
|
||||
where Balance: From<u32> + Saturating + Div<Output=Balance>
|
||||
where
|
||||
Balance: From<u32> + Saturating + Div<Output = Balance>,
|
||||
{
|
||||
let total: u32 = first.saturating_add(second);
|
||||
if total == 0 { return (Self::zero(), Self::zero()) }
|
||||
if total == 0 {
|
||||
return (Self::zero(), Self::zero())
|
||||
}
|
||||
let amount1 = self.peek().saturating_mul(first.into()) / total.into();
|
||||
self.split(amount1)
|
||||
}
|
||||
@@ -100,7 +103,8 @@ pub trait Imbalance<Balance>: Sized + TryDrop + Default {
|
||||
///
|
||||
/// A convenient replacement for `split` and `merge`.
|
||||
fn ration_merge(self, first: u32, second: u32, others: (Self, Self)) -> (Self, Self)
|
||||
where Balance: From<u32> + Saturating + Div<Output=Balance>
|
||||
where
|
||||
Balance: From<u32> + Saturating + Div<Output = Balance>,
|
||||
{
|
||||
let (a, b) = self.ration(first, second);
|
||||
(a.merge(others.0), b.merge(others.1))
|
||||
@@ -121,7 +125,8 @@ pub trait Imbalance<Balance>: Sized + TryDrop + Default {
|
||||
///
|
||||
/// A convenient replacement for `split` and `merge`.
|
||||
fn ration_merge_into(self, first: u32, second: u32, others: &mut (Self, Self))
|
||||
where Balance: From<u32> + Saturating + Div<Output=Balance>
|
||||
where
|
||||
Balance: From<u32> + Saturating + Div<Output = Balance>,
|
||||
{
|
||||
let (a, b) = self.ration(first, second);
|
||||
others.0.subsume(a);
|
||||
@@ -167,7 +172,7 @@ pub trait Imbalance<Balance>: Sized + TryDrop + Default {
|
||||
/// greater value than the `other`. Otherwise returns `Err` with an instance of
|
||||
/// the `Opposite`. In both cases the value represents the combination of `self`
|
||||
/// and `other`.
|
||||
fn offset(self, other: Self::Opposite)-> SameOrOther<Self, Self::Opposite>;
|
||||
fn offset(self, other: Self::Opposite) -> SameOrOther<Self, Self::Opposite>;
|
||||
|
||||
/// The raw value of self.
|
||||
fn peek(&self) -> Balance;
|
||||
|
||||
@@ -33,7 +33,10 @@ pub trait OnUnbalanced<Imbalance: TryDrop> {
|
||||
/// Handler for some imbalances. The different imbalances might have different origins or
|
||||
/// meanings, dependent on the context. Will default to simply calling on_unbalanced for all
|
||||
/// of them. Infallible.
|
||||
fn on_unbalanceds<B>(amounts: impl Iterator<Item=Imbalance>) where Imbalance: crate::traits::Imbalance<B> {
|
||||
fn on_unbalanceds<B>(amounts: impl Iterator<Item = Imbalance>)
|
||||
where
|
||||
Imbalance: crate::traits::Imbalance<B>,
|
||||
{
|
||||
Self::on_unbalanced(amounts.fold(Imbalance::zero(), |i, x| x.merge(i)))
|
||||
}
|
||||
|
||||
@@ -44,7 +47,9 @@ pub trait OnUnbalanced<Imbalance: TryDrop> {
|
||||
|
||||
/// Actually handle a non-zero imbalance. You probably want to implement this rather than
|
||||
/// `on_unbalanced`.
|
||||
fn on_nonzero_unbalanced(amount: Imbalance) { drop(amount); }
|
||||
fn on_nonzero_unbalanced(amount: Imbalance) {
|
||||
drop(amount);
|
||||
}
|
||||
}
|
||||
|
||||
impl<Imbalance: TryDrop> OnUnbalanced<Imbalance> for () {}
|
||||
|
||||
@@ -17,14 +17,14 @@
|
||||
|
||||
//! Convenience type for managing an imbalance whose sign is unknown.
|
||||
|
||||
use codec::FullCodec;
|
||||
use sp_std::fmt::Debug;
|
||||
use sp_runtime::traits::{AtLeast32BitUnsigned, MaybeSerializeDeserialize};
|
||||
use crate::traits::misc::SameOrOther;
|
||||
use super::super::imbalance::Imbalance;
|
||||
use crate::traits::misc::SameOrOther;
|
||||
use codec::FullCodec;
|
||||
use sp_runtime::traits::{AtLeast32BitUnsigned, MaybeSerializeDeserialize};
|
||||
use sp_std::fmt::Debug;
|
||||
|
||||
/// Either a positive or a negative imbalance.
|
||||
pub enum SignedImbalance<B, PositiveImbalance: Imbalance<B>>{
|
||||
pub enum SignedImbalance<B, PositiveImbalance: Imbalance<B>> {
|
||||
/// A positive imbalance (funds have been created but none destroyed).
|
||||
Positive(PositiveImbalance),
|
||||
/// A negative imbalance (funds have been destroyed but none created).
|
||||
@@ -32,10 +32,11 @@ pub enum SignedImbalance<B, PositiveImbalance: Imbalance<B>>{
|
||||
}
|
||||
|
||||
impl<
|
||||
P: Imbalance<B, Opposite=N>,
|
||||
N: Imbalance<B, Opposite=P>,
|
||||
B: AtLeast32BitUnsigned + FullCodec + Copy + MaybeSerializeDeserialize + Debug + Default,
|
||||
> SignedImbalance<B, P> {
|
||||
P: Imbalance<B, Opposite = N>,
|
||||
N: Imbalance<B, Opposite = P>,
|
||||
B: AtLeast32BitUnsigned + FullCodec + Copy + MaybeSerializeDeserialize + Debug + Default,
|
||||
> SignedImbalance<B, P>
|
||||
{
|
||||
/// Create a `Positive` instance of `Self` whose value is zero.
|
||||
pub fn zero() -> Self {
|
||||
SignedImbalance::Positive(P::zero())
|
||||
|
||||
@@ -17,29 +17,24 @@
|
||||
|
||||
//! Means for splitting an imbalance into two and hanlding them differently.
|
||||
|
||||
use sp_std::{ops::Div, marker::PhantomData};
|
||||
use super::super::imbalance::{Imbalance, OnUnbalanced};
|
||||
use sp_core::u32_trait::Value as U32;
|
||||
use sp_runtime::traits::Saturating;
|
||||
use super::super::imbalance::{Imbalance, OnUnbalanced};
|
||||
use sp_std::{marker::PhantomData, ops::Div};
|
||||
|
||||
/// Split an unbalanced amount two ways between a common divisor.
|
||||
pub struct SplitTwoWays<
|
||||
Balance,
|
||||
Imbalance,
|
||||
Part1,
|
||||
Target1,
|
||||
Part2,
|
||||
Target2,
|
||||
>(PhantomData<(Balance, Imbalance, Part1, Target1, Part2, Target2)>);
|
||||
pub struct SplitTwoWays<Balance, Imbalance, Part1, Target1, Part2, Target2>(
|
||||
PhantomData<(Balance, Imbalance, Part1, Target1, Part2, Target2)>,
|
||||
);
|
||||
|
||||
impl<
|
||||
Balance: From<u32> + Saturating + Div<Output=Balance>,
|
||||
I: Imbalance<Balance>,
|
||||
Part1: U32,
|
||||
Target1: OnUnbalanced<I>,
|
||||
Part2: U32,
|
||||
Target2: OnUnbalanced<I>,
|
||||
> OnUnbalanced<I> for SplitTwoWays<Balance, I, Part1, Target1, Part2, Target2>
|
||||
Balance: From<u32> + Saturating + Div<Output = Balance>,
|
||||
I: Imbalance<Balance>,
|
||||
Part1: U32,
|
||||
Target1: OnUnbalanced<I>,
|
||||
Part2: U32,
|
||||
Target2: OnUnbalanced<I>,
|
||||
> OnUnbalanced<I> for SplitTwoWays<Balance, I, Part1, Target1, Part2, Target2>
|
||||
{
|
||||
fn on_nonzero_unbalanced(amount: I) {
|
||||
let total: u32 = Part1::VALUE + Part2::VALUE;
|
||||
|
||||
@@ -17,11 +17,11 @@
|
||||
|
||||
//! Miscellaneous types.
|
||||
|
||||
use sp_std::fmt::Debug;
|
||||
use codec::{Encode, Decode, FullCodec};
|
||||
use codec::{Decode, Encode, FullCodec};
|
||||
use sp_arithmetic::traits::{AtLeast32BitUnsigned, Zero};
|
||||
use sp_core::RuntimeDebug;
|
||||
use sp_arithmetic::traits::{Zero, AtLeast32BitUnsigned};
|
||||
use sp_runtime::{DispatchError, ArithmeticError, TokenError};
|
||||
use sp_runtime::{ArithmeticError, DispatchError, TokenError};
|
||||
use sp_std::fmt::Debug;
|
||||
|
||||
/// One of a number of consequences of withdrawing a fungible from an account.
|
||||
#[derive(Copy, Clone, Eq, PartialEq)]
|
||||
@@ -150,7 +150,7 @@ impl WithdrawReasons {
|
||||
/// assert_eq!(
|
||||
/// WithdrawReasons::FEE | WithdrawReasons::TRANSFER | WithdrawReasons::RESERVE | WithdrawReasons::TIP,
|
||||
/// WithdrawReasons::except(WithdrawReasons::TRANSACTION_PAYMENT),
|
||||
/// );
|
||||
/// );
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn except(one: WithdrawReasons) -> WithdrawReasons {
|
||||
@@ -161,7 +161,7 @@ impl WithdrawReasons {
|
||||
}
|
||||
|
||||
/// Simple amalgamation trait to collect together properties for an AssetId under one roof.
|
||||
pub trait AssetId: FullCodec + Copy + Eq + PartialEq + Debug {}
|
||||
pub trait AssetId: FullCodec + Copy + Eq + PartialEq + Debug {}
|
||||
impl<T: FullCodec + Copy + Eq + PartialEq + Debug> AssetId for T {}
|
||||
|
||||
/// Simple amalgamation trait to collect together properties for a Balance under one roof.
|
||||
|
||||
@@ -24,12 +24,11 @@
|
||||
//! For an NFT API which has dual-level namespacing, the traits in `nonfungibles` are better to
|
||||
//! use.
|
||||
|
||||
use codec::{Encode, Decode};
|
||||
use sp_std::prelude::*;
|
||||
use sp_runtime::TokenError;
|
||||
use crate::dispatch::DispatchResult;
|
||||
use crate::traits::Get;
|
||||
use super::nonfungibles;
|
||||
use crate::{dispatch::DispatchResult, traits::Get};
|
||||
use codec::{Decode, Encode};
|
||||
use sp_runtime::TokenError;
|
||||
use sp_std::prelude::*;
|
||||
|
||||
/// Trait for providing an interface to a read-only NFT-like set of asset instances.
|
||||
pub trait Inspect<AccountId> {
|
||||
@@ -43,7 +42,9 @@ pub trait Inspect<AccountId> {
|
||||
/// Returns the attribute value of `instance` corresponding to `key`.
|
||||
///
|
||||
/// By default this is `None`; no attributes are defined.
|
||||
fn attribute(_instance: &Self::InstanceId, _key: &[u8]) -> Option<Vec<u8>> { None }
|
||||
fn attribute(_instance: &Self::InstanceId, _key: &[u8]) -> Option<Vec<u8>> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Returns the strongly-typed attribute value of `instance` corresponding to `key`.
|
||||
///
|
||||
@@ -56,7 +57,9 @@ pub trait Inspect<AccountId> {
|
||||
/// Returns `true` if the asset `instance` may be transferred.
|
||||
///
|
||||
/// Default implementation is that all assets are transferable.
|
||||
fn can_transfer(_instance: &Self::InstanceId) -> bool { true }
|
||||
fn can_transfer(_instance: &Self::InstanceId) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// Interface for enumerating assets in existence or owned by a given account over a collection
|
||||
@@ -117,15 +120,14 @@ pub struct ItemOf<
|
||||
F: nonfungibles::Inspect<AccountId>,
|
||||
A: Get<<F as nonfungibles::Inspect<AccountId>>::ClassId>,
|
||||
AccountId,
|
||||
>(
|
||||
sp_std::marker::PhantomData<(F, A, AccountId)>
|
||||
);
|
||||
>(sp_std::marker::PhantomData<(F, A, AccountId)>);
|
||||
|
||||
impl<
|
||||
F: nonfungibles::Inspect<AccountId>,
|
||||
A: Get<<F as nonfungibles::Inspect<AccountId>>::ClassId>,
|
||||
AccountId,
|
||||
> Inspect<AccountId> for ItemOf<F, A, AccountId> {
|
||||
F: nonfungibles::Inspect<AccountId>,
|
||||
A: Get<<F as nonfungibles::Inspect<AccountId>>::ClassId>,
|
||||
AccountId,
|
||||
> Inspect<AccountId> for ItemOf<F, A, AccountId>
|
||||
{
|
||||
type InstanceId = <F as nonfungibles::Inspect<AccountId>>::InstanceId;
|
||||
fn owner(instance: &Self::InstanceId) -> Option<AccountId> {
|
||||
<F as nonfungibles::Inspect<AccountId>>::owner(&A::get(), instance)
|
||||
@@ -142,10 +144,11 @@ impl<
|
||||
}
|
||||
|
||||
impl<
|
||||
F: nonfungibles::InspectEnumerable<AccountId>,
|
||||
A: Get<<F as nonfungibles::Inspect<AccountId>>::ClassId>,
|
||||
AccountId,
|
||||
> InspectEnumerable<AccountId> for ItemOf<F, A, AccountId> {
|
||||
F: nonfungibles::InspectEnumerable<AccountId>,
|
||||
A: Get<<F as nonfungibles::Inspect<AccountId>>::ClassId>,
|
||||
AccountId,
|
||||
> InspectEnumerable<AccountId> for ItemOf<F, A, AccountId>
|
||||
{
|
||||
fn instances() -> Box<dyn Iterator<Item = Self::InstanceId>> {
|
||||
<F as nonfungibles::InspectEnumerable<AccountId>>::instances(&A::get())
|
||||
}
|
||||
@@ -155,10 +158,11 @@ impl<
|
||||
}
|
||||
|
||||
impl<
|
||||
F: nonfungibles::Mutate<AccountId>,
|
||||
A: Get<<F as nonfungibles::Inspect<AccountId>>::ClassId>,
|
||||
AccountId,
|
||||
> Mutate<AccountId> for ItemOf<F, A, AccountId> {
|
||||
F: nonfungibles::Mutate<AccountId>,
|
||||
A: Get<<F as nonfungibles::Inspect<AccountId>>::ClassId>,
|
||||
AccountId,
|
||||
> Mutate<AccountId> for ItemOf<F, A, AccountId>
|
||||
{
|
||||
fn mint_into(instance: &Self::InstanceId, who: &AccountId) -> DispatchResult {
|
||||
<F as nonfungibles::Mutate<AccountId>>::mint_into(&A::get(), instance, who)
|
||||
}
|
||||
@@ -178,10 +182,11 @@ impl<
|
||||
}
|
||||
|
||||
impl<
|
||||
F: nonfungibles::Transfer<AccountId>,
|
||||
A: Get<<F as nonfungibles::Inspect<AccountId>>::ClassId>,
|
||||
AccountId,
|
||||
> Transfer<AccountId> for ItemOf<F, A, AccountId> {
|
||||
F: nonfungibles::Transfer<AccountId>,
|
||||
A: Get<<F as nonfungibles::Inspect<AccountId>>::ClassId>,
|
||||
AccountId,
|
||||
> Transfer<AccountId> for ItemOf<F, A, AccountId>
|
||||
{
|
||||
fn transfer(instance: &Self::InstanceId, destination: &AccountId) -> DispatchResult {
|
||||
<F as nonfungibles::Transfer<AccountId>>::transfer(&A::get(), instance, destination)
|
||||
}
|
||||
|
||||
@@ -27,10 +27,10 @@
|
||||
//! Implementations of these traits may be converted to implementations of corresponding
|
||||
//! `nonfungible` traits by using the `nonfungible::ItemOf` type adapter.
|
||||
|
||||
use sp_std::prelude::*;
|
||||
use codec::{Encode, Decode};
|
||||
use sp_runtime::TokenError;
|
||||
use crate::dispatch::DispatchResult;
|
||||
use codec::{Decode, Encode};
|
||||
use sp_runtime::TokenError;
|
||||
use sp_std::prelude::*;
|
||||
|
||||
/// Trait for providing an interface to many read-only NFT-like sets of asset instances.
|
||||
pub trait Inspect<AccountId> {
|
||||
@@ -48,14 +48,18 @@ pub trait Inspect<AccountId> {
|
||||
/// Returns the owner of the asset `class`, if there is one. For many NFTs this may not make
|
||||
/// any sense, so users of this API should not be surprised to find an asset class results in
|
||||
/// `None` here.
|
||||
fn class_owner(_class: &Self::ClassId) -> Option<AccountId> { None }
|
||||
fn class_owner(_class: &Self::ClassId) -> Option<AccountId> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Returns the attribute value of `instance` of `class` corresponding to `key`.
|
||||
///
|
||||
/// By default this is `None`; no attributes are defined.
|
||||
fn attribute(_class: &Self::ClassId, _instance: &Self::InstanceId, _key: &[u8])
|
||||
-> Option<Vec<u8>>
|
||||
{
|
||||
fn attribute(
|
||||
_class: &Self::ClassId,
|
||||
_instance: &Self::InstanceId,
|
||||
_key: &[u8],
|
||||
) -> Option<Vec<u8>> {
|
||||
None
|
||||
}
|
||||
|
||||
@@ -74,15 +78,14 @@ pub trait Inspect<AccountId> {
|
||||
/// Returns the attribute value of `class` corresponding to `key`.
|
||||
///
|
||||
/// By default this is `None`; no attributes are defined.
|
||||
fn class_attribute(_class: &Self::ClassId, _key: &[u8]) -> Option<Vec<u8>> { None }
|
||||
fn class_attribute(_class: &Self::ClassId, _key: &[u8]) -> Option<Vec<u8>> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Returns the strongly-typed attribute value of `class` corresponding to `key`.
|
||||
///
|
||||
/// By default this just attempts to use `class_attribute`.
|
||||
fn typed_class_attribute<K: Encode, V: Decode>(
|
||||
class: &Self::ClassId,
|
||||
key: &K,
|
||||
) -> Option<V> {
|
||||
fn typed_class_attribute<K: Encode, V: Decode>(class: &Self::ClassId, key: &K) -> Option<V> {
|
||||
key.using_encoded(|d| Self::class_attribute(class, d))
|
||||
.and_then(|v| V::decode(&mut &v[..]).ok())
|
||||
}
|
||||
@@ -90,7 +93,9 @@ pub trait Inspect<AccountId> {
|
||||
/// Returns `true` if the asset `instance` of `class` may be transferred.
|
||||
///
|
||||
/// Default implementation is that all assets are transferable.
|
||||
fn can_transfer(_class: &Self::ClassId, _instance: &Self::InstanceId) -> bool { true }
|
||||
fn can_transfer(_class: &Self::ClassId, _instance: &Self::InstanceId) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// Interface for enumerating assets in existence or owned by a given account over many collections
|
||||
@@ -106,7 +111,10 @@ pub trait InspectEnumerable<AccountId>: Inspect<AccountId> {
|
||||
fn owned(who: &AccountId) -> Box<dyn Iterator<Item = (Self::ClassId, Self::InstanceId)>>;
|
||||
|
||||
/// Returns an iterator of the asset instances of `class` owned by `who`.
|
||||
fn owned_in_class(class: &Self::ClassId, who: &AccountId) -> Box<dyn Iterator<Item = Self::InstanceId>>;
|
||||
fn owned_in_class(
|
||||
class: &Self::ClassId,
|
||||
who: &AccountId,
|
||||
) -> Box<dyn Iterator<Item = Self::InstanceId>>;
|
||||
}
|
||||
|
||||
/// Trait for providing an interface for multiple classes of NFT-like assets which may be minted,
|
||||
@@ -151,19 +159,13 @@ pub trait Mutate<AccountId>: Inspect<AccountId> {
|
||||
key: &K,
|
||||
value: &V,
|
||||
) -> DispatchResult {
|
||||
key.using_encoded(|k| value.using_encoded(|v|
|
||||
Self::set_attribute(class, instance, k, v)
|
||||
))
|
||||
key.using_encoded(|k| value.using_encoded(|v| Self::set_attribute(class, instance, k, v)))
|
||||
}
|
||||
|
||||
/// Set attribute `value` of asset `class`'s `key`.
|
||||
///
|
||||
/// By default, this is not a supported operation.
|
||||
fn set_class_attribute(
|
||||
_class: &Self::ClassId,
|
||||
_key: &[u8],
|
||||
_value: &[u8],
|
||||
) -> DispatchResult {
|
||||
fn set_class_attribute(_class: &Self::ClassId, _key: &[u8], _value: &[u8]) -> DispatchResult {
|
||||
Err(TokenError::Unsupported.into())
|
||||
}
|
||||
|
||||
@@ -175,9 +177,7 @@ pub trait Mutate<AccountId>: Inspect<AccountId> {
|
||||
key: &K,
|
||||
value: &V,
|
||||
) -> DispatchResult {
|
||||
key.using_encoded(|k| value.using_encoded(|v|
|
||||
Self::set_class_attribute(class, k, v)
|
||||
))
|
||||
key.using_encoded(|k| value.using_encoded(|v| Self::set_class_attribute(class, k, v)))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -17,13 +17,14 @@
|
||||
|
||||
//! Traits for dealing with validation and validators.
|
||||
|
||||
use sp_std::prelude::*;
|
||||
use crate::{dispatch::Parameter, weights::Weight};
|
||||
use codec::{Codec, Decode};
|
||||
use sp_runtime::traits::{Convert, Zero};
|
||||
use sp_runtime::{BoundToRuntimeAppPublic, ConsensusEngineId, Permill, RuntimeAppPublic};
|
||||
use sp_runtime::{
|
||||
traits::{Convert, Zero},
|
||||
BoundToRuntimeAppPublic, ConsensusEngineId, Permill, RuntimeAppPublic,
|
||||
};
|
||||
use sp_staking::SessionIndex;
|
||||
use crate::dispatch::Parameter;
|
||||
use crate::weights::Weight;
|
||||
use sp_std::prelude::*;
|
||||
|
||||
/// A trait for online node inspection in a session.
|
||||
///
|
||||
@@ -54,12 +55,14 @@ pub trait ValidatorSetWithIdentification<AccountId>: ValidatorSet<AccountId> {
|
||||
pub trait FindAuthor<Author> {
|
||||
/// Find the author of a block based on the pre-runtime digests.
|
||||
fn find_author<'a, I>(digests: I) -> Option<Author>
|
||||
where I: 'a + IntoIterator<Item=(ConsensusEngineId, &'a [u8])>;
|
||||
where
|
||||
I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>;
|
||||
}
|
||||
|
||||
impl<A> FindAuthor<A> for () {
|
||||
fn find_author<'a, I>(_: I) -> Option<A>
|
||||
where I: 'a + IntoIterator<Item=(ConsensusEngineId, &'a [u8])>
|
||||
where
|
||||
I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,
|
||||
{
|
||||
None
|
||||
}
|
||||
@@ -81,7 +84,9 @@ pub trait OneSessionHandler<ValidatorId>: BoundToRuntimeAppPublic {
|
||||
/// for the second session, therefore the first call to `on_new_session`
|
||||
/// should provide the same validator set.
|
||||
fn on_genesis_session<'a, I: 'a>(validators: I)
|
||||
where I: Iterator<Item=(&'a ValidatorId, Self::Key)>, ValidatorId: 'a;
|
||||
where
|
||||
I: Iterator<Item = (&'a ValidatorId, Self::Key)>,
|
||||
ValidatorId: 'a;
|
||||
|
||||
/// Session set has changed; act appropriately. Note that this can be called
|
||||
/// before initialization of your module.
|
||||
@@ -92,11 +97,10 @@ pub trait OneSessionHandler<ValidatorId>: BoundToRuntimeAppPublic {
|
||||
///
|
||||
/// The `validators` are the validators of the incoming session, and `queued_validators`
|
||||
/// will follow.
|
||||
fn on_new_session<'a, I: 'a>(
|
||||
changed: bool,
|
||||
validators: I,
|
||||
queued_validators: I,
|
||||
) where I: Iterator<Item=(&'a ValidatorId, Self::Key)>, ValidatorId: 'a;
|
||||
fn on_new_session<'a, I: 'a>(changed: bool, validators: I, queued_validators: I)
|
||||
where
|
||||
I: Iterator<Item = (&'a ValidatorId, Self::Key)>,
|
||||
ValidatorId: 'a;
|
||||
|
||||
/// A notification for end of the session.
|
||||
///
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
//! Traits and associated data structures concerned with voting, and moving between tokens and
|
||||
//! votes.
|
||||
|
||||
use sp_arithmetic::traits::{UniqueSaturatedInto, UniqueSaturatedFrom, SaturatedConversion};
|
||||
use sp_arithmetic::traits::{SaturatedConversion, UniqueSaturatedFrom, UniqueSaturatedInto};
|
||||
|
||||
/// A trait similar to `Convert` to convert values from `B` an abstract balance type
|
||||
/// into u64 and back from u128. (This conversion is used in election and other places where complex
|
||||
@@ -69,7 +69,6 @@ impl CurrencyToVote<u128> for U128CurrencyToVote {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// A naive implementation of `CurrencyConvert` that simply saturates all conversions.
|
||||
///
|
||||
/// # Warning
|
||||
@@ -77,7 +76,9 @@ impl CurrencyToVote<u128> for U128CurrencyToVote {
|
||||
/// This is designed to be used mostly for testing. Use with care, and think about the consequences.
|
||||
pub struct SaturatingCurrencyToVote;
|
||||
|
||||
impl<B: UniqueSaturatedInto<u64> + UniqueSaturatedFrom<u128>> CurrencyToVote<B> for SaturatingCurrencyToVote {
|
||||
impl<B: UniqueSaturatedInto<u64> + UniqueSaturatedFrom<u128>> CurrencyToVote<B>
|
||||
for SaturatingCurrencyToVote
|
||||
{
|
||||
fn to_vote(value: B, _: B) -> u64 {
|
||||
value.unique_saturated_into()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user