use super::MultiLocation;
use crate::v3::{
AssetId as NewAssetId, AssetInstance as NewAssetInstance, Fungibility as NewFungibility,
MultiAsset as NewMultiAsset, MultiAssetFilter as NewMultiAssetFilter,
MultiAssets as NewMultiAssets, WildFungibility as NewWildFungibility,
WildMultiAsset as NewWildMultiAsset,
};
use alloc::{vec, vec::Vec};
use core::cmp::Ordering;
use parity_scale_codec::{self as codec, Decode, Encode};
use scale_info::TypeInfo;
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, Debug, TypeInfo)]
#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))]
pub enum AssetInstance {
Undefined,
Index(#[codec(compact)] u128),
Array4([u8; 4]),
Array8([u8; 8]),
Array16([u8; 16]),
Array32([u8; 32]),
Blob(Vec<u8>),
}
impl From<()> for AssetInstance {
fn from(_: ()) -> Self {
Self::Undefined
}
}
impl From<[u8; 4]> for AssetInstance {
fn from(x: [u8; 4]) -> Self {
Self::Array4(x)
}
}
impl From<[u8; 8]> for AssetInstance {
fn from(x: [u8; 8]) -> Self {
Self::Array8(x)
}
}
impl From<[u8; 16]> for AssetInstance {
fn from(x: [u8; 16]) -> Self {
Self::Array16(x)
}
}
impl From<[u8; 32]> for AssetInstance {
fn from(x: [u8; 32]) -> Self {
Self::Array32(x)
}
}
impl From<Vec<u8>> for AssetInstance {
fn from(x: Vec<u8>) -> Self {
Self::Blob(x)
}
}
impl TryFrom<NewAssetInstance> for AssetInstance {
type Error = ();
fn try_from(value: NewAssetInstance) -> Result<Self, Self::Error> {
use NewAssetInstance::*;
Ok(match value {
Undefined => Self::Undefined,
Index(n) => Self::Index(n),
Array4(n) => Self::Array4(n),
Array8(n) => Self::Array8(n),
Array16(n) => Self::Array16(n),
Array32(n) => Self::Array32(n),
})
}
}
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Debug, Encode, Decode, TypeInfo)]
#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))]
pub enum AssetId {
Concrete(MultiLocation),
Abstract(Vec<u8>),
}
impl<T: Into<MultiLocation>> From<T> for AssetId {
fn from(x: T) -> Self {
Self::Concrete(x.into())
}
}
impl From<Vec<u8>> for AssetId {
fn from(x: Vec<u8>) -> Self {
Self::Abstract(x)
}
}
impl TryFrom<NewAssetId> for AssetId {
type Error = ();
fn try_from(old: NewAssetId) -> Result<Self, ()> {
use NewAssetId::*;
Ok(match old {
Concrete(l) => Self::Concrete(l.try_into()?),
Abstract(v) => {
let zeroes = v.iter().rev().position(|n| *n != 0).unwrap_or(v.len());
Self::Abstract(v[0..(32 - zeroes)].to_vec())
},
})
}
}
impl AssetId {
pub fn prepend_with(&mut self, prepend: &MultiLocation) -> Result<(), ()> {
if let AssetId::Concrete(ref mut l) = self {
l.prepend_with(prepend.clone()).map_err(|_| ())?;
}
Ok(())
}
pub fn reanchor(&mut self, target: &MultiLocation, ancestry: &MultiLocation) -> Result<(), ()> {
if let AssetId::Concrete(ref mut l) = self {
l.reanchor(target, ancestry)?;
}
Ok(())
}
pub fn into_multiasset(self, fun: Fungibility) -> MultiAsset {
MultiAsset { fun, id: self }
}
pub fn into_wild(self, fun: WildFungibility) -> WildMultiAsset {
WildMultiAsset::AllOf { fun, id: self }
}
}
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Debug, Encode, Decode, TypeInfo)]
#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))]
pub enum Fungibility {
Fungible(#[codec(compact)] u128),
NonFungible(AssetInstance),
}
impl Fungibility {
pub fn is_kind(&self, w: WildFungibility) -> bool {
use Fungibility::*;
use WildFungibility::{Fungible as WildFungible, NonFungible as WildNonFungible};
matches!((self, w), (Fungible(_), WildFungible) | (NonFungible(_), WildNonFungible))
}
}
impl From<u128> for Fungibility {
fn from(amount: u128) -> Fungibility {
debug_assert_ne!(amount, 0);
Fungibility::Fungible(amount)
}
}
impl<T: Into<AssetInstance>> From<T> for Fungibility {
fn from(instance: T) -> Fungibility {
Fungibility::NonFungible(instance.into())
}
}
impl TryFrom<NewFungibility> for Fungibility {
type Error = ();
fn try_from(value: NewFungibility) -> Result<Self, Self::Error> {
use NewFungibility::*;
Ok(match value {
Fungible(n) => Self::Fungible(n),
NonFungible(i) => Self::NonFungible(i.try_into()?),
})
}
}
#[derive(Clone, Eq, PartialEq, Debug, Encode, Decode, TypeInfo)]
#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))]
pub struct MultiAsset {
pub id: AssetId,
pub fun: Fungibility,
}
impl PartialOrd for MultiAsset {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for MultiAsset {
fn cmp(&self, other: &Self) -> Ordering {
match (&self.fun, &other.fun) {
(Fungibility::Fungible(..), Fungibility::NonFungible(..)) => Ordering::Less,
(Fungibility::NonFungible(..), Fungibility::Fungible(..)) => Ordering::Greater,
_ => (&self.id, &self.fun).cmp(&(&other.id, &other.fun)),
}
}
}
impl<A: Into<AssetId>, B: Into<Fungibility>> From<(A, B)> for MultiAsset {
fn from((id, fun): (A, B)) -> MultiAsset {
MultiAsset { fun: fun.into(), id: id.into() }
}
}
impl MultiAsset {
pub fn is_fungible(&self, maybe_id: Option<AssetId>) -> bool {
use Fungibility::*;
matches!(self.fun, Fungible(..)) && maybe_id.map_or(true, |i| i == self.id)
}
pub fn is_non_fungible(&self, maybe_id: Option<AssetId>) -> bool {
use Fungibility::*;
matches!(self.fun, NonFungible(..)) && maybe_id.map_or(true, |i| i == self.id)
}
pub fn prepend_with(&mut self, prepend: &MultiLocation) -> Result<(), ()> {
self.id.prepend_with(prepend)
}
pub fn reanchor(&mut self, target: &MultiLocation, ancestry: &MultiLocation) -> Result<(), ()> {
self.id.reanchor(target, ancestry)
}
pub fn reanchored(
mut self,
target: &MultiLocation,
ancestry: &MultiLocation,
) -> Result<Self, ()> {
self.id.reanchor(target, ancestry)?;
Ok(self)
}
pub fn contains(&self, inner: &MultiAsset) -> bool {
use Fungibility::*;
if self.id == inner.id {
match (&self.fun, &inner.fun) {
(Fungible(a), Fungible(i)) if a >= i => return true,
(NonFungible(a), NonFungible(i)) if a == i => return true,
_ => (),
}
}
false
}
}
impl TryFrom<NewMultiAsset> for MultiAsset {
type Error = ();
fn try_from(new: NewMultiAsset) -> Result<Self, ()> {
Ok(Self { id: new.id.try_into()?, fun: new.fun.try_into()? })
}
}
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Debug, Encode, TypeInfo)]
#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))]
pub struct MultiAssets(Vec<MultiAsset>);
impl Decode for MultiAssets {
fn decode<I: codec::Input>(input: &mut I) -> Result<Self, parity_scale_codec::Error> {
Self::from_sorted_and_deduplicated(Vec::<MultiAsset>::decode(input)?)
.map_err(|()| "Out of order".into())
}
}
impl TryFrom<NewMultiAssets> for MultiAssets {
type Error = ();
fn try_from(new: NewMultiAssets) -> Result<Self, ()> {
let v = new
.into_inner()
.into_iter()
.map(MultiAsset::try_from)
.collect::<Result<Vec<_>, ()>>()?;
Ok(MultiAssets(v))
}
}
impl From<Vec<MultiAsset>> for MultiAssets {
fn from(mut assets: Vec<MultiAsset>) -> Self {
let mut res = Vec::with_capacity(assets.len());
if !assets.is_empty() {
assets.sort();
let mut iter = assets.into_iter();
if let Some(first) = iter.next() {
let last = iter.fold(first, |a, b| -> MultiAsset {
match (a, b) {
(
MultiAsset { fun: Fungibility::Fungible(a_amount), id: a_id },
MultiAsset { fun: Fungibility::Fungible(b_amount), id: b_id },
) if a_id == b_id => MultiAsset {
id: a_id,
fun: Fungibility::Fungible(a_amount.saturating_add(b_amount)),
},
(
MultiAsset { fun: Fungibility::NonFungible(a_instance), id: a_id },
MultiAsset { fun: Fungibility::NonFungible(b_instance), id: b_id },
) if a_id == b_id && a_instance == b_instance =>
MultiAsset { fun: Fungibility::NonFungible(a_instance), id: a_id },
(to_push, to_remember) => {
res.push(to_push);
to_remember
},
}
});
res.push(last);
}
}
Self(res)
}
}
impl<T: Into<MultiAsset>> From<T> for MultiAssets {
fn from(x: T) -> Self {
Self(vec![x.into()])
}
}
impl MultiAssets {
pub fn new() -> Self {
Self(Vec::new())
}
pub fn from_sorted_and_deduplicated(r: Vec<MultiAsset>) -> Result<Self, ()> {
if r.is_empty() {
return Ok(Self(Vec::new()))
}
r.iter().skip(1).try_fold(&r[0], |a, b| -> Result<&MultiAsset, ()> {
if a.id < b.id || a < b && (a.is_non_fungible(None) || b.is_non_fungible(None)) {
Ok(b)
} else {
Err(())
}
})?;
Ok(Self(r))
}
#[cfg(test)]
pub fn from_sorted_and_deduplicated_skip_checks(r: Vec<MultiAsset>) -> Self {
Self::from_sorted_and_deduplicated(r).expect("Invalid input r is not sorted/deduped")
}
#[cfg(not(test))]
pub fn from_sorted_and_deduplicated_skip_checks(r: Vec<MultiAsset>) -> Self {
Self(r)
}
pub fn push(&mut self, a: MultiAsset) {
if let Fungibility::Fungible(ref amount) = a.fun {
for asset in self.0.iter_mut().filter(|x| x.id == a.id) {
if let Fungibility::Fungible(ref mut balance) = asset.fun {
*balance = balance.saturating_add(*amount);
return
}
}
}
self.0.push(a);
self.0.sort();
}
pub fn is_none(&self) -> bool {
self.0.is_empty()
}
pub fn contains(&self, inner: &MultiAsset) -> bool {
self.0.iter().any(|i| i.contains(inner))
}
pub fn drain(self) -> Vec<MultiAsset> {
self.0
}
pub fn inner(&self) -> &Vec<MultiAsset> {
&self.0
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn prepend_with(&mut self, prefix: &MultiLocation) -> Result<(), ()> {
self.0.iter_mut().try_for_each(|i| i.prepend_with(prefix))
}
pub fn reanchor(&mut self, target: &MultiLocation, ancestry: &MultiLocation) -> Result<(), ()> {
self.0.iter_mut().try_for_each(|i| i.reanchor(target, ancestry))
}
pub fn get(&self, index: usize) -> Option<&MultiAsset> {
self.0.get(index)
}
}
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Debug, Encode, Decode, TypeInfo)]
#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))]
pub enum WildFungibility {
Fungible,
NonFungible,
}
impl TryFrom<NewWildFungibility> for WildFungibility {
type Error = ();
fn try_from(value: NewWildFungibility) -> Result<Self, Self::Error> {
use NewWildFungibility::*;
Ok(match value {
Fungible => Self::Fungible,
NonFungible => Self::NonFungible,
})
}
}
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Debug, Encode, Decode, TypeInfo)]
#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))]
pub enum WildMultiAsset {
All,
AllOf { id: AssetId, fun: WildFungibility },
}
impl WildMultiAsset {
pub fn contains(&self, inner: &MultiAsset) -> bool {
use WildMultiAsset::*;
match self {
AllOf { fun, id } => inner.fun.is_kind(*fun) && &inner.id == id,
All => true,
}
}
pub fn reanchor(&mut self, target: &MultiLocation, ancestry: &MultiLocation) -> Result<(), ()> {
use WildMultiAsset::*;
match self {
AllOf { ref mut id, .. } => id.reanchor(target, ancestry).map_err(|_| ()),
All => Ok(()),
}
}
}
impl<A: Into<AssetId>, B: Into<WildFungibility>> From<(A, B)> for WildMultiAsset {
fn from((id, fun): (A, B)) -> WildMultiAsset {
WildMultiAsset::AllOf { fun: fun.into(), id: id.into() }
}
}
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Debug, Encode, Decode, TypeInfo)]
#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))]
pub enum MultiAssetFilter {
Definite(MultiAssets),
Wild(WildMultiAsset),
}
impl<T: Into<WildMultiAsset>> From<T> for MultiAssetFilter {
fn from(x: T) -> Self {
Self::Wild(x.into())
}
}
impl From<MultiAsset> for MultiAssetFilter {
fn from(x: MultiAsset) -> Self {
Self::Definite(vec![x].into())
}
}
impl From<Vec<MultiAsset>> for MultiAssetFilter {
fn from(x: Vec<MultiAsset>) -> Self {
Self::Definite(x.into())
}
}
impl From<MultiAssets> for MultiAssetFilter {
fn from(x: MultiAssets) -> Self {
Self::Definite(x)
}
}
impl MultiAssetFilter {
pub fn contains(&self, inner: &MultiAsset) -> bool {
match self {
MultiAssetFilter::Definite(ref assets) => assets.contains(inner),
MultiAssetFilter::Wild(ref wild) => wild.contains(inner),
}
}
pub fn reanchor(&mut self, target: &MultiLocation, ancestry: &MultiLocation) -> Result<(), ()> {
match self {
MultiAssetFilter::Definite(ref mut assets) => assets.reanchor(target, ancestry),
MultiAssetFilter::Wild(ref mut wild) => wild.reanchor(target, ancestry),
}
}
}
impl TryFrom<NewWildMultiAsset> for WildMultiAsset {
type Error = ();
fn try_from(new: NewWildMultiAsset) -> Result<Self, ()> {
use NewWildMultiAsset::*;
Ok(match new {
AllOf { id, fun } | AllOfCounted { id, fun, .. } =>
Self::AllOf { id: id.try_into()?, fun: fun.try_into()? },
All | AllCounted(_) => Self::All,
})
}
}
impl TryFrom<NewMultiAssetFilter> for MultiAssetFilter {
type Error = ();
fn try_from(old: NewMultiAssetFilter) -> Result<Self, ()> {
use NewMultiAssetFilter::*;
Ok(match old {
Definite(x) => Self::Definite(x.try_into()?),
Wild(x) => Self::Wild(x.try_into()?),
})
}
}