referrerpolicy=no-referrer-when-downgrade

snowbridge_core/
reward.rs

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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: 2023 Snowfork <hello@snowfork.com>

extern crate alloc;

use crate::reward::RewardPaymentError::{ChargeFeesFailure, XcmSendFailure};
use bp_relayers::PaymentProcedure;
use frame_support::dispatch::GetDispatchInfo;
use scale_info::TypeInfo;
use sp_runtime::{
	codec::{Decode, Encode},
	traits::Get,
	DispatchError,
};
use sp_std::{fmt::Debug, marker::PhantomData};
use xcm::{
	opaque::latest::prelude::Xcm,
	prelude::{ExecuteXcm, Junction::*, Location, SendXcm, *},
};

/// Error related to paying out relayer rewards.
#[derive(Debug, Encode, Decode)]
pub enum RewardPaymentError {
	/// The XCM to mint the reward on AssetHub could not be sent.
	XcmSendFailure,
	/// The delivery fee to send the XCM could not be charged.
	ChargeFeesFailure,
}

impl From<RewardPaymentError> for DispatchError {
	fn from(e: RewardPaymentError) -> DispatchError {
		match e {
			XcmSendFailure => DispatchError::Other("xcm send failure"),
			ChargeFeesFailure => DispatchError::Other("charge fees error"),
		}
	}
}

/// Reward payment procedure that sends a XCM to AssetHub to mint the reward (foreign asset)
/// into the provided beneficiary account.
pub struct PayAccountOnLocation<
	Relayer,
	RewardBalance,
	EthereumNetwork,
	AssetHubLocation,
	InboundQueueLocation,
	XcmSender,
	XcmExecutor,
	Call,
>(
	PhantomData<(
		Relayer,
		RewardBalance,
		EthereumNetwork,
		AssetHubLocation,
		InboundQueueLocation,
		XcmSender,
		XcmExecutor,
		Call,
	)>,
);

impl<
		Relayer,
		RewardBalance,
		EthereumNetwork,
		AssetHubLocation,
		InboundQueueLocation,
		XcmSender,
		XcmExecutor,
		Call,
	> PaymentProcedure<Relayer, (), RewardBalance>
	for PayAccountOnLocation<
		Relayer,
		RewardBalance,
		EthereumNetwork,
		AssetHubLocation,
		InboundQueueLocation,
		XcmSender,
		XcmExecutor,
		Call,
	>
where
	Relayer: Clone
		+ Debug
		+ Decode
		+ Encode
		+ Eq
		+ TypeInfo
		+ Into<sp_runtime::AccountId32>
		+ Into<Location>,
	EthereumNetwork: Get<NetworkId>,
	InboundQueueLocation: Get<InteriorLocation>,
	AssetHubLocation: Get<Location>,
	XcmSender: SendXcm,
	RewardBalance: Into<u128> + Clone,
	XcmExecutor: ExecuteXcm<Call>,
	Call: Decode + GetDispatchInfo,
{
	type Error = DispatchError;
	type Beneficiary = Location;

	fn pay_reward(
		relayer: &Relayer,
		_: (),
		reward: RewardBalance,
		beneficiary: Self::Beneficiary,
	) -> Result<(), Self::Error> {
		let ethereum_location = Location::new(2, [GlobalConsensus(EthereumNetwork::get())]);
		let assets: Asset = (ethereum_location.clone(), reward.into()).into();

		let xcm: Xcm<()> = alloc::vec![
			UnpaidExecution { weight_limit: Unlimited, check_origin: None },
			DescendOrigin(InboundQueueLocation::get().into()),
			UniversalOrigin(GlobalConsensus(EthereumNetwork::get())),
			ReserveAssetDeposited(assets.into()),
			DepositAsset { assets: AllCounted(1).into(), beneficiary },
		]
		.into();

		let (ticket, fee) =
			validate_send::<XcmSender>(AssetHubLocation::get(), xcm).map_err(|_| XcmSendFailure)?;
		XcmExecutor::charge_fees(relayer.clone(), fee).map_err(|_| ChargeFeesFailure)?;
		XcmSender::deliver(ticket).map_err(|_| XcmSendFailure)?;

		Ok(())
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use frame_support::parameter_types;
	use sp_runtime::AccountId32;

	#[derive(Clone, Debug, Decode, Encode, Eq, PartialEq, TypeInfo)]
	pub struct MockRelayer(pub AccountId32);

	impl From<MockRelayer> for AccountId32 {
		fn from(m: MockRelayer) -> Self {
			m.0
		}
	}

	impl From<MockRelayer> for Location {
		fn from(_m: MockRelayer) -> Self {
			// For simplicity, return a dummy location
			Location::new(1, Here)
		}
	}

	pub enum BridgeReward {
		Snowbridge,
	}

	parameter_types! {
		pub AssetHubLocation: Location = Location::new(1,[Parachain(1000)]);
		pub InboundQueueLocation: InteriorLocation = [PalletInstance(84)].into();
		pub EthereumNetwork: NetworkId = NetworkId::Ethereum { chain_id: 11155111 };
		pub const DefaultMyRewardKind: BridgeReward = BridgeReward::Snowbridge;
	}

	pub enum Weightless {}
	impl PreparedMessage for Weightless {
		fn weight_of(&self) -> Weight {
			unreachable!();
		}
	}

	pub struct MockXcmExecutor;
	impl<C> ExecuteXcm<C> for MockXcmExecutor {
		type Prepared = Weightless;
		fn prepare(message: Xcm<C>) -> Result<Self::Prepared, Xcm<C>> {
			Err(message)
		}
		fn execute(
			_: impl Into<Location>,
			_: Self::Prepared,
			_: &mut XcmHash,
			_: Weight,
		) -> Outcome {
			unreachable!()
		}
		fn charge_fees(_: impl Into<Location>, _: Assets) -> xcm::latest::Result {
			Ok(())
		}
	}

	#[derive(Debug, Decode, Default)]
	pub struct MockCall;
	impl GetDispatchInfo for MockCall {
		fn get_dispatch_info(&self) -> frame_support::dispatch::DispatchInfo {
			Default::default()
		}
	}

	pub struct MockXcmSender;
	impl SendXcm for MockXcmSender {
		type Ticket = Xcm<()>;

		fn validate(
			dest: &mut Option<Location>,
			xcm: &mut Option<Xcm<()>>,
		) -> SendResult<Self::Ticket> {
			if let Some(location) = dest {
				match location.unpack() {
					(_, [Parachain(1001)]) => return Err(SendError::NotApplicable),
					_ => Ok((xcm.clone().unwrap(), Assets::default())),
				}
			} else {
				Ok((xcm.clone().unwrap(), Assets::default()))
			}
		}

		fn deliver(xcm: Self::Ticket) -> core::result::Result<XcmHash, SendError> {
			let hash = xcm.using_encoded(sp_io::hashing::blake2_256);
			Ok(hash)
		}
	}

	#[test]
	fn pay_reward_success() {
		let relayer = MockRelayer(AccountId32::new([1u8; 32]));
		let beneficiary = Location::new(1, Here);
		let reward = 1_000u128;

		type TestedPayAccountOnLocation = PayAccountOnLocation<
			MockRelayer,
			u128,
			EthereumNetwork,
			AssetHubLocation,
			InboundQueueLocation,
			MockXcmSender,
			MockXcmExecutor,
			MockCall,
		>;

		let result = TestedPayAccountOnLocation::pay_reward(&relayer, (), reward, beneficiary);

		assert!(result.is_ok());
	}

	#[test]
	fn pay_reward_fails_on_xcm_validate_xcm() {
		struct FailingXcmValidator;
		impl SendXcm for FailingXcmValidator {
			type Ticket = ();

			fn validate(
				_dest: &mut Option<Location>,
				_xcm: &mut Option<Xcm<()>>,
			) -> SendResult<Self::Ticket> {
				Err(SendError::NotApplicable)
			}

			fn deliver(xcm: Self::Ticket) -> core::result::Result<XcmHash, SendError> {
				let hash = xcm.using_encoded(sp_io::hashing::blake2_256);
				Ok(hash)
			}
		}

		type FailingSenderPayAccount = PayAccountOnLocation<
			MockRelayer,
			u128,
			EthereumNetwork,
			AssetHubLocation,
			InboundQueueLocation,
			FailingXcmValidator,
			MockXcmExecutor,
			MockCall,
		>;

		let relayer = MockRelayer(AccountId32::new([1u8; 32]));
		let reward = 1_000u128;
		let beneficiary = Location::new(1, Here);
		let result = FailingSenderPayAccount::pay_reward(&relayer, (), reward, beneficiary);

		assert!(result.is_err());
		let err_str = format!("{:?}", result.err().unwrap());
		assert!(
			err_str.contains("xcm send failure"),
			"Expected xcm send failure error, got {:?}",
			err_str
		);
	}

	#[test]
	fn pay_reward_fails_on_charge_fees() {
		struct FailingXcmExecutor;
		impl<C> ExecuteXcm<C> for FailingXcmExecutor {
			type Prepared = Weightless;
			fn prepare(message: Xcm<C>) -> Result<Self::Prepared, Xcm<C>> {
				Err(message)
			}
			fn execute(
				_: impl Into<Location>,
				_: Self::Prepared,
				_: &mut XcmHash,
				_: Weight,
			) -> Outcome {
				unreachable!()
			}
			fn charge_fees(_: impl Into<Location>, _: Assets) -> xcm::latest::Result {
				Err(crate::reward::SendError::Fees.into())
			}
		}

		type FailingExecutorPayAccount = PayAccountOnLocation<
			MockRelayer,
			u128,
			EthereumNetwork,
			AssetHubLocation,
			InboundQueueLocation,
			MockXcmSender,
			FailingXcmExecutor,
			MockCall,
		>;

		let relayer = MockRelayer(AccountId32::new([3u8; 32]));
		let beneficiary = Location::new(1, Here);
		let reward = 500u128;
		let result = FailingExecutorPayAccount::pay_reward(&relayer, (), reward, beneficiary);

		assert!(result.is_err());
		let err_str = format!("{:?}", result.err().unwrap());
		assert!(
			err_str.contains("charge fees error"),
			"Expected 'charge fees error', got {:?}",
			err_str
		);
	}

	#[test]
	fn pay_reward_fails_on_delivery() {
		#[derive(Default)]
		struct FailingDeliveryXcmSender;
		impl SendXcm for FailingDeliveryXcmSender {
			type Ticket = ();

			fn validate(
				_dest: &mut Option<Location>,
				_xcm: &mut Option<Xcm<()>>,
			) -> SendResult<Self::Ticket> {
				Ok(((), Assets::from(vec![])))
			}

			fn deliver(_xcm: Self::Ticket) -> core::result::Result<XcmHash, SendError> {
				Err(SendError::NotApplicable)
			}
		}

		type FailingDeliveryPayAccount = PayAccountOnLocation<
			MockRelayer,
			u128,
			EthereumNetwork,
			AssetHubLocation,
			InboundQueueLocation,
			FailingDeliveryXcmSender,
			MockXcmExecutor,
			MockCall,
		>;

		let relayer = MockRelayer(AccountId32::new([4u8; 32]));
		let beneficiary = Location::new(1, Here);
		let reward = 123u128;
		let result = FailingDeliveryPayAccount::pay_reward(&relayer, (), reward, beneficiary);

		assert!(result.is_err());
		let err_str = format!("{:?}", result.err().unwrap());
		assert!(
			err_str.contains("xcm send failure"),
			"Expected 'xcm delivery failure', got {:?}",
			err_str
		);
	}
}