xcm_runtime_apis/conversions.rs
1// Copyright (C) Parity Technologies (UK) Ltd.
2// This file is part of Polkadot.
3// SPDX-License-Identifier: Apache-2.0
4
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
17//! Contains runtime APIs for useful conversions, such as between XCM `Location` and `AccountId`.
18
19use codec::{Decode, Encode};
20use scale_info::TypeInfo;
21use xcm::VersionedLocation;
22use xcm_executor::traits::ConvertLocation;
23
24sp_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)]
33pub 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`.
46pub struct LocationToAccountHelper<AccountId, Conversion>(
47 core::marker::PhantomData<(AccountId, Conversion)>,
48);
49impl<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}