* cargo fmt

* Create benchmarks for XCM instructions introduced in v3 (#4564)

* Create benchmarks for BurnAsset and ExpectAsset

* Add benchmarks for ExpectOrigin and ExpectError

* Add benchmarks for QueryPallet and ExpectPallet

* Add benchmarks for ReportTransactStatus and ClearTransactStatus

* cargo fmt

* Use AllPalletsWithSystem in mocks

* Update XCM generic benchmarks for westend

* Remove default impls for some XCM weight functions

* Fix compilation error

* Add weight_args helper attribute

* Remove manually written XcmWeightInfo

* Parse trailing comma

* Revert "Add weight_args helper attribute"

This reverts commit 3b7c47a6182e1b9227036c38b406d494c3fcf6fd.

* Fixes

* Fixes

* XCM v3: Introduce querier field into `QueryReponse` (#4732)

* Introduce querier field into QueryReponse

* Convert &Option<MultiLocation> to Option<&MultiLocation>

&Option<T> is almost always never quite useful, most of the time it
still gets converted to an Option<&T> via `as_ref`, so we should simply
make functions that accept Option<&T> instead.

* Fix tests

* cargo fmt

* Fix benchmarks

* Appease spellchecker

* Fix test

* Fix tests

* Fix test

* Fix mock

* Fixes

* Fix tests

* Add test for response queriers

* Update xcm/pallet-xcm/src/lib.rs

* Test for non-existence of querier

Co-authored-by: Keith Yeung <kungfukeith11@gmail.com>

* Fixes

* Fixes

* Add `starts_with` function to `MultiLocation` and `Junctions` (#4835)

* add matches_prefix function to MultiLocation and Junctions

* rename matches_prefix to starts_with

* remove unnecessary main in doc comment

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Make use of starts_with in match_and_split

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>
Co-authored-by: Keith Yeung <kungfukeith11@gmail.com>

* XCM v3: Bridge infrastructure (#4681)

* XCM bridge infrastructure

* Missing bit of cherry-pick

* Revamped XCM proc macros; new NetworkIds

* Fixes

* Formatting

* ExportMessage instruction and config type

* Add MessageExporter definitions

* Formatting

* Missing files

* Fixes

* Initial bridging config API

* Allow for two-stage XCM execution

* Update xcm/src/v3/mod.rs

Co-authored-by: Keith Yeung <kungfukeith11@gmail.com>

* XCM crate building again

* Initial bridging primitive

* Docs

* Docs

* More work

* More work

* Merge branch 'gav-xcm-v3' into gav-xcm-v3-bridging

* Make build

* WithComputedOrigin and SovereignPaidRemoteExporter

* Remove TODOs

* Slim bridge API and tests.

* Fixes

* More work

* First bridge test passing

* Formatting

* Another test

* Next round of bridging tests

* Repot tests

* Cleanups

* Paid bridging

* Formatting

* Tests

* Spelling

* Formatting

* Fees and refactoring

* Fixes

* Formatting

* Refactor SendXcm to become two-phase

* Fix tests

* Refactoring of SendXcm and ExportXcm complete

* Formatting

* Rename CannotReachDestination -> NotApplicable

* Remove XCM v0

* Minor grumbles

* Formatting

* Formatting

* Fixes

* Fixes

* Cleanup XCM config

* Fee handling

* Fixes

* Formatting

* Fixes

* Bump

Co-authored-by: Keith Yeung <kungfukeith11@gmail.com>

* Bump Substrate

* XCM v3: `ExchangeAsset` and Remote-locking (#4945)

* Asset Exchange and Locks

* Make sure XCM typers impl MaxEncodedLen

* Basic implementation for locks

* Bump Substrate

* Missing files

* Use new API

* Introduce  instruction

* Big refactor

* Docs

* Remove deprecated struct

* Remove deprecated struct

* Repot XCM builder tests

* ExchangeAsset test

* Exchange tests

* Locking tests

* Locking tests

* Fixes and tests

* Fixes

* Formatting

* Spelling

* Add simulator test for remote locking

* Fix tests

* Bump

* XCM v3: Support for non-fungibles (#4950)

* NFT support and a test

* New files.

* Integration tests for sending NFTs

* Formatting

* Broken Cargo features

* Use 2021 edition

* Fixes

* Formatting

* Formatting

* Update xcm/xcm-builder/src/asset_conversion.rs

Co-authored-by: Keith Yeung <kungfukeith11@gmail.com>

* Update xcm/xcm-builder/src/nonfungibles_adapter.rs

Co-authored-by: Keith Yeung <kungfukeith11@gmail.com>

* Update xcm/xcm-executor/src/lib.rs

Co-authored-by: Keith Yeung <kungfukeith11@gmail.com>

* Fixes

* Fixes

* Fixes

* Formatting

* Fixes

Co-authored-by: Bastian Köcher <info@kchr.de>
Co-authored-by: Keith Yeung <kungfukeith11@gmail.com>

* XCM v3: Context & ID hash (#4756)

* send_xcm returns message hash

* cargo fmt

* Create topic register and instructions

* Fix weights

* Use tabs

* Sketch out XcmContext

* Fix doc test

* Add the XCM context as a parameter to executor trait fns

* Fixes

* Add XcmContext parameter

* Revert adding context as an arg to SendXcm trait methods

* Revert adding context argument to ConvertOrigin trait methods

* cargo fmt

* Do not change the API of XcmExecutor::execute

* Fixes

* Fixes

* Fixes

* Fixes

* Remove convenience method

* Fixes

* Fixes

* cargo fmt

* Fixes

* Add benchmarks for XCM topic instructions

* cargo run --quiet --profile=production  --features=runtime-benchmarks -- benchmark --chain=westend-dev --steps=50 --repeat=20 --pallet=pallet_xcm_benchmarks::generic --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --header=./file_header.txt --template=./xcm/pallet-xcm-benchmarks/template.hbs --output=./runtime/westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs

* Remove context argument on FilterAssetLocation

* Fixes

* Remove unused import

* Fixes

* Fixes

* Fixes

* Accept XCM hash parameter in ExecuteXcm trait methods

* cargo fmt

* Properly enable sp-io/std

* Fixes

* default-features = false

* Fixes

* Fixes

* Fixes

* Make XcmContext optional in withdraw_asset

* Fixes

* Fixes

* Fixes

* Modify tests to check for the correct XCM hash

* Small refactor

* cargo fmt

* Check for expected hash in xcm-builder unit tests

* Add doc comment for the optionality of the XCM context in withdraw_asset

* Update xcm/src/v3/traits.rs

* Update xcm/src/v3/traits.rs

* Store XcmContext and avoid rebuilding

* Use ref for XcmContext

* Formatting

* Fix incorrect hash CC @KiChjang

* Refactor and make clear fake hashes

* Fixes

* Fixes

* Fixes

* Fix broken hashing

* Docs

* Fixes

* Fixes

* Fixes

* Formatting

* Fixes

* Fixes

* Fixes

* Remove unknowable hash

* Formatting

* Use message hash for greater identifiability

* Formatting

* Fixes

* Formatting

Co-authored-by: Keith Yeung <kungfukeith11@gmail.com>
Co-authored-by: Parity Bot <admin@parity.io>

* Fixes

* Fixes

* Fixes

* Fixes

* Formatting

* Fixes

* Formatting

* Fixes

* Fixes

* Formatting

* Formatting

* Remove horrible names

* Bump

* Remove InvertLocation trait (#5092)

* Remove InvertLocation trait

* Remove unneeded functions

* Formatting

* Fixes

* Remove XCMv1 (#5094)

* Remove XCMv1

* Remove XCMv1

* Formatting

* Fixes

* Fixes

* Formatting

* derive serialize/deserialize for xcm primitives (#5036)

* derive serialize/deserialize for xcm primitives

* derive serialize/deserialize for xcm primitives

* update v3

* update v2

Co-authored-by: Gav Wood <gavin@parity.io>

* Update lock

* Fixes

* Add benchmarks for the ExchangeAsset instruction

* `AliasOrigin` instruction stub (#5122)

* AliasOrigin instruction stub

* Fixes

* Fixes

* Update substrate

* Fixes

* Ensure same array length before using copy_from_slice

* Fixes

* Add benchmarks for the UniversalOrigin instruction

* Remove unused import

* Remove unused import

* Add benchmarks for SetFeesMode instruction

* Add benchmarks for asset (un)locking instructions

* Leave AliasOrigin unbenchmarked

* Fixes after merge

* cargo fmt

* Fixes

* Fixes

* Set TrustedReserves to None on both Kusama and Westend

* Remove extraneous reserve_asset_deposited benchmark

* Fix universal_origin benchmark

* cargo run --quiet --profile=production  --features=runtime-benchmarks -- benchmark pallet --chain=westend-dev --steps=50 --repeat=20 --pallet=pallet_xcm_benchmarks::generic --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --header=./file_header.txt --template=./xcm/pallet-xcm-benchmarks/template.hbs --output=./runtime/westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs

* Don't rely on skipped benchmark functions

* Fixes

* cargo run --quiet --profile=production  --features=runtime-benchmarks -- benchmark pallet --chain=kusama-dev --steps=50 --repeat=20 --pallet=pallet_xcm_benchmarks::generic --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --header=./file_header.txt --template=./xcm/pallet-xcm-benchmarks/template.hbs --output=./runtime/kusama/src/weights/xcm/pallet_xcm_benchmarks_generic.rs

* Fix unused variables

* Fixes

* Spelling

* Fixes

* Fix codec index of VersionedXcm

* Allows to customize how calls are dispatched from XCM (#5657)

* CallDispatcher trait

* fmt

* unused import

* fix test-runtime

* remove JustDispatch type

* fix typo in test-runtime

* missing CallDispatcher

* more missing CallDispatcher

* Update comment `NoteAssetLocked` -> `NoteUnlockable`

* Fixes

* Fixes

* Adjust MultiAssets weights based on new wild card variants

* Fixes

* Fixes

* Fixes

* Fixes

* Fixes

* Some late fixes for XCMv3 (#5237)

* Maximise chances that trapped assets can be reclaimed

* Do origin check as part of ExportMessage for security

* Formatting

* Fixes

* Cleanup export XCM APIs

* Formatting

* Update xcm/src/v3/junctions.rs

* UnpaidExecution instruction and associated barrier.

* Tighten barriers (ClearOrigin/QueryResponse)

* Allow only 1 ClearOrigin instruction in AllowTopLevelPaidExecutionFrom

* Bi-directional teleport accounting

* Revert other fix

* Build fixes]

* Tests build

* Benchmark fixes

Co-authored-by: Keith Yeung <kungfukeith11@gmail.com>

* Update Substrate

* Re-export `pub` stuff from universal_exports.rs + removed unecessary clone (#6145)

* Re-export `pub` stuff from universal_exports.rs

* Removed unnecessary clone

* Use 2D weights in XCM v3 (#6134)

* Depend upon sp-core instead of sp-runtime

* Make sp-io a dev-dependency

* Use 2D weights in XCM v3

* cargo fmt

* Add XCM pallet migration to runtimes

* Use from_parts

* cargo fmt

* Fixes

* cargo fmt

* Remove XCMWeight import

* Fixes

* Fixes

* Fixes

* Fixes

* Use translate in migration

* Increase max upward message size in tests

* Fix doc test

* Remove most uses of from_ref_time

* cargo fmt

* Fixes

* Fixes

* Add extrinsic benchmarking to XCM pallet

* cargo fmt

* Fixes

* Use old syntax

* cargo fmt

* Fixes

* Remove hardcoded weights

* Add XCM pallet to benchmarks

* Use successful origin

* Fix weird type parameter compilation issue

* Fixes

* ".git/.scripts/bench-bot.sh" runtime westend-dev pallet_xcm

* ".git/.scripts/bench-bot.sh" runtime rococo-dev pallet_xcm

* ".git/.scripts/bench-bot.sh" runtime kusama-dev pallet_xcm

* ".git/.scripts/bench-bot.sh" runtime polkadot-dev pallet_xcm

* Use benchmarked XCM pallet weights

* Fixes

* Fixes

* Use override instead of skip

* Fixes

* Fixes

* Fixes

* Fixes

* ".git/.scripts/bench-bot.sh" runtime polkadot-dev pallet_xcm

* Fixes

* ".git/.scripts/bench-bot.sh" runtime polkadot-dev pallet_xcm

* ".git/.scripts/bench-bot.sh" runtime westend-dev pallet_xcm

Co-authored-by: command-bot <>

* Replace Weight::MAX with 100b weight units

* Add test to ensure all_gte in barriers is correct

* Update xcm/src/v3/junction.rs

Co-authored-by: asynchronous rob <rphmeier@gmail.com>

* Add more weight tests

* cargo fmt

* Create thread_local in XCM executor to limit recursion depth (#6304)

* Create thread_local in XCM executor to limit recursion depth

* Add unit test for recursion limit

* Fix statefulness in tests

* Remove panic

* Use defer and environmental macro

* Fix the implementation

* Use nicer interface

* Change ThisNetwork to AnyNetwork

* Move recursion check up to top level

* cargo fmt

* Update comment

Co-authored-by: Bastian Köcher <info@kchr.de>

* Add upper limit on the number of overweight messages in the queue (#6298)

* Add upper limit on the number of ovwerweight messages in the queue

* Add newline

* Introduce whitelist for Transact and limit UMP processing to 10 messages per block (#6280)

* Add SafeCallFilter to XcmConfig

* Limit UMP to receive 10 messages every block

* Place 10 message limit on processing instead of receiving

* Always increment the message_processed count whenever a message is processed

* Add as_derivative to the Transact whitelist

* cargo fmt

* Fixes

* Update xcm/xcm-builder/src/universal_exports.rs

Co-authored-by: Branislav Kontur <bkontur@gmail.com>

* Fixes

* Fixes

* Remove topic register and instead use the topic field in XcmContext

* Derive some common traits for DispatchBlobError

* Fixes

* cargo fmt

* Fixes

* Fixes

* Fix comments

* Fixes

* Introduce WithOriginFilter and apply it as the CallDispatcher for runtimes

* Fixes

* Appease clippy and fixes

* Fixes

* Fix more clippy issues

* Fixes

* ".git/.scripts/bench-bot.sh" runtime polkadot-dev pallet_xcm

* ".git/.scripts/bench-bot.sh" runtime westend-dev pallet_xcm

* ".git/.scripts/bench-bot.sh" runtime westend-dev pallet_xcm

* Add benchmark function for ExportMessage

* Fix comment

* Add upper limit to DownwardMessageQueues size

* Add max size check for queue in can_queue_downward_message

* Fixes

* Make Transact runtime call configurable

* Return Weight::MAX when there is no successful send XCM origin

* Update substrate

* Fixes

* Fixes

* Remove ExportMessage benchmark

* Remove assertion on Transact instruction benchmark

* Make reachable destination configurable in XCM pallet benchmarks

* Fixes

* Fixes

* Remove cfg attribute in fuzzer

* Fixes

* Remove cfg attribute for XCM pallet in test runtime

* Fixes

* Use ReachableDest where possible

* Fixes

* Add benchmark for UnpaidExecution

* Update substrate

* Ensure benchmark functions pass filters

* Add runtime-benchmarks feature to fuzzer

* Ensure FixedRateOfFungible accounts for proof size weights

* cargo fmt

* Whitelist remark_with_event when runtime-benchmarks feature is enabled

* Use remark_with_event for Transact benchmarks

* Fix Cargo.lock

* Allow up to 3 DescendOrigin instructions before UnpaidExecution

* cargo fmt

* Edit code comment

* Check check_origin for unpaid execution privilege

* Fixes

* Small nits for xcm-v3 (#6408)

* Add possibility to skip benchmark for export_message

* ".git/.scripts/bench-bot.sh" xcm westend-dev pallet_xcm_benchmarks::generic

* Revert

* ".git/.scripts/bench-bot.sh" xcm westend-dev pallet_xcm_benchmarks::generic

* Add HaulBlobError to `fn haul_blob`

* ".git/.scripts/bench-bot.sh" xcm westend-dev pallet_xcm_benchmarks::generic

Co-authored-by: command-bot <>

* Revert changes to UnpaidExecution

* Change AllowUnpaidExecutionFrom to be explicit

* Fix log text

* cargo fmt

* Add benchmarks for XCM pallet version migration (#6448)

* Add benchmarks for XCM pallet version migration

* cargo fmt

* Fixes

* Fixes

* Fixes

* ".git/.scripts/bench-bot.sh" runtime westend-dev pallet_xcm

* ".git/.scripts/bench-bot.sh" runtime kusama-dev pallet_xcm

* ".git/.scripts/bench-bot.sh" runtime rococo-dev pallet_xcm

* ".git/.scripts/bench-bot.sh" runtime polkadot-dev pallet_xcm

* Fix benchmarks

* Fix benchmarks

* ".git/.scripts/bench-bot.sh" runtime westend-dev pallet_xcm

* ".git/.scripts/bench-bot.sh" runtime kusama-dev pallet_xcm

* ".git/.scripts/bench-bot.sh" runtime rococo-dev pallet_xcm

* ".git/.scripts/bench-bot.sh" runtime polkadot-dev pallet_xcm

Co-authored-by: command-bot <>

* Merge remote-tracking branch 'origin/master' into gav-xcm-v3

* Fixes

* Fix comments (#6470)

* Specify Ethereum networks by their chain id (#6286)

Co-authored-by: Squirrel <gilescope@gmail.com>

* Use  for Kusama

* Use WithComputedOrigin for Polkadot, Rococo and Westend

* Update lock

* Fix warning

* Update xcm/pallet-xcm/src/tests.rs

Co-authored-by: Squirrel <gilescope@gmail.com>

* Update runtime/parachains/src/ump/migration.rs

Co-authored-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>

* Update xcm/pallet-xcm/src/migration.rs

Co-authored-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>

* Fixes

* cargo fmt

* Typo

* Update xcm/src/v3/mod.rs

Co-authored-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>

* Docs

* Docs

* Docs

* Docs

* Docs

* Update xcm/src/v3/multiasset.rs

Co-authored-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>

* Add tests for MultiAssets::from_sorted_and_deduplicated

* Fail gracefully when same instance NFTs are detected during push

* Update Substrate to fix benchmarks

* Apply suggestions from code review

* Update runtime/kusama/src/xcm_config.rs

* Rename arguments

* Attempt to fix benchmark

* ".git/.scripts/commands/bench/bench.sh" runtime polkadot-dev runtime_parachains::ump

* Use actual weights for UMP pallet in Polkadot

* ".git/.scripts/commands/bench/bench.sh" runtime kusama-dev runtime_parachains::ump

* ".git/.scripts/commands/bench/bench.sh" runtime westend-dev runtime_parachains::ump

* ".git/.scripts/commands/bench/bench.sh" runtime rococo-dev runtime_parachains::ump

Co-authored-by: Keith Yeung <kungfukeith11@gmail.com>
Co-authored-by: Alexander Popiak <alexander.popiak@parity.io>
Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>
Co-authored-by: Bastian Köcher <info@kchr.de>
Co-authored-by: Parity Bot <admin@parity.io>
Co-authored-by: stanly-johnson <stanlyjohnson@outlook.com>
Co-authored-by: nanocryk <6422796+nanocryk@users.noreply.github.com>
Co-authored-by: Branislav Kontur <bkontur@gmail.com>
Co-authored-by: asynchronous rob <rphmeier@gmail.com>
Co-authored-by: command-bot <>
Co-authored-by: Vincent Geddes <vincent.geddes@hey.com>
Co-authored-by: Squirrel <gilescope@gmail.com>
Co-authored-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>
Co-authored-by: Shawn Tabrizi <shawntabrizi@gmail.com>
This commit is contained in:
Gavin Wood
2023-01-17 04:04:34 -03:00
committed by GitHub
parent 2952ad6f44
commit 1a1bfd2af9
155 changed files with 19234 additions and 8436 deletions
+203 -62
View File
@@ -23,9 +23,9 @@ use sp_std::{
use xcm::latest::{
AssetId, AssetInstance,
Fungibility::{Fungible, NonFungible},
MultiAsset, MultiAssetFilter, MultiAssets, MultiLocation,
InteriorMultiLocation, MultiAsset, MultiAssetFilter, MultiAssets, MultiLocation,
WildFungibility::{Fungible as WildFungible, NonFungible as WildNonFungible},
WildMultiAsset::{All, AllOf},
WildMultiAsset::{All, AllCounted, AllOf, AllOfCounted},
};
/// List of non-wildcard fungible and non-fungible assets.
@@ -60,7 +60,7 @@ impl From<Vec<MultiAsset>> for Assets {
impl From<MultiAssets> for Assets {
fn from(assets: MultiAssets) -> Assets {
assets.drain().into()
assets.into_inner().into()
}
}
@@ -103,14 +103,14 @@ impl Assets {
pub fn fungible_assets_iter(&self) -> impl Iterator<Item = MultiAsset> + '_ {
self.fungible
.iter()
.map(|(id, &amount)| MultiAsset { fun: Fungible(amount), id: id.clone() })
.map(|(id, &amount)| MultiAsset { fun: Fungible(amount), id: *id })
}
/// A borrowing iterator over the non-fungible assets.
pub fn non_fungible_assets_iter(&self) -> impl Iterator<Item = MultiAsset> + '_ {
self.non_fungible
.iter()
.map(|(id, instance)| MultiAsset { fun: NonFungible(instance.clone()), id: id.clone() })
.map(|(id, instance)| MultiAsset { fun: NonFungible(*instance), id: *id })
}
/// A consuming iterator over all assets.
@@ -210,20 +210,20 @@ impl Assets {
}
/// Mutate the assets to be interpreted as the same assets from the perspective of a `target`
/// chain. The local chain's `ancestry` is provided.
/// chain. The local chain's `context` is provided.
///
/// Any assets which were unable to be reanchored are introduced into `failed_bin`.
pub fn reanchor(
&mut self,
target: &MultiLocation,
ancestry: &MultiLocation,
context: InteriorMultiLocation,
mut maybe_failed_bin: Option<&mut Self>,
) {
let mut fungible = Default::default();
mem::swap(&mut self.fungible, &mut fungible);
self.fungible = fungible
.into_iter()
.filter_map(|(mut id, amount)| match id.reanchor(target, ancestry) {
.filter_map(|(mut id, amount)| match id.reanchor(target, context) {
Ok(()) => Some((id, amount)),
Err(()) => {
maybe_failed_bin.as_mut().map(|f| f.fungible.insert(id, amount));
@@ -235,7 +235,7 @@ impl Assets {
mem::swap(&mut self.non_fungible, &mut non_fungible);
self.non_fungible = non_fungible
.into_iter()
.filter_map(|(mut class, inst)| match class.reanchor(target, ancestry) {
.filter_map(|(mut class, inst)| match class.reanchor(target, context) {
Ok(()) => Some((class, inst)),
Err(()) => {
maybe_failed_bin.as_mut().map(|f| f.non_fungible.insert((class, inst)));
@@ -245,18 +245,42 @@ impl Assets {
.collect();
}
/// Returns `true` if `asset` is contained within `self`.
pub fn contains_asset(&self, asset: &MultiAsset) -> bool {
match asset {
MultiAsset { fun: Fungible(amount), id } =>
self.fungible.get(id).map_or(false, |a| a >= amount),
MultiAsset { fun: NonFungible(instance), id } =>
self.non_fungible.contains(&(*id, *instance)),
}
}
/// Returns `true` if all `assets` are contained within `self`.
pub fn contains_assets(&self, assets: &MultiAssets) -> bool {
assets.inner().iter().all(|a| self.contains_asset(a))
}
/// Returns `true` if all `assets` are contained within `self`.
pub fn contains(&self, assets: &Assets) -> bool {
assets
.fungible
.iter()
.all(|(k, v)| self.fungible.get(k).map_or(false, |a| a >= v)) &&
self.non_fungible.is_superset(&assets.non_fungible)
}
/// Returns an error unless all `assets` are contained in `self`. In the case of an error, the first asset in
/// `assets` which is not wholly in `self` is returned.
pub fn ensure_contains(&self, assets: &MultiAssets) -> Result<(), TakeError> {
for asset in assets.inner().iter() {
match asset {
MultiAsset { fun: Fungible(ref amount), ref id } => {
MultiAsset { fun: Fungible(amount), id } => {
if self.fungible.get(id).map_or(true, |a| a < amount) {
return Err(TakeError::AssetUnderflow((id.clone(), *amount).into()))
return Err(TakeError::AssetUnderflow((*id, *amount).into()))
}
},
MultiAsset { fun: NonFungible(ref instance), ref id } => {
let id_instance = (id.clone(), instance.clone());
MultiAsset { fun: NonFungible(instance), id } => {
let id_instance = (*id, *instance);
if !self.non_fungible.contains(&id_instance) {
return Err(TakeError::AssetUnderflow(id_instance.into()))
}
@@ -272,7 +296,8 @@ impl Assets {
/// reducing it by assets it does not contain. In this case, the function is infallible. If `saturate` is `false`
/// and `mask` references a definite asset which `self` does not contain then an error is returned.
///
/// The number of unique assets which are removed will never be any greater than `limit`.
/// The number of unique assets which are removed will respect the `count` parameter in the
/// counted wildcard variants.
///
/// Returns `Ok` with the definite assets token from `self` and mutates `self` to its value minus
/// `mask`. Returns `Err` in the non-saturating case where `self` did not contain (enough of) a definite asset to
@@ -281,17 +306,18 @@ impl Assets {
&mut self,
mask: MultiAssetFilter,
saturate: bool,
limit: usize,
) -> Result<Assets, TakeError> {
let mut taken = Assets::new();
let maybe_limit = mask.limit().map(|x| x as usize);
match mask {
MultiAssetFilter::Wild(All) =>
if self.fungible.len() + self.non_fungible.len() <= limit {
// TODO: Counted variants where we define `limit`.
MultiAssetFilter::Wild(All) | MultiAssetFilter::Wild(AllCounted(_)) => {
if maybe_limit.map_or(true, |l| self.len() <= l) {
return Ok(self.swapped(Assets::new()))
} else {
let fungible = mem::replace(&mut self.fungible, Default::default());
fungible.into_iter().for_each(|(c, amount)| {
if taken.len() < limit {
if maybe_limit.map_or(true, |l| taken.len() < l) {
taken.fungible.insert(c, amount);
} else {
self.fungible.insert(c, amount);
@@ -299,22 +325,26 @@ impl Assets {
});
let non_fungible = mem::replace(&mut self.non_fungible, Default::default());
non_fungible.into_iter().for_each(|(c, instance)| {
if taken.len() < limit {
if maybe_limit.map_or(true, |l| taken.len() < l) {
taken.non_fungible.insert((c, instance));
} else {
self.non_fungible.insert((c, instance));
}
});
},
MultiAssetFilter::Wild(AllOf { fun: WildFungible, id }) => {
if let Some((id, amount)) = self.fungible.remove_entry(&id) {
taken.fungible.insert(id, amount);
}
},
MultiAssetFilter::Wild(AllOfCounted { fun: WildFungible, id, .. }) |
MultiAssetFilter::Wild(AllOf { fun: WildFungible, id }) =>
if maybe_limit.map_or(true, |l| l >= 1) {
if let Some((id, amount)) = self.fungible.remove_entry(&id) {
taken.fungible.insert(id, amount);
}
},
MultiAssetFilter::Wild(AllOfCounted { fun: WildNonFungible, id, .. }) |
MultiAssetFilter::Wild(AllOf { fun: WildNonFungible, id }) => {
let non_fungible = mem::replace(&mut self.non_fungible, Default::default());
non_fungible.into_iter().for_each(|(c, instance)| {
if c == id && taken.len() < limit {
if c == id && maybe_limit.map_or(true, |l| taken.len() < l) {
taken.non_fungible.insert((c, instance));
} else {
self.non_fungible.insert((c, instance));
@@ -325,7 +355,7 @@ impl Assets {
if !saturate {
self.ensure_contains(&assets)?;
}
for asset in assets.drain().into_iter() {
for asset in assets.into_inner().into_iter() {
match asset {
MultiAsset { fun: Fungible(amount), id } => {
let (remove, amount) = match self.fungible.get_mut(&id) {
@@ -350,9 +380,6 @@ impl Assets {
}
},
}
if taken.len() == limit {
break
}
}
},
}
@@ -364,16 +391,7 @@ impl Assets {
/// Returns `Ok` with the non-wildcard equivalence of `mask` taken and mutates `self` to its value minus
/// `mask` if `self` contains `asset`, and return `Err` otherwise.
pub fn saturating_take(&mut self, asset: MultiAssetFilter) -> Assets {
self.general_take(asset, true, usize::max_value())
.expect("general_take never results in error when saturating")
}
/// Mutates `self` to its original value less `mask` and returns `true` iff it contains at least `mask`.
///
/// Returns `Ok` with the non-wildcard equivalence of `mask` taken and mutates `self` to its value minus
/// `mask` if `self` contains `asset`, and return `Err` otherwise.
pub fn limited_saturating_take(&mut self, asset: MultiAssetFilter, limit: usize) -> Assets {
self.general_take(asset, true, limit)
self.general_take(asset, true)
.expect("general_take never results in error when saturating")
}
@@ -382,7 +400,7 @@ impl Assets {
/// Returns `Ok` with the non-wildcard equivalence of `asset` taken and mutates `self` to its value minus
/// `asset` if `self` contains `asset`, and return `Err` otherwise.
pub fn try_take(&mut self, mask: MultiAssetFilter) -> Result<Assets, TakeError> {
self.general_take(mask, false, usize::max_value())
self.general_take(mask, false)
}
/// Consumes `self` and returns its original value excluding `asset` iff it contains at least `asset`.
@@ -415,47 +433,72 @@ impl Assets {
/// Return the assets in `self`, but (asset-wise) of no greater value than `mask`.
///
/// Result is undefined if `mask` includes elements which match to the same asset more than once.
/// The number of unique assets which are returned will respect the `count` parameter in the
/// counted wildcard variants of `mask`.
///
/// Example:
///
/// ```
/// use xcm_executor::Assets;
/// use xcm::latest::prelude::*;
/// let assets_i_have: Assets = vec![ (Here, 100).into(), (vec![0], 100).into() ].into();
/// let assets_they_want: MultiAssetFilter = vec![ (Here, 200).into(), (vec![0], 50).into() ].into();
/// let assets_i_have: Assets = vec![ (Here, 100).into(), ([0; 32], 100).into() ].into();
/// let assets_they_want: MultiAssetFilter = vec![ (Here, 200).into(), ([0; 32], 50).into() ].into();
///
/// let assets_we_can_trade: Assets = assets_i_have.min(&assets_they_want);
/// assert_eq!(assets_we_can_trade.into_assets_iter().collect::<Vec<_>>(), vec![
/// (Here, 100).into(), (vec![0], 50).into(),
/// (Here, 100).into(), ([0; 32], 50).into(),
/// ]);
/// ```
pub fn min(&self, mask: &MultiAssetFilter) -> Assets {
let mut masked = Assets::new();
let maybe_limit = mask.limit().map(|x| x as usize);
if maybe_limit.map_or(false, |l| l == 0) {
return masked
}
match mask {
MultiAssetFilter::Wild(All) => return self.clone(),
MultiAssetFilter::Wild(AllOf { fun: WildFungible, id }) => {
if let Some(&amount) = self.fungible.get(&id) {
masked.fungible.insert(id.clone(), amount);
MultiAssetFilter::Wild(All) | MultiAssetFilter::Wild(AllCounted(_)) => {
if maybe_limit.map_or(true, |l| self.len() <= l) {
return self.clone()
} else {
for (&c, &amount) in self.fungible.iter() {
masked.fungible.insert(c, amount);
if maybe_limit.map_or(false, |l| masked.len() >= l) {
return masked
}
}
for (c, instance) in self.non_fungible.iter() {
masked.non_fungible.insert((*c, *instance));
if maybe_limit.map_or(false, |l| masked.len() >= l) {
return masked
}
}
}
},
MultiAssetFilter::Wild(AllOf { fun: WildNonFungible, id }) => {
self.non_fungible.iter().for_each(|(ref c, ref instance)| {
MultiAssetFilter::Wild(AllOfCounted { fun: WildFungible, id, .. }) |
MultiAssetFilter::Wild(AllOf { fun: WildFungible, id }) =>
if let Some(&amount) = self.fungible.get(&id) {
masked.fungible.insert(*id, amount);
},
MultiAssetFilter::Wild(AllOfCounted { fun: WildNonFungible, id, .. }) |
MultiAssetFilter::Wild(AllOf { fun: WildNonFungible, id }) =>
for (c, instance) in self.non_fungible.iter() {
if c == id {
masked.non_fungible.insert((c.clone(), instance.clone()));
masked.non_fungible.insert((*c, *instance));
if maybe_limit.map_or(false, |l| masked.len() >= l) {
return masked
}
}
});
},
},
MultiAssetFilter::Definite(assets) =>
for asset in assets.inner().iter() {
match asset {
MultiAsset { fun: Fungible(ref amount), ref id } => {
MultiAsset { fun: Fungible(amount), id } => {
if let Some(m) = self.fungible.get(id) {
masked.subsume((id.clone(), Fungible(*amount.min(m))).into());
masked.subsume((*id, Fungible(*amount.min(m))).into());
}
},
MultiAsset { fun: NonFungible(ref instance), ref id } => {
let id_instance = (id.clone(), instance.clone());
MultiAsset { fun: NonFungible(instance), id } => {
let id_instance = (*id, *instance);
if self.non_fungible.contains(&id_instance) {
masked.subsume(id_instance.into());
}
@@ -474,12 +517,12 @@ mod tests {
#[allow(non_snake_case)]
/// Abstract fungible constructor
fn AF(id: u8, amount: u128) -> MultiAsset {
(vec![id], amount).into()
([id; 32], amount).into()
}
#[allow(non_snake_case)]
/// Abstract non-fungible constructor
fn ANF(class: u8, instance_id: u8) -> MultiAsset {
(vec![class], vec![instance_id]).into()
([class; 32], [instance_id; 4]).into()
}
#[allow(non_snake_case)]
/// Concrete fungible constructor
@@ -586,11 +629,38 @@ mod tests {
assert!(all_min.assets_iter().eq(assets.assets_iter()));
}
#[test]
fn min_counted_works() {
let mut assets = Assets::new();
assets.subsume(AF(1, 100));
assets.subsume(ANF(2, 20));
assets.subsume(CNF(40));
assets.subsume(AF(10, 50));
assets.subsume(ANF(2, 40));
assets.subsume(ANF(2, 30));
assets.subsume(CF(3000));
assets.subsume(CNF(80));
assets.subsume(ANF(3, 10));
let fungible = WildMultiAsset::from(([1u8; 32], WildFungible)).counted(2).into();
let non_fungible = WildMultiAsset::from(([2u8; 32], WildNonFungible)).counted(2).into();
let all = WildMultiAsset::AllCounted(6).into();
let fungible = assets.min(&fungible);
let fungible = fungible.assets_iter().collect::<Vec<_>>();
assert_eq!(fungible, vec![AF(1, 100)]);
let non_fungible = assets.min(&non_fungible);
let non_fungible = non_fungible.assets_iter().collect::<Vec<_>>();
assert_eq!(non_fungible, vec![ANF(2, 20), ANF(2, 30)]);
let all = assets.min(&all);
let all = all.assets_iter().collect::<Vec<_>>();
assert_eq!(all, vec![CF(3000), AF(1, 100), AF(10, 50), CNF(40), CNF(80), ANF(2, 20),]);
}
#[test]
fn min_all_abstract_works() {
let assets = test_assets();
let fungible = Wild((vec![1], WildFungible).into());
let non_fungible = Wild((vec![2], WildNonFungible).into());
let fungible = Wild(([1u8; 32], WildFungible).into());
let non_fungible = Wild(([2u8; 32], WildNonFungible).into());
let fungible = assets.min(&fungible);
let fungible = fungible.assets_iter().collect::<Vec<_>>();
@@ -650,8 +720,8 @@ mod tests {
#[test]
fn saturating_take_all_abstract_works() {
let mut assets = test_assets();
let fungible = Wild((vec![1], WildFungible).into());
let non_fungible = Wild((vec![2], WildNonFungible).into());
let fungible = Wild(([1u8; 32], WildFungible).into());
let non_fungible = Wild(([2u8; 32], WildNonFungible).into());
let fungible = assets.saturating_take(fungible);
let fungible = fungible.assets_iter().collect::<Vec<_>>();
@@ -703,4 +773,75 @@ mod tests {
let assets = assets1.into_assets_iter().collect::<Vec<_>>();
assert_eq!(assets, vec![AF(1, 50), ANF(2, 20)]);
}
#[test]
fn try_take_all_counted_works() {
let mut assets = Assets::new();
assets.subsume(AF(1, 100));
assets.subsume(ANF(2, 20));
assets.subsume(CNF(40));
assets.subsume(AF(10, 50));
assets.subsume(ANF(2, 40));
assets.subsume(ANF(2, 30));
assets.subsume(CF(3000));
assets.subsume(CNF(80));
assets.subsume(ANF(3, 10));
let all = assets.try_take(WildMultiAsset::AllCounted(6).into()).unwrap();
assert_eq!(
MultiAssets::from(all).inner(),
&vec![CF(3000), AF(1, 100), AF(10, 50), CNF(40), CNF(80), ANF(2, 20),]
);
assert_eq!(MultiAssets::from(assets).inner(), &vec![ANF(2, 30), ANF(2, 40), ANF(3, 10),]);
}
#[test]
fn try_take_fungibles_counted_works() {
let mut assets = Assets::new();
assets.subsume(AF(1, 100));
assets.subsume(ANF(2, 20));
assets.subsume(CNF(40));
assets.subsume(AF(10, 50));
assets.subsume(ANF(2, 40));
assets.subsume(ANF(2, 30));
assets.subsume(CF(3000));
assets.subsume(CNF(80));
assets.subsume(ANF(3, 10));
let mask = WildMultiAsset::from(([1u8; 32], WildFungible)).counted(2).into();
let taken = assets.try_take(mask).unwrap();
assert_eq!(MultiAssets::from(taken).inner(), &vec![AF(1, 100)]);
assert_eq!(
MultiAssets::from(assets).inner(),
&vec![
CF(3000),
AF(10, 50),
CNF(40),
CNF(80),
ANF(2, 20),
ANF(2, 30),
ANF(2, 40),
ANF(3, 10),
]
);
}
#[test]
fn try_take_non_fungibles_counted_works() {
let mut assets = Assets::new();
assets.subsume(AF(1, 100));
assets.subsume(ANF(2, 20));
assets.subsume(CNF(40));
assets.subsume(AF(10, 50));
assets.subsume(ANF(2, 40));
assets.subsume(ANF(2, 30));
assets.subsume(CF(3000));
assets.subsume(CNF(80));
assets.subsume(ANF(3, 10));
let mask = WildMultiAsset::from(([2u8; 32], WildNonFungible)).counted(2).into();
let taken = assets.try_take(mask).unwrap();
assert_eq!(MultiAssets::from(taken).inner(), &vec![ANF(2, 20), ANF(2, 30),]);
assert_eq!(
MultiAssets::from(assets).inner(),
&vec![CF(3000), AF(1, 100), AF(10, 50), CNF(40), CNF(80), ANF(2, 40), ANF(3, 10),]
);
}
}
+51 -10
View File
@@ -15,11 +15,15 @@
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
use crate::traits::{
ClaimAssets, ConvertOrigin, DropAssets, FilterAssetLocation, InvertLocation, OnResponse,
ShouldExecute, TransactAsset, VersionChangeNotifier, WeightBounds, WeightTrader,
AssetExchange, AssetLock, CallDispatcher, ClaimAssets, ConvertOrigin, DropAssets, ExportXcm,
FeeManager, OnResponse, ShouldExecute, TransactAsset, VersionChangeNotifier, WeightBounds,
WeightTrader,
};
use frame_support::dispatch::{Dispatchable, GetDispatchInfo, Parameter, PostDispatchInfo};
use xcm::latest::SendXcm;
use frame_support::{
dispatch::{Dispatchable, GetDispatchInfo, Parameter, PostDispatchInfo},
traits::{Contains, ContainsPair, Get, PalletsInfoAccess},
};
use xcm::prelude::*;
/// The trait to parameterize the `XcmExecutor`.
pub trait Config {
@@ -35,14 +39,14 @@ pub trait Config {
/// How to get a call origin from a `OriginKind` value.
type OriginConverter: ConvertOrigin<<Self::RuntimeCall as Dispatchable>::RuntimeOrigin>;
/// Combinations of (Location, Asset) pairs which we trust as reserves.
type IsReserve: FilterAssetLocation;
/// Combinations of (Asset, Location) pairs which we trust as reserves.
type IsReserve: ContainsPair<MultiAsset, MultiLocation>;
/// Combinations of (Location, Asset) pairs which we trust as teleporters.
type IsTeleporter: FilterAssetLocation;
/// Combinations of (Asset, Location) pairs which we trust as teleporters.
type IsTeleporter: ContainsPair<MultiAsset, MultiLocation>;
/// Means of inverting a location.
type LocationInverter: InvertLocation;
/// This chain's Universal Location.
type UniversalLocation: Get<InteriorMultiLocation>;
/// Whether we should execute the given XCM at all.
type Barrier: ShouldExecute;
@@ -60,9 +64,46 @@ pub trait Config {
/// end of execution.
type AssetTrap: DropAssets;
/// Handler for asset locking.
type AssetLocker: AssetLock;
/// Handler for exchanging assets.
type AssetExchanger: AssetExchange;
/// The handler for when there is an instruction to claim assets.
type AssetClaims: ClaimAssets;
/// How we handle version subscription requests.
type SubscriptionService: VersionChangeNotifier;
/// Information on all pallets.
type PalletInstancesInfo: PalletsInfoAccess;
/// The maximum number of assets we target to have in the Holding Register at any one time.
///
/// NOTE: In the worse case, the Holding Register may contain up to twice as many assets as this
/// and any benchmarks should take that into account.
type MaxAssetsIntoHolding: Get<u32>;
/// Configure the fees.
type FeeManager: FeeManager;
/// The method of exporting a message.
type MessageExporter: ExportXcm;
/// The origin locations and specific universal junctions to which they are allowed to elevate
/// themselves.
type UniversalAliases: Contains<(MultiLocation, Junction)>;
/// The call dispatcher used by XCM.
///
/// XCM will use this to dispatch any calls. When no special call dispatcher is required,
/// this can be set to the same type as `Self::Call`.
type CallDispatcher: CallDispatcher<Self::RuntimeCall>;
/// The safe call filter for `Transact`.
///
/// Use this type to explicitly whitelist calls that cannot undergo recursion. This is a
/// temporary measure until we properly account for proof size weights for XCM instructions.
type SafeCallFilter: Contains<Self::RuntimeCall>;
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,58 @@
// Copyright 2020 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.
// Polkadot is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Polkadot is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
use crate::Assets;
use xcm::prelude::*;
/// A service for exchanging assets.
pub trait AssetExchange {
/// Handler for exchanging an asset.
///
/// - `origin`: The location attempting the exchange; this should generally not matter.
/// - `give`: The assets which have been removed from the caller.
/// - `want`: The minimum amount of assets which should be given to the caller in case any
/// exchange happens. If more assets are provided, then they should generally be of the
/// same asset class if at all possible.
/// - `maximal`: If `true`, then as much as possible should be exchanged.
///
/// `Ok` is returned along with the new set of assets which have been exchanged for `give`. At
/// least want must be in the set. Some assets originally in `give` may also be in this set. In
/// the case of returning an `Err`, then `give` is returned.
fn exchange_asset(
origin: Option<&MultiLocation>,
give: Assets,
want: &MultiAssets,
maximal: bool,
) -> Result<Assets, Assets>;
}
#[impl_trait_for_tuples::impl_for_tuples(30)]
impl AssetExchange for Tuple {
fn exchange_asset(
origin: Option<&MultiLocation>,
give: Assets,
want: &MultiAssets,
maximal: bool,
) -> Result<Assets, Assets> {
for_tuples!( #(
let give = match Tuple::exchange_asset(origin, give, want, maximal) {
Ok(r) => return Ok(r),
Err(a) => a,
};
)* );
Err(give)
}
}
@@ -0,0 +1,152 @@
// Copyright 2020 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.
// Polkadot is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Polkadot is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
use sp_std::convert::Infallible;
use xcm::prelude::*;
#[derive(Debug)]
pub enum LockError {
NotApplicable,
WouldClobber,
BadOrigin,
NotLocked,
NotEnoughLocked,
Unimplemented,
NotTrusted,
BadOwner,
UnknownAsset,
AssetNotOwned,
NoResources,
UnexpectedState,
InUse,
}
impl From<LockError> for XcmError {
fn from(e: LockError) -> XcmError {
use LockError::*;
match e {
NotApplicable => XcmError::AssetNotFound,
BadOrigin => XcmError::BadOrigin,
WouldClobber | NotLocked | NotEnoughLocked | Unimplemented | NotTrusted |
BadOwner | UnknownAsset | AssetNotOwned | NoResources | UnexpectedState | InUse =>
XcmError::LockError,
}
}
}
pub trait Enact {
/// Enact a lock. This should generally be infallible if called immediately after being
/// received.
fn enact(self) -> Result<(), LockError>;
}
impl Enact for Infallible {
fn enact(self) -> Result<(), LockError> {
unreachable!()
}
}
/// Define a handler for notification of an asset being locked and for the unlock instruction.
pub trait AssetLock {
/// `Enact` implementer for `prepare_lock`. This type may be dropped safely to avoid doing the
/// lock.
type LockTicket: Enact;
/// `Enact` implementer for `prepare_unlock`. This type may be dropped safely to avoid doing the
/// unlock.
type UnlockTicket: Enact;
/// `Enact` implementer for `prepare_reduce_unlockable`. This type may be dropped safely to avoid doing the
/// unlock.
type ReduceTicket: Enact;
/// Prepare to lock an asset. On success, a `Self::LockTicket` it returned, which can be used
/// to actually enact the lock.
///
/// WARNING: Don't call this with an undropped instance of `Self::LockTicket` or
/// `Self::UnlockTicket`.
fn prepare_lock(
unlocker: MultiLocation,
asset: MultiAsset,
owner: MultiLocation,
) -> Result<Self::LockTicket, LockError>;
/// Prepare to unlock an asset. On success, a `Self::UnlockTicket` it returned, which can be
/// used to actually enact the lock.
///
/// WARNING: Don't call this with an undropped instance of `Self::LockTicket` or
/// `Self::UnlockTicket`.
fn prepare_unlock(
locker: MultiLocation,
asset: MultiAsset,
owner: MultiLocation,
) -> Result<Self::UnlockTicket, LockError>;
/// Handler for when a location reports to us that an asset has been locked for us to unlock
/// at a later stage.
///
/// If there is no way to handle the lock report, then this should return an error so that the
/// sending chain can ensure the lock does not remain.
///
/// We should only act upon this message if we believe that the `origin` is honest.
fn note_unlockable(
locker: MultiLocation,
asset: MultiAsset,
owner: MultiLocation,
) -> Result<(), LockError>;
/// Handler for when an owner wishes to unlock an asset on a remote chain.
///
/// Returns a ticket which can be used to actually note the reduction in unlockable assets that
/// `owner` commands on `locker`.
///
/// WARNING: Don't call this with an undropped instance of `Self::ReduceTicket`.
fn prepare_reduce_unlockable(
locker: MultiLocation,
asset: MultiAsset,
owner: MultiLocation,
) -> Result<Self::ReduceTicket, LockError>;
}
impl AssetLock for () {
type LockTicket = Infallible;
type UnlockTicket = Infallible;
type ReduceTicket = Infallible;
fn prepare_lock(
_: MultiLocation,
_: MultiAsset,
_: MultiLocation,
) -> Result<Self::LockTicket, LockError> {
Err(LockError::NotApplicable)
}
fn prepare_unlock(
_: MultiLocation,
_: MultiAsset,
_: MultiLocation,
) -> Result<Self::UnlockTicket, LockError> {
Err(LockError::NotApplicable)
}
fn note_unlockable(_: MultiLocation, _: MultiAsset, _: MultiLocation) -> Result<(), LockError> {
Err(LockError::NotApplicable)
}
fn prepare_reduce_unlockable(
_: MultiLocation,
_: MultiAsset,
_: MultiLocation,
) -> Result<Self::ReduceTicket, LockError> {
Err(LockError::NotApplicable)
}
}
@@ -14,9 +14,11 @@
// You should have received a copy of the GNU General Public License
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
use frame_support::traits::{Contains, OriginTrait};
use parity_scale_codec::{Decode, Encode};
use sp_std::{borrow::Borrow, prelude::*, result::Result};
use xcm::latest::{MultiLocation, OriginKind};
use sp_runtime::{traits::Dispatchable, DispatchErrorWithPostInfo};
use sp_std::{borrow::Borrow, marker::PhantomData, prelude::*, result::Result};
use xcm::latest::prelude::*;
/// Generic third-party conversion trait. Use this when you don't want to force the user to use default
/// implementations of `From` and `Into` for the types you wish to convert between.
@@ -204,9 +206,43 @@ impl<O> ConvertOrigin<O> for Tuple {
}
}
/// Means of inverting a location: given a location which describes a `target` interpreted from the
/// `source`, this will provide the corresponding location which describes the `source`.
pub trait InvertLocation {
fn ancestry() -> MultiLocation;
fn invert_location(l: &MultiLocation) -> Result<MultiLocation, ()>;
/// Defines how a call is dispatched with given origin.
/// Allows to customize call dispatch, such as adapting the origin based on the call
/// or modifying the call.
pub trait CallDispatcher<Call: Dispatchable> {
fn dispatch(
call: Call,
origin: Call::RuntimeOrigin,
) -> Result<Call::PostInfo, DispatchErrorWithPostInfo<Call::PostInfo>>;
}
pub struct WithOriginFilter<Filter>(PhantomData<Filter>);
impl<Call, Filter> CallDispatcher<Call> for WithOriginFilter<Filter>
where
Call: Dispatchable,
Call::RuntimeOrigin: OriginTrait,
<<Call as Dispatchable>::RuntimeOrigin as OriginTrait>::Call: 'static,
Filter: Contains<<<Call as Dispatchable>::RuntimeOrigin as OriginTrait>::Call> + 'static,
{
fn dispatch(
call: Call,
mut origin: <Call as Dispatchable>::RuntimeOrigin,
) -> Result<
<Call as Dispatchable>::PostInfo,
DispatchErrorWithPostInfo<<Call as Dispatchable>::PostInfo>,
> {
origin.add_filter(Filter::contains);
call.dispatch(origin)
}
}
// We implement it for every calls so they can dispatch themselves
// (without any change).
impl<Call: Dispatchable> CallDispatcher<Call> for Call {
fn dispatch(
call: Call,
origin: Call::RuntimeOrigin,
) -> Result<Call::PostInfo, DispatchErrorWithPostInfo<Call::PostInfo>> {
call.dispatch(origin)
}
}
@@ -17,16 +17,15 @@
use crate::Assets;
use core::marker::PhantomData;
use frame_support::traits::Contains;
use sp_runtime::traits::Zero;
use xcm::latest::{MultiAssets, MultiLocation, Weight};
use xcm::latest::{MultiAssets, MultiLocation, Weight, XcmContext};
/// Define a handler for when some non-empty `Assets` value should be dropped.
pub trait DropAssets {
/// Handler for receiving dropped assets. Returns the weight consumed by this operation.
fn drop_assets(origin: &MultiLocation, assets: Assets) -> Weight;
fn drop_assets(origin: &MultiLocation, assets: Assets, context: &XcmContext) -> Weight;
}
impl DropAssets for () {
fn drop_assets(_origin: &MultiLocation, _assets: Assets) -> Weight {
fn drop_assets(_origin: &MultiLocation, _assets: Assets, _context: &XcmContext) -> Weight {
Weight::zero()
}
}
@@ -36,9 +35,9 @@ impl DropAssets for () {
pub struct FilterAssets<D, A>(PhantomData<(D, A)>);
impl<D: DropAssets, A: Contains<Assets>> DropAssets for FilterAssets<D, A> {
fn drop_assets(origin: &MultiLocation, assets: Assets) -> Weight {
fn drop_assets(origin: &MultiLocation, assets: Assets, context: &XcmContext) -> Weight {
if A::contains(&assets) {
D::drop_assets(origin, assets)
D::drop_assets(origin, assets, context)
} else {
Weight::zero()
}
@@ -51,9 +50,9 @@ impl<D: DropAssets, A: Contains<Assets>> DropAssets for FilterAssets<D, A> {
pub struct FilterOrigin<D, O>(PhantomData<(D, O)>);
impl<D: DropAssets, O: Contains<MultiLocation>> DropAssets for FilterOrigin<D, O> {
fn drop_assets(origin: &MultiLocation, assets: Assets) -> Weight {
fn drop_assets(origin: &MultiLocation, assets: Assets, context: &XcmContext) -> Weight {
if O::contains(origin) {
D::drop_assets(origin, assets)
D::drop_assets(origin, assets, context)
} else {
Weight::zero()
}
@@ -64,14 +63,24 @@ impl<D: DropAssets, O: Contains<MultiLocation>> DropAssets for FilterOrigin<D, O
pub trait ClaimAssets {
/// Claim any assets available to `origin` and return them in a single `Assets` value, together
/// with the weight used by this operation.
fn claim_assets(origin: &MultiLocation, ticket: &MultiLocation, what: &MultiAssets) -> bool;
fn claim_assets(
origin: &MultiLocation,
ticket: &MultiLocation,
what: &MultiAssets,
context: &XcmContext,
) -> bool;
}
#[impl_trait_for_tuples::impl_for_tuples(30)]
impl ClaimAssets for Tuple {
fn claim_assets(origin: &MultiLocation, ticket: &MultiLocation, what: &MultiAssets) -> bool {
fn claim_assets(
origin: &MultiLocation,
ticket: &MultiLocation,
what: &MultiAssets,
context: &XcmContext,
) -> bool {
for_tuples!( #(
if Tuple::claim_assets(origin, ticket, what) {
if Tuple::claim_assets(origin, ticket, what, context) {
return true;
}
)* );
@@ -0,0 +1,146 @@
// Copyright 2020 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.
// Polkadot is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Polkadot is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
use xcm::latest::prelude::*;
/// Utility for delivering a message to a system under a different (non-local) consensus with a
/// spoofed origin. This essentially defines the behaviour of the `ExportMessage` XCM instruction.
///
/// This is quite different to `SendXcm`; `SendXcm` assumes that the local side's location will be
/// preserved to be represented as the value of the Origin register in the messages execution.
///
/// This trait on the other hand assumes that we do not necessarily want the Origin register to
/// contain the local (i.e. the caller chain's) location, since it will generally be exporting a
/// message on behalf of another consensus system. Therefore in addition to the message, the
/// destination must be given in two parts: the network and the interior location within it.
///
/// We also require the caller to state exactly what location they purport to be representing. The
/// destination must accept the local location to represent that location or the operation will
/// fail.
pub trait ExportXcm {
/// Intermediate value which connects the two phaases of the export operation.
type Ticket;
/// Check whether the given `message` is deliverable to the given `destination` on `network`,
/// spoofing its source as `universal_source` and if so determine the cost which will be paid by
/// this chain to do so, returning a `Ticket` token which can be used to enact delivery.
///
/// The `channel` to be used on the `network`'s export mechanism (bridge, probably) must also
/// be provided.
///
/// The `destination` and `message` must be `Some` (or else an error will be returned) and they
/// may only be consumed if the `Err` is not `NotApplicable`.
///
/// If it is not a destination which can be reached with this type but possibly could by others,
/// then this *MUST* return `NotApplicable`. Any other error will cause the tuple
/// implementation (used to compose routing systems from different delivery agents) to exit
/// early without trying alternative means of delivery.
fn validate(
network: NetworkId,
channel: u32,
universal_source: &mut Option<InteriorMultiLocation>,
destination: &mut Option<InteriorMultiLocation>,
message: &mut Option<Xcm<()>>,
) -> SendResult<Self::Ticket>;
/// Actually carry out the delivery operation for a previously validated message sending.
///
/// The implementation should do everything possible to ensure that this function is infallible
/// if called immediately after `validate`. Returning an error here would result in a price
/// paid without the service being delivered.
fn deliver(ticket: Self::Ticket) -> Result<XcmHash, SendError>;
}
#[impl_trait_for_tuples::impl_for_tuples(30)]
impl ExportXcm for Tuple {
for_tuples! { type Ticket = (#( Option<Tuple::Ticket> ),* ); }
fn validate(
network: NetworkId,
channel: u32,
universal_source: &mut Option<InteriorMultiLocation>,
destination: &mut Option<InteriorMultiLocation>,
message: &mut Option<Xcm<()>>,
) -> SendResult<Self::Ticket> {
let mut maybe_cost: Option<MultiAssets> = None;
let one_ticket: Self::Ticket = (for_tuples! { #(
if maybe_cost.is_some() {
None
} else {
match Tuple::validate(network, channel, universal_source, destination, message) {
Err(SendError::NotApplicable) => None,
Err(e) => { return Err(e) },
Ok((v, c)) => {
maybe_cost = Some(c);
Some(v)
},
}
}
),* });
if let Some(cost) = maybe_cost {
Ok((one_ticket, cost))
} else {
Err(SendError::NotApplicable)
}
}
fn deliver(one_ticket: Self::Ticket) -> Result<XcmHash, SendError> {
for_tuples!( #(
if let Some(validated) = one_ticket.Tuple.take() {
return Tuple::deliver(validated);
}
)* );
Err(SendError::Unroutable)
}
}
/// Convenience function for using a `SendXcm` implementation. Just interprets the `dest` and wraps
/// both in `Some` before passing them as as mutable references into `T::send_xcm`.
pub fn validate_export<T: ExportXcm>(
network: NetworkId,
channel: u32,
universal_source: InteriorMultiLocation,
dest: InteriorMultiLocation,
msg: Xcm<()>,
) -> SendResult<T::Ticket> {
T::validate(network, channel, &mut Some(universal_source), &mut Some(dest), &mut Some(msg))
}
/// Convenience function for using a `SendXcm` implementation. Just interprets the `dest` and wraps
/// both in `Some` before passing them as as mutable references into `T::send_xcm`.
///
/// Returns either `Ok` with the price of the delivery, or `Err` with the reason why the message
/// could not be sent.
///
/// Generally you'll want to validate and get the price first to ensure that the sender can pay it
/// before actually doing the delivery.
pub fn export_xcm<T: ExportXcm>(
network: NetworkId,
channel: u32,
universal_source: InteriorMultiLocation,
dest: InteriorMultiLocation,
msg: Xcm<()>,
) -> Result<(XcmHash, MultiAssets), SendError> {
let (ticket, price) = T::validate(
network,
channel,
&mut Some(universal_source),
&mut Some(dest),
&mut Some(msg),
)?;
let hash = T::deliver(ticket)?;
Ok((hash, price))
}
@@ -0,0 +1,59 @@
// Copyright 2022 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.
// Polkadot is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Polkadot is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
use xcm::prelude::*;
/// Handle stuff to do with taking fees in certain XCM instructions.
pub trait FeeManager {
/// Determine if a fee which would normally payable should be waived.
fn is_waived(origin: Option<&MultiLocation>, r: FeeReason) -> bool;
/// Do something with the fee which has been paid. Doing nothing here silently burns the
/// fees.
fn handle_fee(fee: MultiAssets);
}
/// Context under which a fee is paid.
#[derive(Copy, Clone, Eq, PartialEq)]
pub enum FeeReason {
/// When a reporting instruction is called.
Report,
/// When the `TransferReserveAsset` instruction is called.
TransferReserveAsset,
/// When the `DepositReserveAsset` instruction is called.
DepositReserveAsset,
/// When the `InitiateReserveWithdraw` instruction is called.
InitiateReserveWithdraw,
/// When the `InitiateTeleport` instruction is called.
InitiateTeleport,
/// When the `QueryPallet` instruction is called.
QueryPallet,
/// When the `ExportMessage` instruction is called (and includes the network ID).
Export(NetworkId),
/// The `charge_fees` API.
ChargeFees,
/// When the `LockAsset` instruction is called.
LockAsset,
/// When the `RequestUnlock` instruction is called.
RequestUnlock,
}
impl FeeManager for () {
fn is_waived(_: Option<&MultiLocation>, _: FeeReason) -> bool {
true
}
fn handle_fee(_: MultiAssets) {}
}
@@ -14,28 +14,21 @@
// You should have received a copy of the GNU General Public License
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
use frame_support::traits::ContainsPair;
use xcm::latest::{MultiAsset, MultiLocation};
/// Filters assets/location pairs.
///
/// Can be amalgamated into tuples. If any item returns `true`, it short-circuits, else `false` is returned.
#[deprecated = "Use `frame_support::traits::ContainsPair<MultiAsset, MultiLocation>` instead"]
pub trait FilterAssetLocation {
/// A filter to distinguish between asset/location pairs.
fn filter_asset_location(asset: &MultiAsset, origin: &MultiLocation) -> bool;
fn contains(asset: &MultiAsset, origin: &MultiLocation) -> bool;
}
#[impl_trait_for_tuples::impl_for_tuples(30)]
impl FilterAssetLocation for Tuple {
fn filter_asset_location(what: &MultiAsset, origin: &MultiLocation) -> bool {
for_tuples!( #(
if Tuple::filter_asset_location(what, origin) { return true }
)* );
log::trace!(
target: "xcm::filter_asset_location",
"got filtered: what: {:?}, origin: {:?}",
what,
origin,
);
false
#[allow(deprecated)]
impl<T: ContainsPair<MultiAsset, MultiLocation>> FilterAssetLocation for T {
fn contains(asset: &MultiAsset, origin: &MultiLocation) -> bool {
T::contains(asset, origin)
}
}
@@ -1,32 +0,0 @@
// Copyright 2020 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.
// Polkadot is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Polkadot is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
use xcm::latest::MultiAsset;
pub trait MatchesFungible<Balance> {
fn matches_fungible(a: &MultiAsset) -> Option<Balance>;
}
#[impl_trait_for_tuples::impl_for_tuples(30)]
impl<Balance> MatchesFungible<Balance> for Tuple {
fn matches_fungible(a: &MultiAsset) -> Option<Balance> {
for_tuples!( #(
match Tuple::matches_fungible(a) { o @ Some(_) => return o, _ => () }
)* );
log::trace!(target: "xcm::matches_fungible", "did not match fungible asset: {:?}", &a);
None
}
}
+26 -5
View File
@@ -17,15 +17,26 @@
//! Various traits used in configuring the executor.
mod conversion;
pub use conversion::{Convert, ConvertOrigin, Decoded, Encoded, Identity, InvertLocation, JustTry};
pub use conversion::{
CallDispatcher, Convert, ConvertOrigin, Decoded, Encoded, Identity, JustTry, WithOriginFilter,
};
mod drop_assets;
pub use drop_assets::{ClaimAssets, DropAssets};
mod asset_lock;
pub use asset_lock::{AssetLock, Enact, LockError};
mod asset_exchange;
pub use asset_exchange::AssetExchange;
mod export;
pub use export::{export_xcm, validate_export, ExportXcm};
mod fee_manager;
pub use fee_manager::{FeeManager, FeeReason};
mod filter_asset_location;
#[allow(deprecated)]
pub use filter_asset_location::FilterAssetLocation;
mod matches_fungible;
pub use matches_fungible::MatchesFungible;
mod matches_fungibles;
pub use matches_fungibles::{Error, MatchesFungibles};
mod token_matching;
pub use token_matching::{
Error, MatchesFungible, MatchesFungibles, MatchesNonFungible, MatchesNonFungibles,
};
mod on_response;
pub use on_response::{OnResponse, VersionChangeNotifier};
mod should_execute;
@@ -34,3 +45,13 @@ mod transact_asset;
pub use transact_asset::TransactAsset;
mod weight;
pub use weight::{WeightBounds, WeightTrader};
pub mod prelude {
pub use super::{
export_xcm, validate_export, AssetExchange, AssetLock, ClaimAssets, Convert, ConvertOrigin,
Decoded, DropAssets, Enact, Encoded, Error, ExportXcm, FeeManager, FeeReason, Identity,
JustTry, LockError, MatchesFungible, MatchesFungibles, MatchesNonFungible,
MatchesNonFungibles, OnResponse, ShouldExecute, TransactAsset, VersionChangeNotifier,
WeightBounds, WeightTrader, WithOriginFilter,
};
}
@@ -14,32 +14,45 @@
// You should have received a copy of the GNU General Public License
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
use sp_runtime::traits::Zero;
use xcm::latest::{
Error as XcmError, MultiLocation, QueryId, Response, Result as XcmResult, Weight,
Error as XcmError, MultiLocation, QueryId, Response, Result as XcmResult, Weight, XcmContext,
};
/// Define what needs to be done upon receiving a query response.
pub trait OnResponse {
/// Returns `true` if we are expecting a response from `origin` for query `query_id`.
fn expecting_response(origin: &MultiLocation, query_id: u64) -> bool;
/// Handler for receiving a `response` from `origin` relating to `query_id`.
/// Returns `true` if we are expecting a response from `origin` for query `query_id` that was
/// queried by `querier`.
fn expecting_response(
origin: &MultiLocation,
query_id: u64,
querier: Option<&MultiLocation>,
) -> bool;
/// Handler for receiving a `response` from `origin` relating to `query_id` initiated by
/// `querier`.
fn on_response(
origin: &MultiLocation,
query_id: u64,
querier: Option<&MultiLocation>,
response: Response,
max_weight: Weight,
context: &XcmContext,
) -> Weight;
}
impl OnResponse for () {
fn expecting_response(_origin: &MultiLocation, _query_id: u64) -> bool {
fn expecting_response(
_origin: &MultiLocation,
_query_id: u64,
_querier: Option<&MultiLocation>,
) -> bool {
false
}
fn on_response(
_origin: &MultiLocation,
_query_id: u64,
_querier: Option<&MultiLocation>,
_response: Response,
_max_weight: Weight,
_context: &XcmContext,
) -> Weight {
Weight::zero()
}
@@ -50,26 +63,31 @@ pub trait VersionChangeNotifier {
/// Start notifying `location` should the XCM version of this chain change.
///
/// When it does, this type should ensure a `QueryResponse` message is sent with the given
/// `query_id` & `max_weight` and with a `response` of `Repsonse::Version`. This should happen
/// `query_id` & `max_weight` and with a `response` of `Response::Version`. This should happen
/// until/unless `stop` is called with the correct `query_id`.
///
/// If the `location` has an ongoing notification and when this function is called, then an
/// error should be returned.
fn start(location: &MultiLocation, query_id: QueryId, max_weight: u64) -> XcmResult;
fn start(
location: &MultiLocation,
query_id: QueryId,
max_weight: Weight,
context: &XcmContext,
) -> XcmResult;
/// Stop notifying `location` should the XCM change. Returns an error if there is no existing
/// notification set up.
fn stop(location: &MultiLocation) -> XcmResult;
fn stop(location: &MultiLocation, context: &XcmContext) -> XcmResult;
/// Return true if a location is subscribed to XCM version changes.
fn is_subscribed(location: &MultiLocation) -> bool;
}
impl VersionChangeNotifier for () {
fn start(_: &MultiLocation, _: QueryId, _: u64) -> XcmResult {
fn start(_: &MultiLocation, _: QueryId, _: Weight, _: &XcmContext) -> XcmResult {
Err(XcmError::Unimplemented)
}
fn stop(_: &MultiLocation) -> XcmResult {
fn stop(_: &MultiLocation, _: &XcmContext) -> XcmResult {
Err(XcmError::Unimplemented)
}
fn is_subscribed(_: &MultiLocation) -> bool {
@@ -15,7 +15,7 @@
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
use sp_std::result::Result;
use xcm::latest::{MultiLocation, Weight, Xcm};
use xcm::latest::{Instruction, MultiLocation, Weight};
/// Trait to determine whether the execution engine should actually execute a given XCM.
///
@@ -25,14 +25,14 @@ pub trait ShouldExecute {
/// Returns `true` if the given `message` may be executed.
///
/// - `origin`: The origin (sender) of the message.
/// - `message`: The message itself.
/// - `instructions`: The message itself.
/// - `max_weight`: The (possibly over-) estimation of the weight of execution of the message.
/// - `weight_credit`: The pre-established amount of weight that the system has determined this
/// message may utilize in its execution. Typically non-zero only because of prior fee
/// payment, but could in principle be due to other factors.
fn should_execute<RuntimeCall>(
origin: &MultiLocation,
message: &mut Xcm<RuntimeCall>,
instructions: &mut [Instruction<RuntimeCall>],
max_weight: Weight,
weight_credit: &mut Weight,
) -> Result<(), ()>;
@@ -42,21 +42,21 @@ pub trait ShouldExecute {
impl ShouldExecute for Tuple {
fn should_execute<RuntimeCall>(
origin: &MultiLocation,
message: &mut Xcm<RuntimeCall>,
instructions: &mut [Instruction<RuntimeCall>],
max_weight: Weight,
weight_credit: &mut Weight,
) -> Result<(), ()> {
for_tuples!( #(
match Tuple::should_execute(origin, message, max_weight, weight_credit) {
match Tuple::should_execute(origin, instructions, max_weight, weight_credit) {
Ok(()) => return Ok(()),
_ => (),
}
)* );
log::trace!(
target: "xcm::should_execute",
"did not pass barrier: origin: {:?}, message: {:?}, max_weight: {:?}, weight_credit: {:?}",
"did not pass barrier: origin: {:?}, instructions: {:?}, max_weight: {:?}, weight_credit: {:?}",
origin,
message,
instructions,
max_weight,
weight_credit,
);
@@ -15,7 +15,37 @@
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
use sp_std::result;
use xcm::latest::{Error as XcmError, MultiAsset};
use xcm::latest::prelude::*;
pub trait MatchesFungible<Balance> {
fn matches_fungible(a: &MultiAsset) -> Option<Balance>;
}
#[impl_trait_for_tuples::impl_for_tuples(30)]
impl<Balance> MatchesFungible<Balance> for Tuple {
fn matches_fungible(a: &MultiAsset) -> Option<Balance> {
for_tuples!( #(
match Tuple::matches_fungible(a) { o @ Some(_) => return o, _ => () }
)* );
log::trace!(target: "xcm::matches_fungible", "did not match fungible asset: {:?}", &a);
None
}
}
pub trait MatchesNonFungible<Instance> {
fn matches_nonfungible(a: &MultiAsset) -> Option<Instance>;
}
#[impl_trait_for_tuples::impl_for_tuples(30)]
impl<Instance> MatchesNonFungible<Instance> for Tuple {
fn matches_nonfungible(a: &MultiAsset) -> Option<Instance> {
for_tuples!( #(
match Tuple::matches_nonfungible(a) { o @ Some(_) => return o, _ => () }
)* );
log::trace!(target: "xcm::matches_non_fungible", "did not match non-fungible asset: {:?}", &a);
None
}
}
/// Errors associated with [`MatchesFungibles`] operation.
pub enum Error {
@@ -25,8 +55,10 @@ pub enum Error {
AccountIdConversionFailed,
/// `u128` amount to currency `Balance` conversion failed.
AmountToBalanceConversionFailed,
/// `MultiLocation` to `AssetId` conversion failed.
/// `MultiLocation` to `AssetId`/`ClassId` conversion failed.
AssetIdConversionFailed,
/// `AssetInstance` to non-fungibles instance ID conversion failed.
InstanceConversionFailed,
}
impl From<Error> for XcmError {
@@ -38,6 +70,7 @@ impl From<Error> for XcmError {
Error::AmountToBalanceConversionFailed =>
FailedToTransactAsset("AmountToBalanceConversionFailed"),
Error::AssetIdConversionFailed => FailedToTransactAsset("AssetIdConversionFailed"),
Error::InstanceConversionFailed => FailedToTransactAsset("InstanceConversionFailed"),
}
}
}
@@ -47,7 +80,7 @@ pub trait MatchesFungibles<AssetId, Balance> {
}
#[impl_trait_for_tuples::impl_for_tuples(30)]
impl<AssetId: Clone, Balance: Clone> MatchesFungibles<AssetId, Balance> for Tuple {
impl<AssetId, Balance> MatchesFungibles<AssetId, Balance> for Tuple {
fn matches_fungibles(a: &MultiAsset) -> result::Result<(AssetId, Balance), Error> {
for_tuples!( #(
match Tuple::matches_fungibles(a) { o @ Ok(_) => return o, _ => () }
@@ -56,3 +89,18 @@ impl<AssetId: Clone, Balance: Clone> MatchesFungibles<AssetId, Balance> for Tupl
Err(Error::AssetNotFound)
}
}
pub trait MatchesNonFungibles<AssetId, Instance> {
fn matches_nonfungibles(a: &MultiAsset) -> result::Result<(AssetId, Instance), Error>;
}
#[impl_trait_for_tuples::impl_for_tuples(30)]
impl<AssetId, Instance> MatchesNonFungibles<AssetId, Instance> for Tuple {
fn matches_nonfungibles(a: &MultiAsset) -> result::Result<(AssetId, Instance), Error> {
for_tuples!( #(
match Tuple::matches_nonfungibles(a) { o @ Ok(_) => return o, _ => () }
)* );
log::trace!(target: "xcm::matches_non_fungibles", "did not match fungibles asset: {:?}", &a);
Err(Error::AssetNotFound)
}
}
@@ -16,7 +16,7 @@
use crate::Assets;
use sp_std::result::Result;
use xcm::latest::{Error as XcmError, MultiAsset, MultiLocation, Result as XcmResult};
use xcm::latest::{Error as XcmError, MultiAsset, MultiLocation, Result as XcmResult, XcmContext};
/// Facility for asset transacting.
///
@@ -26,10 +26,14 @@ use xcm::latest::{Error as XcmError, MultiAsset, MultiLocation, Result as XcmRes
/// Can be amalgamated as a tuple of items that implement this trait. In such executions, if any of the transactors
/// returns `Ok(())`, then it will short circuit. Else, execution is passed to the next transactor.
pub trait TransactAsset {
/// Ensure that `check_in` will result in `Ok`.
/// Ensure that `check_in` will do as expected.
///
/// When composed as a tuple, all type-items are called and at least one must result in `Ok`.
fn can_check_in(_origin: &MultiLocation, _what: &MultiAsset) -> XcmResult {
fn can_check_in(
_origin: &MultiLocation,
_what: &MultiAsset,
_context: &XcmContext,
) -> XcmResult {
Err(XcmError::Unimplemented)
}
@@ -46,7 +50,18 @@ pub trait TransactAsset {
///
/// When composed as a tuple, all type-items are called. It is up to the implementer that there exists no
/// value for `_what` which can cause side-effects for more than one of the type-items.
fn check_in(_origin: &MultiLocation, _what: &MultiAsset) {}
fn check_in(_origin: &MultiLocation, _what: &MultiAsset, _context: &XcmContext) {}
/// Ensure that `check_out` will do as expected.
///
/// When composed as a tuple, all type-items are called and at least one must result in `Ok`.
fn can_check_out(
_dest: &MultiLocation,
_what: &MultiAsset,
_context: &XcmContext,
) -> XcmResult {
Err(XcmError::Unimplemented)
}
/// An asset has been teleported out to the given destination. This should do whatever housekeeping is needed.
///
@@ -58,20 +73,28 @@ pub trait TransactAsset {
///
/// When composed as a tuple, all type-items are called. It is up to the implementer that there exists no
/// value for `_what` which can cause side-effects for more than one of the type-items.
fn check_out(_dest: &MultiLocation, _what: &MultiAsset) {}
fn check_out(_dest: &MultiLocation, _what: &MultiAsset, _context: &XcmContext) {}
/// Deposit the `what` asset into the account of `who`.
///
/// Implementations should return `XcmError::FailedToTransactAsset` if deposit failed.
fn deposit_asset(_what: &MultiAsset, _who: &MultiLocation) -> XcmResult {
fn deposit_asset(_what: &MultiAsset, _who: &MultiLocation, _context: &XcmContext) -> XcmResult {
Err(XcmError::Unimplemented)
}
/// Withdraw the given asset from the consensus system. Return the actual asset(s) withdrawn,
/// which should always be equal to `_what`.
///
/// The XCM `_maybe_context` parameter may be `None` when the caller of `withdraw_asset` is
/// outside of the context of a currently-executing XCM. An example will be the `charge_fees`
/// method in the XCM executor.
///
/// Implementations should return `XcmError::FailedToTransactAsset` if withdraw failed.
fn withdraw_asset(_what: &MultiAsset, _who: &MultiLocation) -> Result<Assets, XcmError> {
fn withdraw_asset(
_what: &MultiAsset,
_who: &MultiLocation,
_maybe_context: Option<&XcmContext>,
) -> Result<Assets, XcmError> {
Err(XcmError::Unimplemented)
}
@@ -88,6 +111,7 @@ pub trait TransactAsset {
_asset: &MultiAsset,
_from: &MultiLocation,
_to: &MultiLocation,
_context: &XcmContext,
) -> Result<Assets, XcmError> {
Err(XcmError::Unimplemented)
}
@@ -100,12 +124,13 @@ pub trait TransactAsset {
asset: &MultiAsset,
from: &MultiLocation,
to: &MultiLocation,
context: &XcmContext,
) -> Result<Assets, XcmError> {
match Self::internal_transfer_asset(asset, from, to) {
Err(XcmError::Unimplemented) => {
let assets = Self::withdraw_asset(asset, from)?;
match Self::internal_transfer_asset(asset, from, to, context) {
Err(XcmError::AssetNotFound | XcmError::Unimplemented) => {
let assets = Self::withdraw_asset(asset, from, Some(context))?;
// Not a very forgiving attitude; once we implement roll-backs then it'll be nicer.
Self::deposit_asset(asset, to)?;
Self::deposit_asset(asset, to, context)?;
Ok(assets)
},
result => result,
@@ -115,62 +140,86 @@ pub trait TransactAsset {
#[impl_trait_for_tuples::impl_for_tuples(30)]
impl TransactAsset for Tuple {
fn can_check_in(origin: &MultiLocation, what: &MultiAsset) -> XcmResult {
fn can_check_in(origin: &MultiLocation, what: &MultiAsset, context: &XcmContext) -> XcmResult {
for_tuples!( #(
match Tuple::can_check_in(origin, what) {
match Tuple::can_check_in(origin, what, context) {
Err(XcmError::AssetNotFound) | Err(XcmError::Unimplemented) => (),
r => return r,
}
)* );
log::trace!(
target: "xcm::TransactAsset::can_check_in",
"asset not found: what: {:?}, origin: {:?}",
"asset not found: what: {:?}, origin: {:?}, context: {:?}",
what,
origin,
context,
);
Err(XcmError::AssetNotFound)
}
fn check_in(origin: &MultiLocation, what: &MultiAsset) {
fn check_in(origin: &MultiLocation, what: &MultiAsset, context: &XcmContext) {
for_tuples!( #(
Tuple::check_in(origin, what);
Tuple::check_in(origin, what, context);
)* );
}
fn check_out(dest: &MultiLocation, what: &MultiAsset) {
fn can_check_out(dest: &MultiLocation, what: &MultiAsset, context: &XcmContext) -> XcmResult {
for_tuples!( #(
Tuple::check_out(dest, what);
match Tuple::can_check_out(dest, what, context) {
Err(XcmError::AssetNotFound) | Err(XcmError::Unimplemented) => (),
r => return r,
}
)* );
log::trace!(
target: "xcm::TransactAsset::can_check_out",
"asset not found: what: {:?}, dest: {:?}, context: {:?}",
what,
dest,
context,
);
Err(XcmError::AssetNotFound)
}
fn check_out(dest: &MultiLocation, what: &MultiAsset, context: &XcmContext) {
for_tuples!( #(
Tuple::check_out(dest, what, context);
)* );
}
fn deposit_asset(what: &MultiAsset, who: &MultiLocation) -> XcmResult {
fn deposit_asset(what: &MultiAsset, who: &MultiLocation, context: &XcmContext) -> XcmResult {
for_tuples!( #(
match Tuple::deposit_asset(what, who) {
match Tuple::deposit_asset(what, who, context) {
Err(XcmError::AssetNotFound) | Err(XcmError::Unimplemented) => (),
r => return r,
}
)* );
log::trace!(
target: "xcm::TransactAsset::deposit_asset",
"did not deposit asset: what: {:?}, who: {:?}",
"did not deposit asset: what: {:?}, who: {:?}, context: {:?}",
what,
who,
context,
);
Err(XcmError::AssetNotFound)
}
fn withdraw_asset(what: &MultiAsset, who: &MultiLocation) -> Result<Assets, XcmError> {
fn withdraw_asset(
what: &MultiAsset,
who: &MultiLocation,
maybe_context: Option<&XcmContext>,
) -> Result<Assets, XcmError> {
for_tuples!( #(
match Tuple::withdraw_asset(what, who) {
match Tuple::withdraw_asset(what, who, maybe_context) {
Err(XcmError::AssetNotFound) | Err(XcmError::Unimplemented) => (),
r => return r,
}
)* );
log::trace!(
target: "xcm::TransactAsset::withdraw_asset",
"did not withdraw asset: what: {:?}, who: {:?}",
"did not withdraw asset: what: {:?}, who: {:?}, maybe_context: {:?}",
what,
who,
maybe_context,
);
Err(XcmError::AssetNotFound)
}
@@ -179,19 +228,21 @@ impl TransactAsset for Tuple {
what: &MultiAsset,
from: &MultiLocation,
to: &MultiLocation,
context: &XcmContext,
) -> Result<Assets, XcmError> {
for_tuples!( #(
match Tuple::internal_transfer_asset(what, from, to) {
match Tuple::internal_transfer_asset(what, from, to, context) {
Err(XcmError::AssetNotFound) | Err(XcmError::Unimplemented) => (),
r => return r,
}
)* );
log::trace!(
target: "xcm::TransactAsset::internal_transfer_asset",
"did not transfer asset: what: {:?}, from: {:?}, to: {:?}",
"did not transfer asset: what: {:?}, from: {:?}, to: {:?}, context: {:?}",
what,
from,
to,
context,
);
Err(XcmError::AssetNotFound)
}
@@ -207,15 +258,35 @@ mod tests {
pub struct NotFoundTransactor;
impl TransactAsset for NotFoundTransactor {
fn can_check_in(_origin: &MultiLocation, _what: &MultiAsset) -> XcmResult {
fn can_check_in(
_origin: &MultiLocation,
_what: &MultiAsset,
_context: &XcmContext,
) -> XcmResult {
Err(XcmError::AssetNotFound)
}
fn deposit_asset(_what: &MultiAsset, _who: &MultiLocation) -> XcmResult {
fn can_check_out(
_dest: &MultiLocation,
_what: &MultiAsset,
_context: &XcmContext,
) -> XcmResult {
Err(XcmError::AssetNotFound)
}
fn withdraw_asset(_what: &MultiAsset, _who: &MultiLocation) -> Result<Assets, XcmError> {
fn deposit_asset(
_what: &MultiAsset,
_who: &MultiLocation,
_context: &XcmContext,
) -> XcmResult {
Err(XcmError::AssetNotFound)
}
fn withdraw_asset(
_what: &MultiAsset,
_who: &MultiLocation,
_context: Option<&XcmContext>,
) -> Result<Assets, XcmError> {
Err(XcmError::AssetNotFound)
}
@@ -223,6 +294,7 @@ mod tests {
_what: &MultiAsset,
_from: &MultiLocation,
_to: &MultiLocation,
_context: &XcmContext,
) -> Result<Assets, XcmError> {
Err(XcmError::AssetNotFound)
}
@@ -230,15 +302,35 @@ mod tests {
pub struct OverflowTransactor;
impl TransactAsset for OverflowTransactor {
fn can_check_in(_origin: &MultiLocation, _what: &MultiAsset) -> XcmResult {
fn can_check_in(
_origin: &MultiLocation,
_what: &MultiAsset,
_context: &XcmContext,
) -> XcmResult {
Err(XcmError::Overflow)
}
fn deposit_asset(_what: &MultiAsset, _who: &MultiLocation) -> XcmResult {
fn can_check_out(
_dest: &MultiLocation,
_what: &MultiAsset,
_context: &XcmContext,
) -> XcmResult {
Err(XcmError::Overflow)
}
fn withdraw_asset(_what: &MultiAsset, _who: &MultiLocation) -> Result<Assets, XcmError> {
fn deposit_asset(
_what: &MultiAsset,
_who: &MultiLocation,
_context: &XcmContext,
) -> XcmResult {
Err(XcmError::Overflow)
}
fn withdraw_asset(
_what: &MultiAsset,
_who: &MultiLocation,
_context: Option<&XcmContext>,
) -> Result<Assets, XcmError> {
Err(XcmError::Overflow)
}
@@ -246,6 +338,7 @@ mod tests {
_what: &MultiAsset,
_from: &MultiLocation,
_to: &MultiLocation,
_context: &XcmContext,
) -> Result<Assets, XcmError> {
Err(XcmError::Overflow)
}
@@ -253,15 +346,35 @@ mod tests {
pub struct SuccessfulTransactor;
impl TransactAsset for SuccessfulTransactor {
fn can_check_in(_origin: &MultiLocation, _what: &MultiAsset) -> XcmResult {
fn can_check_in(
_origin: &MultiLocation,
_what: &MultiAsset,
_context: &XcmContext,
) -> XcmResult {
Ok(())
}
fn deposit_asset(_what: &MultiAsset, _who: &MultiLocation) -> XcmResult {
fn can_check_out(
_dest: &MultiLocation,
_what: &MultiAsset,
_context: &XcmContext,
) -> XcmResult {
Ok(())
}
fn withdraw_asset(_what: &MultiAsset, _who: &MultiLocation) -> Result<Assets, XcmError> {
fn deposit_asset(
_what: &MultiAsset,
_who: &MultiLocation,
_context: &XcmContext,
) -> XcmResult {
Ok(())
}
fn withdraw_asset(
_what: &MultiAsset,
_who: &MultiLocation,
_context: Option<&XcmContext>,
) -> Result<Assets, XcmError> {
Ok(Assets::default())
}
@@ -269,6 +382,7 @@ mod tests {
_what: &MultiAsset,
_from: &MultiLocation,
_to: &MultiLocation,
_context: &XcmContext,
) -> Result<Assets, XcmError> {
Ok(Assets::default())
}
@@ -280,7 +394,11 @@ mod tests {
(UnimplementedTransactor, NotFoundTransactor, UnimplementedTransactor);
assert_eq!(
MultiTransactor::deposit_asset(&(Here, 1).into(), &Here.into()),
MultiTransactor::deposit_asset(
&(Here, 1u128).into(),
&Here.into(),
&XcmContext::with_message_hash([0; 32]),
),
Err(XcmError::AssetNotFound)
);
}
@@ -289,7 +407,14 @@ mod tests {
fn unimplemented_and_not_found_continue_iteration() {
type MultiTransactor = (UnimplementedTransactor, NotFoundTransactor, SuccessfulTransactor);
assert_eq!(MultiTransactor::deposit_asset(&(Here, 1).into(), &Here.into()), Ok(()),);
assert_eq!(
MultiTransactor::deposit_asset(
&(Here, 1u128).into(),
&Here.into(),
&XcmContext::with_message_hash([0; 32]),
),
Ok(())
);
}
#[test]
@@ -297,7 +422,11 @@ mod tests {
type MultiTransactor = (OverflowTransactor, SuccessfulTransactor);
assert_eq!(
MultiTransactor::deposit_asset(&(Here, 1).into(), &Here.into()),
MultiTransactor::deposit_asset(
&(Here, 1u128).into(),
&Here.into(),
&XcmContext::with_message_hash([0; 32]),
),
Err(XcmError::Overflow)
);
}
@@ -306,6 +435,13 @@ mod tests {
fn success_stops_iteration() {
type MultiTransactor = (SuccessfulTransactor, OverflowTransactor);
assert_eq!(MultiTransactor::deposit_asset(&(Here, 1).into(), &Here.into()), Ok(()),);
assert_eq!(
MultiTransactor::deposit_asset(
&(Here, 1u128).into(),
&Here.into(),
&XcmContext::with_message_hash([0; 32]),
),
Ok(()),
);
}
}