1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
// 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 sp_std::result::Result;
use xcm::latest::{Error as XcmError, MultiAsset, MultiLocation, Result as XcmResult};

/// Facility for asset transacting.
///
/// This should work with as many asset/location combinations as possible. Locations to support may include non-account
/// locations such as a `MultiLocation::X1(Junction::Parachain)`. Different chains may handle them in different ways.
///
/// 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`.
	///
	/// 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 {
		Err(XcmError::Unimplemented)
	}

	/// An asset has been teleported in from the given origin. This should do whatever housekeeping is needed.
	///
	/// NOTE: This will make only a best-effort at bookkeeping. The caller should ensure that `can_check_in` has
	/// returned with `Ok` in order to guarantee that this operation proceeds properly.
	///
	/// Implementation note: In general this will do one of two things: On chains where the asset is native,
	/// it will reduce the assets from a special "teleported" account so that a) total-issuance is preserved;
	/// and b) to ensure that no more assets can be teleported in than were teleported out overall (this should
	/// not be needed if the teleporting chains are to be trusted, but better to be safe than sorry). On chains
	/// where the asset is not native then it will generally just be a no-op.
	///
	/// 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) {}

	/// An asset has been teleported out to the given destination. This should do whatever housekeeping is needed.
	///
	/// Implementation note: In general this will do one of two things: On chains where the asset is native,
	/// it will increase the assets in a special "teleported" account so that a) total-issuance is preserved; and
	/// b) to ensure that no more assets can be teleported in than were teleported out overall (this should not
	/// be needed if the teleporting chains are to be trusted, but better to be safe than sorry). On chains where
	/// the asset is not native then it will generally just be a no-op.
	///
	/// 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) {}

	/// 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 {
		Err(XcmError::Unimplemented)
	}

	/// Withdraw the given asset from the consensus system. Return the actual asset(s) withdrawn,
	/// which should always be equal to `_what`.
	///
	/// Implementations should return `XcmError::FailedToTransactAsset` if withdraw failed.
	fn withdraw_asset(_what: &MultiAsset, _who: &MultiLocation) -> Result<Assets, XcmError> {
		Err(XcmError::Unimplemented)
	}

	/// Move an `asset` `from` one location in `to` another location.
	///
	/// Returns `XcmError::FailedToTransactAsset` if transfer failed.
	///
	/// ## Notes
	/// This function is meant to only be implemented by the type implementing `TransactAsset`, and
	/// not be called directly. Most common API usages will instead call `transfer_asset`, which in
	/// turn has a default implementation that calls `internal_transfer_asset`. As such, **please
	/// do not call this method directly unless you know what you're doing**.
	fn internal_transfer_asset(
		_asset: &MultiAsset,
		_from: &MultiLocation,
		_to: &MultiLocation,
	) -> Result<Assets, XcmError> {
		Err(XcmError::Unimplemented)
	}

	/// Move an `asset` `from` one location in `to` another location.
	///
	/// Attempts to use `internal_transfer_asset` and if not available then falls back to using a
	/// two-part withdraw/deposit.
	fn transfer_asset(
		asset: &MultiAsset,
		from: &MultiLocation,
		to: &MultiLocation,
	) -> Result<Assets, XcmError> {
		match Self::internal_transfer_asset(asset, from, to) {
			Err(XcmError::Unimplemented) => {
				let assets = Self::withdraw_asset(asset, from)?;
				// Not a very forgiving attitude; once we implement roll-backs then it'll be nicer.
				Self::deposit_asset(asset, to)?;
				Ok(assets)
			},
			result => result,
		}
	}
}

#[impl_trait_for_tuples::impl_for_tuples(30)]
impl TransactAsset for Tuple {
	fn can_check_in(origin: &MultiLocation, what: &MultiAsset) -> XcmResult {
		for_tuples!( #(
			match Tuple::can_check_in(origin, what) {
				Err(XcmError::AssetNotFound) | Err(XcmError::Unimplemented) => (),
				r => return r,
			}
		)* );
		log::trace!(
			target: "xcm::TransactAsset::can_check_in",
			"asset not found: what: {:?}, origin: {:?}",
			what,
			origin,
		);
		Err(XcmError::AssetNotFound)
	}

	fn check_in(origin: &MultiLocation, what: &MultiAsset) {
		for_tuples!( #(
			Tuple::check_in(origin, what);
		)* );
	}

	fn check_out(dest: &MultiLocation, what: &MultiAsset) {
		for_tuples!( #(
			Tuple::check_out(dest, what);
		)* );
	}

	fn deposit_asset(what: &MultiAsset, who: &MultiLocation) -> XcmResult {
		for_tuples!( #(
			match Tuple::deposit_asset(what, who) {
				Err(XcmError::AssetNotFound) | Err(XcmError::Unimplemented) => (),
				r => return r,
			}
		)* );
		log::trace!(
			target: "xcm::TransactAsset::deposit_asset",
			"did not deposit asset: what: {:?}, who: {:?}",
			what,
			who,
		);
		Err(XcmError::AssetNotFound)
	}

	fn withdraw_asset(what: &MultiAsset, who: &MultiLocation) -> Result<Assets, XcmError> {
		for_tuples!( #(
			match Tuple::withdraw_asset(what, who) {
				Err(XcmError::AssetNotFound) | Err(XcmError::Unimplemented) => (),
				r => return r,
			}
		)* );
		log::trace!(
			target: "xcm::TransactAsset::withdraw_asset",
			"did not withdraw asset: what: {:?}, who: {:?}",
			what,
			who,
		);
		Err(XcmError::AssetNotFound)
	}

	fn internal_transfer_asset(
		what: &MultiAsset,
		from: &MultiLocation,
		to: &MultiLocation,
	) -> Result<Assets, XcmError> {
		for_tuples!( #(
			match Tuple::internal_transfer_asset(what, from, to) {
				Err(XcmError::AssetNotFound) | Err(XcmError::Unimplemented) => (),
				r => return r,
			}
		)* );
		log::trace!(
			target: "xcm::TransactAsset::internal_transfer_asset",
			"did not transfer asset: what: {:?}, from: {:?}, to: {:?}",
			what,
			from,
			to,
		);
		Err(XcmError::AssetNotFound)
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use xcm::latest::Junctions::Here;

	pub struct UnimplementedTransactor;
	impl TransactAsset for UnimplementedTransactor {}

	pub struct NotFoundTransactor;
	impl TransactAsset for NotFoundTransactor {
		fn can_check_in(_origin: &MultiLocation, _what: &MultiAsset) -> XcmResult {
			Err(XcmError::AssetNotFound)
		}

		fn deposit_asset(_what: &MultiAsset, _who: &MultiLocation) -> XcmResult {
			Err(XcmError::AssetNotFound)
		}

		fn withdraw_asset(_what: &MultiAsset, _who: &MultiLocation) -> Result<Assets, XcmError> {
			Err(XcmError::AssetNotFound)
		}

		fn internal_transfer_asset(
			_what: &MultiAsset,
			_from: &MultiLocation,
			_to: &MultiLocation,
		) -> Result<Assets, XcmError> {
			Err(XcmError::AssetNotFound)
		}
	}

	pub struct OverflowTransactor;
	impl TransactAsset for OverflowTransactor {
		fn can_check_in(_origin: &MultiLocation, _what: &MultiAsset) -> XcmResult {
			Err(XcmError::Overflow)
		}

		fn deposit_asset(_what: &MultiAsset, _who: &MultiLocation) -> XcmResult {
			Err(XcmError::Overflow)
		}

		fn withdraw_asset(_what: &MultiAsset, _who: &MultiLocation) -> Result<Assets, XcmError> {
			Err(XcmError::Overflow)
		}

		fn internal_transfer_asset(
			_what: &MultiAsset,
			_from: &MultiLocation,
			_to: &MultiLocation,
		) -> Result<Assets, XcmError> {
			Err(XcmError::Overflow)
		}
	}

	pub struct SuccessfulTransactor;
	impl TransactAsset for SuccessfulTransactor {
		fn can_check_in(_origin: &MultiLocation, _what: &MultiAsset) -> XcmResult {
			Ok(())
		}

		fn deposit_asset(_what: &MultiAsset, _who: &MultiLocation) -> XcmResult {
			Ok(())
		}

		fn withdraw_asset(_what: &MultiAsset, _who: &MultiLocation) -> Result<Assets, XcmError> {
			Ok(Assets::default())
		}

		fn internal_transfer_asset(
			_what: &MultiAsset,
			_from: &MultiLocation,
			_to: &MultiLocation,
		) -> Result<Assets, XcmError> {
			Ok(Assets::default())
		}
	}

	#[test]
	fn defaults_to_asset_not_found() {
		type MultiTransactor =
			(UnimplementedTransactor, NotFoundTransactor, UnimplementedTransactor);

		assert_eq!(
			MultiTransactor::deposit_asset(&(Here, 1).into(), &Here.into()),
			Err(XcmError::AssetNotFound)
		);
	}

	#[test]
	fn unimplemented_and_not_found_continue_iteration() {
		type MultiTransactor = (UnimplementedTransactor, NotFoundTransactor, SuccessfulTransactor);

		assert_eq!(MultiTransactor::deposit_asset(&(Here, 1).into(), &Here.into()), Ok(()),);
	}

	#[test]
	fn unexpected_error_stops_iteration() {
		type MultiTransactor = (OverflowTransactor, SuccessfulTransactor);

		assert_eq!(
			MultiTransactor::deposit_asset(&(Here, 1).into(), &Here.into()),
			Err(XcmError::Overflow)
		);
	}

	#[test]
	fn success_stops_iteration() {
		type MultiTransactor = (SuccessfulTransactor, OverflowTransactor);

		assert_eq!(MultiTransactor::deposit_asset(&(Here, 1).into(), &Here.into()), Ok(()),);
	}
}