Skip to content
This repository has been archived by the owner on Nov 15, 2023. It is now read-only.

AssetsApi with MultiLocation as preparation for multi pallet_assets instances #2187

Merged
merged 3 commits into from
Feb 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ members = [
"parachains/runtimes/testing/rococo-parachain",
"parachains/runtimes/starters/shell",
"parachains/runtimes/starters/seedling",
"parachains/runtimes/assets/common",
"parachains/runtimes/assets/statemint",
"parachains/runtimes/assets/statemine",
"parachains/runtimes/assets/westmint",
Expand Down
40 changes: 40 additions & 0 deletions parachains/runtimes/assets/common/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
[package]
name = "assets-common"
version = "0.1.0"
authors = ["Parity Technologies <admin@parity.io>"]
edition = "2021"
description = "Assets common utilities"

[dependencies]
codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] }

# Substrate
frame-support = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "master" }
sp-api = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "master" }
sp-std = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "master" }

# Polkadot
xcm = { git = "https://github.com/paritytech/polkadot", default-features = false, branch = "master" }
xcm-builder = { git = "https://github.com/paritytech/polkadot", default-features = false, branch = "master" }
xcm-executor = { git = "https://github.com/paritytech/polkadot", default-features = false, branch = "master" }

# Cumulus
parachains-common = { path = "../../../common", default-features = false }

#[dev-dependencies]

[build-dependencies]
substrate-wasm-builder = { git = "https://github.com/paritytech/substrate", branch = "master" }

[features]
default = [ "std" ]
std = [
"codec/std",
"frame-support/std",
"parachains-common/std",
"sp-api/std",
"sp-std/std",
"xcm/std",
"xcm-builder/std",
"xcm-executor/std",
]
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,17 @@

//! Runtime API definition for assets.

use codec::Codec;
use codec::{Codec, Decode, Encode};
use frame_support::RuntimeDebug;
use sp_std::vec::Vec;

/// The possible errors that can happen querying the storage of assets.
#[derive(Eq, PartialEq, Encode, Decode, RuntimeDebug)]
pub enum AssetsAccessError {
/// `MultiLocation` to `AssetId`/`ClassId` conversion failed.
AssetIdConversionFailed,
}

sp_api::decl_runtime_apis! {
pub trait AssetsApi<AccountId, AssetBalance, AssetId>
where
Expand All @@ -29,6 +37,6 @@ sp_api::decl_runtime_apis! {
AssetId: Codec,
{
/// Returns the list of `AssetId`s and corresponding balance that an `AccountId` has.
fn account_balances(account: AccountId) -> Vec<(AssetId, AssetBalance)>;
fn account_balances(account: AccountId) -> Result<Vec<(AssetId, AssetBalance)>, AssetsAccessError>;
}
}
78 changes: 78 additions & 0 deletions parachains/runtimes/assets/common/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// Copyright (C) 2023 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#![cfg_attr(not(feature = "std"), no_std)]

pub mod assets_api;

use parachains_common::AssetIdForTrustBackedAssets;
use sp_std::prelude::Vec;
use xcm::latest::MultiLocation;
use xcm_builder::AsPrefixedGeneralIndex;
use xcm_executor::traits::{Convert, JustTry};

/// [`MultiLocation`] converter for [`TrustBackedAssets`]'s [`AssetIdForTrustBackedAssets`]
pub type AssetIdForTrustBackedAssetsConvert<TrustBackedAssetsPalletLocation> =
AsPrefixedGeneralIndex<TrustBackedAssetsPalletLocation, AssetIdForTrustBackedAssets, JustTry>;

/// Helper function to convert collections with (`AssetId`, 'Balance') to (`MultiLocation`, 'Balance')
pub fn convert_asset_id<AssetId: Clone, Balance, ConvertAssetId>(
assets_balances: Vec<(AssetId, Balance)>,
) -> Result<Vec<(MultiLocation, Balance)>, assets_api::AssetsAccessError>
where
ConvertAssetId: Convert<MultiLocation, AssetId>,
{
assets_balances
.into_iter()
.map(|(asset_id, balance)| {
ConvertAssetId::reverse_ref(asset_id)
.map(|converted_asset_id| (converted_asset_id, balance))
.map_err(|_| assets_api::AssetsAccessError::AssetIdConversionFailed)
})
.collect()
}

#[cfg(test)]
mod tests {

use super::*;
use xcm::latest::prelude::*;

frame_support::parameter_types! {
pub TrustBackedAssetsPalletLocation: MultiLocation = MultiLocation::new(5, X1(PalletInstance(13)));
}

#[test]
fn asset_id_for_trust_backed_assets_convert_works() {
let local_asset_id = 123456789 as AssetIdForTrustBackedAssets;
let expected_reverse_ref =
MultiLocation::new(5, X2(PalletInstance(13), GeneralIndex(local_asset_id.into())));

assert_eq!(
AssetIdForTrustBackedAssetsConvert::<TrustBackedAssetsPalletLocation>::reverse_ref(
local_asset_id
)
.unwrap(),
expected_reverse_ref
);
assert_eq!(
AssetIdForTrustBackedAssetsConvert::<TrustBackedAssetsPalletLocation>::convert_ref(
expected_reverse_ref
)
.unwrap(),
local_asset_id
);
}
}
5 changes: 3 additions & 2 deletions parachains/runtimes/assets/statemine/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ pallet-state-trie-migration = { git = "https://github.com/paritytech/substrate",
# Polkadot
kusama-runtime-constants = { git = "https://github.com/paritytech/polkadot", default-features = false, branch = "master" }
pallet-xcm = { git = "https://github.com/paritytech/polkadot", default-features = false, branch = "master" }
pallet-xcm-benchmarks = { git = "https://github.com/paritytech/polkadot", branch = "master", default-features = false, optional = true }
polkadot-core-primitives = { git = "https://github.com/paritytech/polkadot", default-features = false, branch = "master" }
polkadot-parachain = { git = "https://github.com/paritytech/polkadot", default-features = false, branch = "master" }
polkadot-runtime-common = { git = "https://github.com/paritytech/polkadot", default-features = false, branch = "master" }
Expand All @@ -69,8 +70,7 @@ cumulus-primitives-utility = { path = "../../../../primitives/utility", default-
pallet-collator-selection = { path = "../../../../pallets/collator-selection", default-features = false }
parachain-info = { path = "../../../pallets/parachain-info", default-features = false }
parachains-common = { path = "../../../common", default-features = false }
pallet-xcm-benchmarks = { git = "https://github.com/paritytech/polkadot", branch = "master", default-features = false, optional = true }

assets-common = { path = "../common", default-features = false }

[dev-dependencies]
asset-test-utils = { path = "../test-utils"}
Expand Down Expand Up @@ -187,4 +187,5 @@ std = [
"pallet-collator-selection/std",
"parachain-info/std",
"parachains-common/std",
"assets-common/std",
]
13 changes: 7 additions & 6 deletions parachains/runtimes/assets/statemine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));

pub mod assets_api;
pub mod constants;
mod weights;
pub mod xcm_config;
Expand Down Expand Up @@ -65,7 +64,7 @@ use parachains_common::{
Index, Signature, AVERAGE_ON_INITIALIZE_RATIO, HOURS, MAXIMUM_BLOCK_WEIGHT,
NORMAL_DISPATCH_RATIO, SLOT_DURATION,
};
use xcm_config::{KsmLocation, XcmConfig};
use xcm_config::{AssetIdForTrustBackedAssetsConvert, KsmLocation, XcmConfig};

#[cfg(any(feature = "std", test))]
pub use sp_runtime::BuildStorage;
Expand Down Expand Up @@ -832,15 +831,17 @@ impl_runtime_apis! {
}
}

impl assets_api::AssetsApi<
impl assets_common::assets_api::AssetsApi<
Block,
AccountId,
Balance,
AssetIdForTrustBackedAssets,
xcm::latest::MultiLocation,
> for Runtime
{
fn account_balances(account: AccountId) -> Vec<(AssetIdForTrustBackedAssets, Balance)> {
Assets::account_balances(account)
fn account_balances(account: AccountId) -> Result<Vec<(xcm::latest::MultiLocation, Balance)>, assets_common::assets_api::AssetsAccessError> {
Ok([
assets_common::convert_asset_id::<_, _, AssetIdForTrustBackedAssetsConvert>(Assets::account_balances(account))?,
].concat())
}
}

Expand Down
27 changes: 11 additions & 16 deletions parachains/runtimes/assets/statemine/src/xcm_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,11 @@ use sp_runtime::traits::ConvertInto;
use xcm::latest::prelude::*;
use xcm_builder::{
AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowKnownQueryResponses,
AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, AsPrefixedGeneralIndex,
ConvertedConcreteId, CurrencyAdapter, EnsureXcmOrigin, FungiblesAdapter, IsConcrete, LocalMint,
NativeAsset, ParentAsSuperuser, ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative,
SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32,
SovereignSignedViaLocation, TakeWeightCredit, UsingComponents, WeightInfoBounds,
WithComputedOrigin,
AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, ConvertedConcreteId, CurrencyAdapter,
EnsureXcmOrigin, FungiblesAdapter, IsConcrete, LocalMint, NativeAsset, ParentAsSuperuser,
ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,
SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,
UsingComponents, WeightInfoBounds, WithComputedOrigin,
};
use xcm_executor::{
traits::{JustTry, WithOriginFilter},
Expand Down Expand Up @@ -84,6 +83,10 @@ pub type CurrencyTransactor = CurrencyAdapter<
(),
>;

/// `AssetId` converter for [`AssetIdForTrustBackedAssets`]
pub type AssetIdForTrustBackedAssetsConvert =
assets_common::AssetIdForTrustBackedAssetsConvert<TrustBackedAssetsPalletLocation>;

/// Means for transacting assets besides the native currency on this chain.
pub type FungiblesTransactor = FungiblesAdapter<
// Use this fungibles implementation:
Expand All @@ -92,11 +95,7 @@ pub type FungiblesTransactor = FungiblesAdapter<
ConvertedConcreteId<
AssetIdForTrustBackedAssets,
Balance,
AsPrefixedGeneralIndex<
TrustBackedAssetsPalletLocation,
AssetIdForTrustBackedAssets,
JustTry,
>,
AssetIdForTrustBackedAssetsConvert,
JustTry,
>,
// Convert an XCM MultiLocation into a local account id:
Expand Down Expand Up @@ -305,11 +304,7 @@ impl xcm_executor::Config for XcmConfig {
ConvertedConcreteId<
AssetIdForTrustBackedAssets,
Balance,
AsPrefixedGeneralIndex<
TrustBackedAssetsPalletLocation,
AssetIdForTrustBackedAssets,
JustTry,
>,
AssetIdForTrustBackedAssetsConvert,
JustTry,
>,
Assets,
Expand Down
Loading