1
// Copyright (C) Parity Technologies (UK) Ltd.
2
// This file is part of Polkadot.
3

            
4
// Substrate is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8

            
9
// Substrate is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13

            
14
// You should have received a copy of the GNU General Public License
15
// along with Polkadot.  If not, see <http://www.gnu.org/licenses/>.
16

            
17
//! Contains runtime APIs for useful conversions, such as between XCM `Location` and `AccountId`.
18

            
19
use codec::{Decode, Encode};
20
use scale_info::TypeInfo;
21
use xcm::VersionedLocation;
22
use xcm_executor::traits::ConvertLocation;
23

            
24
sp_api::decl_runtime_apis! {
25
	/// API for useful conversions between XCM `Location` and `AccountId`.
26
	pub trait LocationToAccountApi<AccountId> where AccountId: Decode {
27
		/// Converts `Location` to `AccountId`.
28
		fn convert_location(location: VersionedLocation) -> Result<AccountId, Error>;
29
	}
30
}
31

            
32
#[derive(Copy, Clone, Encode, Decode, Eq, PartialEq, Debug, TypeInfo)]
33
pub enum Error {
34
	/// Requested `Location` is not supported by the local conversion.
35
	#[codec(index = 0)]
36
	Unsupported,
37

            
38
	/// Converting a versioned data structure from one version to another failed.
39
	#[codec(index = 1)]
40
	VersionedConversionFailed,
41
}
42

            
43
/// A helper implementation that can be used for `LocationToAccountApi` implementations.
44
/// It is useful when you already have a `ConvertLocation<AccountId>` implementation and a default
45
/// `Ss58Prefix`.
46
pub struct LocationToAccountHelper<AccountId, Conversion>(
47
	core::marker::PhantomData<(AccountId, Conversion)>,
48
);
49
impl<AccountId: Decode, Conversion: ConvertLocation<AccountId>>
50
	LocationToAccountHelper<AccountId, Conversion>
51
{
52
	pub fn convert_location(location: VersionedLocation) -> Result<AccountId, Error> {
53
		let location = location.try_into().map_err(|_| Error::VersionedConversionFailed)?;
54
		Conversion::convert_location(&location).ok_or(Error::Unsupported)
55
	}
56
}