fungibles_adapter.rs 9.61 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 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/>.

Alexander Popiak's avatar
Alexander Popiak committed
17
18
//! Adapters to work with `frame_support::traits::tokens::fungibles` through XCM.

Gavin Wood's avatar
Gavin Wood committed
19
use sp_std::{prelude::*, result, marker::PhantomData, borrow::Borrow};
20
use xcm::v0::{Error as XcmError, Result, MultiAsset, MultiLocation, Junction};
21
use frame_support::traits::{Get, tokens::fungibles, Contains};
Alexander Popiak's avatar
Alexander Popiak committed
22
use xcm_executor::traits::{TransactAsset, Convert, MatchesFungibles, Error as MatchError};
23

Denis_P's avatar
Denis_P committed
24
/// Converter struct implementing `AssetIdConversion` converting a numeric asset ID (must be `TryFrom/TryInto<u128>`) into
Alexander Popiak's avatar
Alexander Popiak committed
25
26
/// a `GeneralIndex` junction, prefixed by some `MultiLocation` value. The `MultiLocation` value will typically be a
/// `PalletInstance` junction.
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
pub struct AsPrefixedGeneralIndex<Prefix, AssetId, ConvertAssetId>(PhantomData<(Prefix, AssetId, ConvertAssetId)>);
impl<
	Prefix: Get<MultiLocation>,
	AssetId: Clone,
	ConvertAssetId: Convert<u128, AssetId>,
> Convert<MultiLocation, AssetId> for AsPrefixedGeneralIndex<Prefix, AssetId, ConvertAssetId> {
	fn convert_ref(id: impl Borrow<MultiLocation>) -> result::Result<AssetId, ()> {
		let prefix = Prefix::get();
		let id = id.borrow();
		if !prefix.iter().enumerate().all(|(index, item)| id.at(index) == Some(item)) {
			return Err(())
		}
		match id.at(prefix.len()) {
			Some(Junction::GeneralIndex { id }) => ConvertAssetId::convert_ref(id),
			_ => Err(()),
		}
	}
	fn reverse_ref(what: impl Borrow<AssetId>) -> result::Result<MultiLocation, ()> {
		let mut location = Prefix::get();
		let id = ConvertAssetId::reverse_ref(what)?;
		location.push(Junction::GeneralIndex { id }).map_err(|_| ())?;
		Ok(location)
	}
}

pub struct ConvertedConcreteAssetId<AssetId, Balance, ConvertAssetId, ConvertBalance>(
	PhantomData<(AssetId, Balance, ConvertAssetId, ConvertBalance)>
);
impl<
	AssetId: Clone,
	Balance: Clone,
	ConvertAssetId: Convert<MultiLocation, AssetId>,
	ConvertBalance: Convert<u128, Balance>,
> MatchesFungibles<AssetId, Balance> for
	ConvertedConcreteAssetId<AssetId, Balance, ConvertAssetId, ConvertBalance>
{
Alexander Popiak's avatar
Alexander Popiak committed
63
	fn matches_fungibles(a: &MultiAsset) -> result::Result<(AssetId, Balance), MatchError> {
64
65
		let (id, amount) = match a {
			MultiAsset::ConcreteFungible { id, amount } => (id, amount),
Alexander Popiak's avatar
Alexander Popiak committed
66
			_ => return Err(MatchError::AssetNotFound),
67
		};
Alexander Popiak's avatar
Alexander Popiak committed
68
69
		let what = ConvertAssetId::convert_ref(id).map_err(|_| MatchError::AssetIdConversionFailed)?;
		let amount = ConvertBalance::convert_ref(amount).map_err(|_| MatchError::AmountToBalanceConversionFailed)?;
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
		Ok((what, amount))
	}
}

pub struct ConvertedAbstractAssetId<AssetId, Balance, ConvertAssetId, ConvertBalance>(
	PhantomData<(AssetId, Balance, ConvertAssetId, ConvertBalance)>
);
impl<
	AssetId: Clone,
	Balance: Clone,
	ConvertAssetId: Convert<Vec<u8>, AssetId>,
	ConvertBalance: Convert<u128, Balance>,
> MatchesFungibles<AssetId, Balance> for
	ConvertedAbstractAssetId<AssetId, Balance, ConvertAssetId, ConvertBalance>
{
Alexander Popiak's avatar
Alexander Popiak committed
85
	fn matches_fungibles(a: &MultiAsset) -> result::Result<(AssetId, Balance), MatchError> {
86
87
		let (id, amount) = match a {
			MultiAsset::AbstractFungible { id, amount } => (id, amount),
Alexander Popiak's avatar
Alexander Popiak committed
88
			_ => return Err(MatchError::AssetNotFound),
89
		};
Alexander Popiak's avatar
Alexander Popiak committed
90
91
		let what = ConvertAssetId::convert_ref(id).map_err(|_| MatchError::AssetIdConversionFailed)?;
		let amount = ConvertBalance::convert_ref(amount).map_err(|_| MatchError::AmountToBalanceConversionFailed)?;
92
93
94
95
		Ok((what, amount))
	}
}

Gavin Wood's avatar
Gavin Wood committed
96
pub struct FungiblesTransferAdapter<Assets, Matcher, AccountIdConverter, AccountId>(
97
98
	PhantomData<(Assets, Matcher, AccountIdConverter, AccountId)>
);
Gavin Wood's avatar
Gavin Wood committed
99
100
101
102
103
104
105
106
107
108
109
110
111
112
impl<
	Assets: fungibles::Transfer<AccountId>,
	Matcher: MatchesFungibles<Assets::AssetId, Assets::Balance>,
	AccountIdConverter: Convert<MultiLocation, AccountId>,
	AccountId: Clone,	// can't get away without it since Currency is generic over it.
> TransactAsset for FungiblesTransferAdapter<Assets, Matcher, AccountIdConverter, AccountId> {
	fn transfer_asset(
		what: &MultiAsset,
		from: &MultiLocation,
		to: &MultiLocation,
	) -> result::Result<xcm_executor::Assets, XcmError> {
		// Check we handle this asset.
		let (asset_id, amount) = Matcher::matches_fungibles(what)?;
		let source = AccountIdConverter::convert_ref(from)
Alexander Popiak's avatar
Alexander Popiak committed
113
			.map_err(|()| MatchError::AccountIdConversionFailed)?;
Gavin Wood's avatar
Gavin Wood committed
114
		let dest = AccountIdConverter::convert_ref(to)
Alexander Popiak's avatar
Alexander Popiak committed
115
			.map_err(|()| MatchError::AccountIdConversionFailed)?;
Gavin Wood's avatar
Gavin Wood committed
116
117
118
119
120
		Assets::transfer(asset_id, &source, &dest, amount, true)
			.map_err(|e| XcmError::FailedToTransactAsset(e.into()))?;
		Ok(what.clone().into())
	}
}
121

122
123
pub struct FungiblesMutateAdapter<Assets, Matcher, AccountIdConverter, AccountId, CheckAsset, CheckingAccount>(
	PhantomData<(Assets, Matcher, AccountIdConverter, AccountId, CheckAsset, CheckingAccount)>
Gavin Wood's avatar
Gavin Wood committed
124
);
125
impl<
Gavin Wood's avatar
Gavin Wood committed
126
	Assets: fungibles::Mutate<AccountId>,
127
	Matcher: MatchesFungibles<Assets::AssetId, Assets::Balance>,
Gavin Wood's avatar
Gavin Wood committed
128
129
	AccountIdConverter: Convert<MultiLocation, AccountId>,
	AccountId: Clone,	// can't get away without it since Currency is generic over it.
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
	CheckAsset: Contains<Assets::AssetId>,
	CheckingAccount: Get<AccountId>,
> TransactAsset for FungiblesMutateAdapter<Assets, Matcher, AccountIdConverter, AccountId, CheckAsset, CheckingAccount> {
	fn can_check_in(_origin: &MultiLocation, what: &MultiAsset) -> Result {
		// Check we handle this asset.
		let (asset_id, amount) = Matcher::matches_fungibles(what)?;
		if CheckAsset::contains(&asset_id) {
			// This is an asset whose teleports we track.
			let checking_account = CheckingAccount::get();
			Assets::can_withdraw(asset_id, &checking_account, amount)
				.into_result()
				.map_err(|_| XcmError::NotWithdrawable)?;
		}
		Ok(())
	}

	fn check_in(_origin: &MultiLocation, what: &MultiAsset) {
		if let Ok((asset_id, amount)) = Matcher::matches_fungibles(what) {
			if CheckAsset::contains(&asset_id) {
				let checking_account = CheckingAccount::get();
				let ok = Assets::burn_from(asset_id, &checking_account, amount).is_ok();
				debug_assert!(ok, "`can_check_in` must have returned `true` immediately prior; qed");
			}
		}
	}

	fn check_out(_dest: &MultiLocation, what: &MultiAsset) {
		if let Ok((asset_id, amount)) = Matcher::matches_fungibles(what) {
			if CheckAsset::contains(&asset_id) {
				let checking_account = CheckingAccount::get();
				let ok = Assets::mint_into(asset_id, &checking_account, amount).is_ok();
				debug_assert!(ok, "`mint_into` cannot generally fail; qed");
			}
		}
	}
165
166
167
168

	fn deposit_asset(what: &MultiAsset, who: &MultiLocation) -> Result {
		// Check we handle this asset.
		let (asset_id, amount) = Matcher::matches_fungibles(what)?;
Gavin Wood's avatar
Gavin Wood committed
169
		let who = AccountIdConverter::convert_ref(who)
Alexander Popiak's avatar
Alexander Popiak committed
170
			.map_err(|()| MatchError::AccountIdConversionFailed)?;
thiolliere's avatar
thiolliere committed
171
		Assets::mint_into(asset_id, &who, amount)
172
173
174
175
176
177
			.map_err(|e| XcmError::FailedToTransactAsset(e.into()))
	}

	fn withdraw_asset(
		what: &MultiAsset,
		who: &MultiLocation
Gavin Wood's avatar
Gavin Wood committed
178
	) -> result::Result<xcm_executor::Assets, XcmError> {
179
180
		// Check we handle this asset.
		let (asset_id, amount) = Matcher::matches_fungibles(what)?;
Gavin Wood's avatar
Gavin Wood committed
181
		let who = AccountIdConverter::convert_ref(who)
Alexander Popiak's avatar
Alexander Popiak committed
182
			.map_err(|()| MatchError::AccountIdConversionFailed)?;
thiolliere's avatar
thiolliere committed
183
		Assets::burn_from(asset_id, &who, amount)
184
			.map_err(|e| XcmError::FailedToTransactAsset(e.into()))?;
Gavin Wood's avatar
Gavin Wood committed
185
186
187
188
		Ok(what.clone().into())
	}
}

189
190
pub struct FungiblesAdapter<Assets, Matcher, AccountIdConverter, AccountId, CheckAsset, CheckingAccount>(
	PhantomData<(Assets, Matcher, AccountIdConverter, AccountId, CheckAsset, CheckingAccount)>
Gavin Wood's avatar
Gavin Wood committed
191
192
193
194
195
196
);
impl<
	Assets: fungibles::Mutate<AccountId> + fungibles::Transfer<AccountId>,
	Matcher: MatchesFungibles<Assets::AssetId, Assets::Balance>,
	AccountIdConverter: Convert<MultiLocation, AccountId>,
	AccountId: Clone,	// can't get away without it since Currency is generic over it.
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
	CheckAsset: Contains<Assets::AssetId>,
	CheckingAccount: Get<AccountId>,
> TransactAsset for FungiblesAdapter<Assets, Matcher, AccountIdConverter, AccountId, CheckAsset, CheckingAccount> {
	fn can_check_in(origin: &MultiLocation, what: &MultiAsset) -> Result {
		FungiblesMutateAdapter::<Assets, Matcher, AccountIdConverter, AccountId, CheckAsset, CheckingAccount>
			::can_check_in(origin, what)
	}

	fn check_in(origin: &MultiLocation, what: &MultiAsset) {
		FungiblesMutateAdapter::<Assets, Matcher, AccountIdConverter, AccountId, CheckAsset, CheckingAccount>
			::check_in(origin, what)
	}

	fn check_out(dest: &MultiLocation, what: &MultiAsset) {
		FungiblesMutateAdapter::<Assets, Matcher, AccountIdConverter, AccountId, CheckAsset, CheckingAccount>
			::check_out(dest, what)
	}
Gavin Wood's avatar
Gavin Wood committed
214
215

	fn deposit_asset(what: &MultiAsset, who: &MultiLocation) -> Result {
216
217
		FungiblesMutateAdapter::<Assets, Matcher, AccountIdConverter, AccountId, CheckAsset, CheckingAccount>
			::deposit_asset(what, who)
Gavin Wood's avatar
Gavin Wood committed
218
219
220
221
222
223
	}

	fn withdraw_asset(
		what: &MultiAsset,
		who: &MultiLocation
	) -> result::Result<xcm_executor::Assets, XcmError> {
224
225
		FungiblesMutateAdapter::<Assets, Matcher, AccountIdConverter, AccountId, CheckAsset, CheckingAccount>
			::withdraw_asset(what, who)
Gavin Wood's avatar
Gavin Wood committed
226
227
228
229
230
231
232
233
	}

	fn transfer_asset(
		what: &MultiAsset,
		from: &MultiLocation,
		to: &MultiLocation,
	) -> result::Result<xcm_executor::Assets, XcmError> {
		FungiblesTransferAdapter::<Assets, Matcher, AccountIdConverter, AccountId>::transfer_asset(what, from, to)
234
235
	}
}