use super::{Junctions, MultiLocation};
use crate::{
v2::{
BodyId as OldBodyId, BodyPart as OldBodyPart, Junction as OldJunction,
NetworkId as OldNetworkId,
},
v4::{Junction as NewJunction, NetworkId as NewNetworkId},
VersionedLocation,
};
use bounded_collections::{BoundedSlice, BoundedVec, ConstU32};
use codec::{self, Decode, Encode, MaxEncodedLen};
use scale_info::TypeInfo;
use serde::{Deserialize, Serialize};
#[derive(
Copy,
Clone,
Eq,
PartialEq,
Ord,
PartialOrd,
Encode,
Decode,
Debug,
TypeInfo,
MaxEncodedLen,
Serialize,
Deserialize,
)]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
#[scale_info(replace_segment("staging_xcm", "xcm"))]
pub enum NetworkId {
ByGenesis([u8; 32]),
ByFork { block_number: u64, block_hash: [u8; 32] },
Polkadot,
Kusama,
Westend,
Rococo,
Wococo,
Ethereum {
#[codec(compact)]
chain_id: u64,
},
BitcoinCore,
BitcoinCash,
PolkadotBulletin,
}
impl From<OldNetworkId> for Option<NetworkId> {
fn from(old: OldNetworkId) -> Option<NetworkId> {
use OldNetworkId::*;
match old {
Any => None,
Named(_) => None,
Polkadot => Some(NetworkId::Polkadot),
Kusama => Some(NetworkId::Kusama),
}
}
}
impl TryFrom<OldNetworkId> for NetworkId {
type Error = ();
fn try_from(old: OldNetworkId) -> Result<Self, Self::Error> {
use OldNetworkId::*;
match old {
Any | Named(_) => Err(()),
Polkadot => Ok(NetworkId::Polkadot),
Kusama => Ok(NetworkId::Kusama),
}
}
}
impl From<NewNetworkId> for Option<NetworkId> {
fn from(new: NewNetworkId) -> Self {
Some(NetworkId::from(new))
}
}
impl From<NewNetworkId> for NetworkId {
fn from(new: NewNetworkId) -> Self {
use NewNetworkId::*;
match new {
ByGenesis(hash) => Self::ByGenesis(hash),
ByFork { block_number, block_hash } => Self::ByFork { block_number, block_hash },
Polkadot => Self::Polkadot,
Kusama => Self::Kusama,
Westend => Self::Westend,
Rococo => Self::Rococo,
Wococo => Self::Wococo,
Ethereum { chain_id } => Self::Ethereum { chain_id },
BitcoinCore => Self::BitcoinCore,
BitcoinCash => Self::BitcoinCash,
PolkadotBulletin => Self::PolkadotBulletin,
}
}
}
#[derive(
Copy,
Clone,
Eq,
PartialEq,
Ord,
PartialOrd,
Encode,
Decode,
Debug,
TypeInfo,
MaxEncodedLen,
Serialize,
Deserialize,
)]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
#[scale_info(replace_segment("staging_xcm", "xcm"))]
pub enum BodyId {
Unit,
Moniker([u8; 4]),
Index(#[codec(compact)] u32),
Executive,
Technical,
Legislative,
Judicial,
Defense,
Administration,
Treasury,
}
impl TryFrom<OldBodyId> for BodyId {
type Error = ();
fn try_from(value: OldBodyId) -> Result<Self, ()> {
use OldBodyId::*;
Ok(match value {
Unit => Self::Unit,
Named(n) =>
if n.len() == 4 {
let mut r = [0u8; 4];
r.copy_from_slice(&n[..]);
Self::Moniker(r)
} else {
return Err(())
},
Index(n) => Self::Index(n),
Executive => Self::Executive,
Technical => Self::Technical,
Legislative => Self::Legislative,
Judicial => Self::Judicial,
Defense => Self::Defense,
Administration => Self::Administration,
Treasury => Self::Treasury,
})
}
}
#[derive(
Copy,
Clone,
Eq,
PartialEq,
Ord,
PartialOrd,
Encode,
Decode,
Debug,
TypeInfo,
MaxEncodedLen,
Serialize,
Deserialize,
)]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
#[scale_info(replace_segment("staging_xcm", "xcm"))]
pub enum BodyPart {
Voice,
Members {
#[codec(compact)]
count: u32,
},
Fraction {
#[codec(compact)]
nom: u32,
#[codec(compact)]
denom: u32,
},
AtLeastProportion {
#[codec(compact)]
nom: u32,
#[codec(compact)]
denom: u32,
},
MoreThanProportion {
#[codec(compact)]
nom: u32,
#[codec(compact)]
denom: u32,
},
}
impl BodyPart {
pub fn is_majority(&self) -> bool {
match self {
BodyPart::Fraction { nom, denom } if *nom * 2 > *denom => true,
BodyPart::AtLeastProportion { nom, denom } if *nom * 2 > *denom => true,
BodyPart::MoreThanProportion { nom, denom } if *nom * 2 >= *denom => true,
_ => false,
}
}
}
impl TryFrom<OldBodyPart> for BodyPart {
type Error = ();
fn try_from(value: OldBodyPart) -> Result<Self, ()> {
use OldBodyPart::*;
Ok(match value {
Voice => Self::Voice,
Members { count } => Self::Members { count },
Fraction { nom, denom } => Self::Fraction { nom, denom },
AtLeastProportion { nom, denom } => Self::AtLeastProportion { nom, denom },
MoreThanProportion { nom, denom } => Self::MoreThanProportion { nom, denom },
})
}
}
#[derive(
Copy,
Clone,
Eq,
PartialEq,
Ord,
PartialOrd,
Encode,
Decode,
Debug,
TypeInfo,
MaxEncodedLen,
Serialize,
Deserialize,
)]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
#[scale_info(replace_segment("staging_xcm", "xcm"))]
pub enum Junction {
Parachain(#[codec(compact)] u32),
AccountId32 { network: Option<NetworkId>, id: [u8; 32] },
AccountIndex64 {
network: Option<NetworkId>,
#[codec(compact)]
index: u64,
},
AccountKey20 { network: Option<NetworkId>, key: [u8; 20] },
PalletInstance(u8),
GeneralIndex(#[codec(compact)] u128),
GeneralKey { length: u8, data: [u8; 32] },
OnlyChild,
Plurality { id: BodyId, part: BodyPart },
GlobalConsensus(NetworkId),
}
impl From<NetworkId> for Junction {
fn from(n: NetworkId) -> Self {
Self::GlobalConsensus(n)
}
}
impl From<[u8; 32]> for Junction {
fn from(id: [u8; 32]) -> Self {
Self::AccountId32 { network: None, id }
}
}
impl From<BoundedVec<u8, ConstU32<32>>> for Junction {
fn from(key: BoundedVec<u8, ConstU32<32>>) -> Self {
key.as_bounded_slice().into()
}
}
impl<'a> From<BoundedSlice<'a, u8, ConstU32<32>>> for Junction {
fn from(key: BoundedSlice<'a, u8, ConstU32<32>>) -> Self {
let mut data = [0u8; 32];
data[..key.len()].copy_from_slice(&key[..]);
Self::GeneralKey { length: key.len() as u8, data }
}
}
impl<'a> TryFrom<&'a Junction> for BoundedSlice<'a, u8, ConstU32<32>> {
type Error = ();
fn try_from(key: &'a Junction) -> Result<Self, ()> {
match key {
Junction::GeneralKey { length, data } =>
BoundedSlice::try_from(&data[..data.len().min(*length as usize)]).map_err(|_| ()),
_ => Err(()),
}
}
}
impl From<[u8; 20]> for Junction {
fn from(key: [u8; 20]) -> Self {
Self::AccountKey20 { network: None, key }
}
}
impl From<u64> for Junction {
fn from(index: u64) -> Self {
Self::AccountIndex64 { network: None, index }
}
}
impl From<u128> for Junction {
fn from(id: u128) -> Self {
Self::GeneralIndex(id)
}
}
impl TryFrom<OldJunction> for Junction {
type Error = ();
fn try_from(value: OldJunction) -> Result<Self, ()> {
use OldJunction::*;
Ok(match value {
Parachain(id) => Self::Parachain(id),
AccountId32 { network, id } => Self::AccountId32 { network: network.into(), id },
AccountIndex64 { network, index } =>
Self::AccountIndex64 { network: network.into(), index },
AccountKey20 { network, key } => Self::AccountKey20 { network: network.into(), key },
PalletInstance(index) => Self::PalletInstance(index),
GeneralIndex(id) => Self::GeneralIndex(id),
GeneralKey(key) => match key.len() {
len @ 0..=32 => Self::GeneralKey {
length: len as u8,
data: {
let mut data = [0u8; 32];
data[..len].copy_from_slice(&key[..]);
data
},
},
_ => return Err(()),
},
OnlyChild => Self::OnlyChild,
Plurality { id, part } =>
Self::Plurality { id: id.try_into()?, part: part.try_into()? },
})
}
}
impl TryFrom<NewJunction> for Junction {
type Error = ();
fn try_from(value: NewJunction) -> Result<Self, Self::Error> {
use NewJunction::*;
Ok(match value {
Parachain(id) => Self::Parachain(id),
AccountId32 { network: maybe_network, id } =>
Self::AccountId32 { network: maybe_network.map(|network| network.into()), id },
AccountIndex64 { network: maybe_network, index } =>
Self::AccountIndex64 { network: maybe_network.map(|network| network.into()), index },
AccountKey20 { network: maybe_network, key } =>
Self::AccountKey20 { network: maybe_network.map(|network| network.into()), key },
PalletInstance(index) => Self::PalletInstance(index),
GeneralIndex(id) => Self::GeneralIndex(id),
GeneralKey { length, data } => Self::GeneralKey { length, data },
OnlyChild => Self::OnlyChild,
Plurality { id, part } => Self::Plurality { id, part },
GlobalConsensus(network) => Self::GlobalConsensus(network.into()),
})
}
}
impl Junction {
pub const fn into_location(self) -> MultiLocation {
MultiLocation { parents: 0, interior: Junctions::X1(self) }
}
pub const fn into_exterior(self, n: u8) -> MultiLocation {
MultiLocation { parents: n, interior: Junctions::X1(self) }
}
pub const fn into_versioned(self) -> VersionedLocation {
self.into_location().into_versioned()
}
pub fn remove_network_id(&mut self) {
use Junction::*;
match self {
AccountId32 { ref mut network, .. } |
AccountIndex64 { ref mut network, .. } |
AccountKey20 { ref mut network, .. } => *network = None,
_ => {},
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::vec;
#[test]
fn junction_round_trip_works() {
let j = Junction::GeneralKey { length: 32, data: [1u8; 32] };
let k = Junction::try_from(OldJunction::try_from(j).unwrap()).unwrap();
assert_eq!(j, k);
let j = OldJunction::GeneralKey(vec![1u8; 32].try_into().unwrap());
let k = OldJunction::try_from(Junction::try_from(j.clone()).unwrap()).unwrap();
assert_eq!(j, k);
let j = Junction::from(BoundedVec::try_from(vec![1u8, 2, 3, 4]).unwrap());
let k = Junction::try_from(OldJunction::try_from(j).unwrap()).unwrap();
assert_eq!(j, k);
let s: BoundedSlice<_, _> = (&k).try_into().unwrap();
assert_eq!(s, &[1u8, 2, 3, 4][..]);
let j = OldJunction::GeneralKey(vec![1u8, 2, 3, 4].try_into().unwrap());
let k = OldJunction::try_from(Junction::try_from(j.clone()).unwrap()).unwrap();
assert_eq!(j, k);
}
}