1
// Copyright 2019-2025 PureStake Inc.
2
// This file is part of Moonbeam.
3

            
4
// Moonbeam is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8

            
9
// Moonbeam is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13

            
14
// You should have received a copy of the GNU General Public License
15
// along with Moonbeam.  If not, see <http://www.gnu.org/licenses/>.
16

            
17
//! Scheduled requests functionality for delegators
18

            
19
use crate::pallet::{
20
	BalanceOf, CandidateInfo, Config, DelegationScheduledRequests,
21
	DelegationScheduledRequestsPerCollator, DelegatorState, Error, Event, Pallet, Round,
22
	RoundIndex, Total,
23
};
24
use crate::weights::WeightInfo;
25
use crate::{auto_compound::AutoCompoundDelegations, Delegator};
26
use frame_support::dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo};
27
use frame_support::ensure;
28
use frame_support::traits::Get;
29
use frame_support::BoundedVec;
30
use parity_scale_codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen};
31
use scale_info::TypeInfo;
32
use sp_runtime::{
33
	traits::{Saturating, Zero},
34
	RuntimeDebug,
35
};
36

            
37
/// An action that can be performed upon a delegation
38
#[derive(
39
	Clone,
40
	Eq,
41
	PartialEq,
42
	Encode,
43
	Decode,
44
	RuntimeDebug,
45
	TypeInfo,
46
	PartialOrd,
47
	Ord,
48
	DecodeWithMemTracking,
49
	MaxEncodedLen,
50
)]
51
pub enum DelegationAction<Balance> {
52
	Revoke(Balance),
53
	Decrease(Balance),
54
}
55

            
56
impl<Balance: Copy> DelegationAction<Balance> {
57
	/// Returns the wrapped amount value.
58
97
	pub fn amount(&self) -> Balance {
59
97
		match self {
60
33
			DelegationAction::Revoke(amount) => *amount,
61
64
			DelegationAction::Decrease(amount) => *amount,
62
		}
63
97
	}
64
}
65

            
66
/// Represents a scheduled request that defines a [`DelegationAction`]. The request is executable
67
/// iff the provided [`RoundIndex`] is achieved.
68
#[derive(
69
	Clone,
70
	Eq,
71
	PartialEq,
72
	Encode,
73
	Decode,
74
	RuntimeDebug,
75
	TypeInfo,
76
	PartialOrd,
77
	Ord,
78
	DecodeWithMemTracking,
79
	MaxEncodedLen,
80
)]
81
pub struct ScheduledRequest<Balance> {
82
	pub when_executable: RoundIndex,
83
	pub action: DelegationAction<Balance>,
84
}
85

            
86
/// Represents a cancelled scheduled request for emitting an event.
87
#[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, TypeInfo, DecodeWithMemTracking)]
88
pub struct CancelledScheduledRequest<Balance> {
89
	pub when_executable: RoundIndex,
90
	pub action: DelegationAction<Balance>,
91
}
92

            
93
impl<B> From<ScheduledRequest<B>> for CancelledScheduledRequest<B> {
94
10
	fn from(request: ScheduledRequest<B>) -> Self {
95
10
		CancelledScheduledRequest {
96
10
			when_executable: request.when_executable,
97
10
			action: request.action,
98
10
		}
99
10
	}
100
}
101

            
102
impl<T: Config> Pallet<T> {
103
	/// Schedules a [DelegationAction::Revoke] for the delegator, towards a given collator.
104
52
	pub(crate) fn delegation_schedule_revoke(
105
52
		collator: T::AccountId,
106
52
		delegator: T::AccountId,
107
52
	) -> DispatchResultWithPostInfo {
108
52
		let mut state = <DelegatorState<T>>::get(&delegator).ok_or(<Error<T>>::DelegatorDNE)?;
109
50
		let mut scheduled_requests = <DelegationScheduledRequests<T>>::get(&collator, &delegator);
110

            
111
50
		let actual_weight =
112
50
			<T as Config>::WeightInfo::schedule_revoke_delegation(scheduled_requests.len() as u32);
113

            
114
50
		let is_new_delegator = scheduled_requests.is_empty();
115

            
116
50
		ensure!(
117
50
			is_new_delegator,
118
1
			DispatchErrorWithPostInfo {
119
1
				post_info: Some(actual_weight).into(),
120
1
				error: <Error<T>>::PendingDelegationRequestAlreadyExists.into(),
121
1
			},
122
		);
123

            
124
		// This is the first scheduled request for this delegator towards this collator,
125
		// ensure we do not exceed the maximum number of delegators that can have pending
126
		// requests for the collator.
127
49
		let current = <DelegationScheduledRequestsPerCollator<T>>::get(&collator);
128
49
		if current >= Pallet::<T>::max_delegators_per_candidate() {
129
			return Err(DispatchErrorWithPostInfo {
130
				post_info: Some(actual_weight).into(),
131
				error: Error::<T>::ExceedMaxDelegationsPerDelegator.into(),
132
			});
133
49
		}
134

            
135
49
		let bonded_amount = state
136
49
			.get_bond_amount(&collator)
137
49
			.ok_or(<Error<T>>::DelegationDNE)?;
138
48
		let now = <Round<T>>::get().current;
139
48
		let when = now.saturating_add(T::RevokeDelegationDelay::get());
140
48
		scheduled_requests
141
48
			.try_push(ScheduledRequest {
142
48
				action: DelegationAction::Revoke(bonded_amount),
143
48
				when_executable: when,
144
48
			})
145
48
			.map_err(|_| DispatchErrorWithPostInfo {
146
				post_info: Some(actual_weight).into(),
147
				error: Error::<T>::ExceedMaxDelegationsPerDelegator.into(),
148
			})?;
149
48
		state.less_total = state.less_total.saturating_add(bonded_amount);
150

            
151
48
		<DelegationScheduledRequestsPerCollator<T>>::mutate(&collator, |c| {
152
48
			*c = c.saturating_add(1);
153
48
		});
154

            
155
48
		<DelegationScheduledRequests<T>>::insert(
156
48
			collator.clone(),
157
48
			delegator.clone(),
158
48
			scheduled_requests,
159
		);
160
48
		<DelegatorState<T>>::insert(delegator.clone(), state);
161

            
162
48
		Self::deposit_event(Event::DelegationRevocationScheduled {
163
48
			round: now,
164
48
			delegator,
165
48
			candidate: collator,
166
48
			scheduled_exit: when,
167
48
		});
168
48
		Ok(().into())
169
52
	}
170

            
171
	/// Schedules a [DelegationAction::Decrease] for the delegator, towards a given collator.
172
91
	pub(crate) fn delegation_schedule_bond_decrease(
173
91
		collator: T::AccountId,
174
91
		delegator: T::AccountId,
175
91
		decrease_amount: BalanceOf<T>,
176
91
	) -> DispatchResultWithPostInfo {
177
91
		let mut state = <DelegatorState<T>>::get(&delegator).ok_or(<Error<T>>::DelegatorDNE)?;
178
90
		let mut scheduled_requests = <DelegationScheduledRequests<T>>::get(&collator, &delegator);
179

            
180
90
		let actual_weight = <T as Config>::WeightInfo::schedule_delegator_bond_less(
181
90
			scheduled_requests.len() as u32,
182
		);
183

            
184
		// If this is the first scheduled request for this delegator towards this collator,
185
		// ensure we do not exceed the maximum number of delegators that can have pending
186
		// requests for the collator.
187
90
		let is_new_delegator = scheduled_requests.is_empty();
188
90
		if is_new_delegator {
189
34
			let current = <DelegationScheduledRequestsPerCollator<T>>::get(&collator);
190
34
			let max_delegators = Pallet::<T>::max_delegators_per_candidate();
191
34
			if current >= max_delegators {
192
1
				return Err(DispatchErrorWithPostInfo {
193
1
					post_info: Some(actual_weight).into(),
194
1
					error: Error::<T>::ExceedMaxDelegationsPerDelegator.into(),
195
1
				});
196
33
			}
197
56
		}
198

            
199
89
		ensure!(
200
89
			!scheduled_requests
201
89
				.iter()
202
1285
				.any(|req| matches!(req.action, DelegationAction::Revoke(_))),
203
2
			DispatchErrorWithPostInfo {
204
2
				post_info: Some(actual_weight).into(),
205
2
				error: <Error<T>>::PendingDelegationRequestAlreadyExists.into(),
206
2
			},
207
		);
208

            
209
87
		let bonded_amount = state
210
87
			.get_bond_amount(&collator)
211
87
			.ok_or(DispatchErrorWithPostInfo {
212
87
				post_info: Some(actual_weight).into(),
213
87
				error: <Error<T>>::DelegationDNE.into(),
214
87
			})?;
215
		// Per-request safety: a single decrease cannot exceed the current delegation
216
		// and must leave at least MinDelegation on that delegation.
217
85
		ensure!(
218
85
			bonded_amount > decrease_amount,
219
1
			DispatchErrorWithPostInfo {
220
1
				post_info: Some(actual_weight).into(),
221
1
				error: <Error<T>>::DelegatorBondBelowMin.into(),
222
1
			},
223
		);
224

            
225
		// Cumulative safety: multiple pending Decrease requests for the same
226
		// (collator, delegator) pair must also respect the MinDelegation
227
		// constraint when applied together. Otherwise, snapshots can become
228
		// inconsistent even if each request, in isolation, appears valid.
229
84
		let pending_decrease_total: BalanceOf<T> = scheduled_requests
230
84
			.iter()
231
1283
			.filter_map(|req| match req.action {
232
1280
				DelegationAction::Decrease(amount) => Some(amount),
233
				_ => None,
234
1280
			})
235
1283
			.fold(BalanceOf::<T>::zero(), |acc, amount| {
236
1280
				acc.saturating_add(amount)
237
1280
			});
238
84
		let total_decrease_after = pending_decrease_total.saturating_add(decrease_amount);
239
84
		let new_amount_after_all = bonded_amount.saturating_sub(total_decrease_after);
240
84
		ensure!(
241
84
			new_amount_after_all >= T::MinDelegation::get(),
242
2
			DispatchErrorWithPostInfo {
243
2
				post_info: Some(actual_weight).into(),
244
2
				error: <Error<T>>::DelegationBelowMin.into(),
245
2
			},
246
		);
247

            
248
		// Net Total is total after pending orders are executed
249
82
		let net_total = state.total().saturating_sub(state.less_total);
250
		// Net Total is always >= MinDelegation
251
82
		let max_subtracted_amount = net_total.saturating_sub(T::MinDelegation::get().into());
252
82
		ensure!(
253
82
			decrease_amount <= max_subtracted_amount,
254
			DispatchErrorWithPostInfo {
255
				post_info: Some(actual_weight).into(),
256
				error: <Error<T>>::DelegatorBondBelowMin.into(),
257
			},
258
		);
259

            
260
82
		let now = <Round<T>>::get().current;
261
82
		let when = now.saturating_add(T::DelegationBondLessDelay::get());
262
82
		scheduled_requests
263
82
			.try_push(ScheduledRequest {
264
82
				action: DelegationAction::Decrease(decrease_amount),
265
82
				when_executable: when,
266
82
			})
267
82
			.map_err(|_| DispatchErrorWithPostInfo {
268
1
				post_info: Some(actual_weight).into(),
269
1
				error: Error::<T>::ExceedMaxDelegationsPerDelegator.into(),
270
1
			})?;
271
81
		state.less_total = state.less_total.saturating_add(decrease_amount);
272
81
		if is_new_delegator {
273
29
			<DelegationScheduledRequestsPerCollator<T>>::mutate(&collator, |c| {
274
29
				*c = c.saturating_add(1);
275
29
			});
276
52
		}
277
81
		<DelegationScheduledRequests<T>>::insert(
278
81
			collator.clone(),
279
81
			delegator.clone(),
280
81
			scheduled_requests,
281
		);
282
81
		<DelegatorState<T>>::insert(delegator.clone(), state);
283

            
284
81
		Self::deposit_event(Event::DelegationDecreaseScheduled {
285
81
			delegator,
286
81
			candidate: collator,
287
81
			amount_to_decrease: decrease_amount,
288
81
			execute_round: when,
289
81
		});
290
81
		Ok(Some(actual_weight).into())
291
91
	}
292

            
293
	/// Cancels the delegator's existing [ScheduledRequest] towards a given collator.
294
10
	pub(crate) fn delegation_cancel_request(
295
10
		collator: T::AccountId,
296
10
		delegator: T::AccountId,
297
10
	) -> DispatchResultWithPostInfo {
298
10
		let mut state = <DelegatorState<T>>::get(&delegator).ok_or(<Error<T>>::DelegatorDNE)?;
299
10
		let mut scheduled_requests = <DelegationScheduledRequests<T>>::get(&collator, &delegator);
300
10
		let actual_weight =
301
10
			<T as Config>::WeightInfo::cancel_delegation_request(scheduled_requests.len() as u32);
302

            
303
10
		let request = Self::cancel_request_with_state(&mut state, &mut scheduled_requests).ok_or(
304
10
			DispatchErrorWithPostInfo {
305
10
				post_info: Some(actual_weight).into(),
306
10
				error: <Error<T>>::PendingDelegationRequestDNE.into(),
307
10
			},
308
		)?;
309

            
310
10
		if scheduled_requests.is_empty() {
311
10
			<DelegationScheduledRequestsPerCollator<T>>::mutate(&collator, |c| {
312
10
				*c = c.saturating_sub(1);
313
10
			});
314
10
			<DelegationScheduledRequests<T>>::remove(&collator, &delegator);
315
		} else {
316
			<DelegationScheduledRequests<T>>::insert(
317
				collator.clone(),
318
				delegator.clone(),
319
				scheduled_requests,
320
			);
321
		}
322
10
		<DelegatorState<T>>::insert(delegator.clone(), state);
323

            
324
10
		Self::deposit_event(Event::CancelledDelegationRequest {
325
10
			delegator,
326
10
			collator,
327
10
			cancelled_request: request.into(),
328
10
		});
329
10
		Ok(Some(actual_weight).into())
330
10
	}
331

            
332
12
	fn cancel_request_with_state(
333
12
		state: &mut Delegator<T::AccountId, BalanceOf<T>>,
334
12
		scheduled_requests: &mut BoundedVec<
335
12
			ScheduledRequest<BalanceOf<T>>,
336
12
			T::MaxScheduledRequestsPerDelegator,
337
12
		>,
338
12
	) -> Option<ScheduledRequest<BalanceOf<T>>> {
339
12
		if scheduled_requests.is_empty() {
340
1
			return None;
341
11
		}
342

            
343
		// `BoundedVec::remove` can panic, but we make sure it will not happen by
344
		// checking above that `scheduled_requests` is not empty.
345
11
		let request = scheduled_requests.remove(0);
346
11
		let amount = request.action.amount();
347
11
		state.less_total = state.less_total.saturating_sub(amount);
348
11
		Some(request)
349
12
	}
350

            
351
	/// Executes the delegator's existing [ScheduledRequest] towards a given collator.
352
39
	pub(crate) fn delegation_execute_scheduled_request(
353
39
		collator: T::AccountId,
354
39
		delegator: T::AccountId,
355
39
	) -> DispatchResultWithPostInfo {
356
39
		let mut state = <DelegatorState<T>>::get(&delegator).ok_or(<Error<T>>::DelegatorDNE)?;
357
39
		let mut scheduled_requests = <DelegationScheduledRequests<T>>::get(&collator, &delegator);
358
39
		let request = scheduled_requests
359
39
			.first()
360
39
			.ok_or(<Error<T>>::PendingDelegationRequestDNE)?;
361

            
362
39
		let now = <Round<T>>::get().current;
363
39
		ensure!(
364
39
			request.when_executable <= now,
365
			<Error<T>>::PendingDelegationRequestNotDueYet
366
		);
367

            
368
39
		match request.action {
369
23
			DelegationAction::Revoke(amount) => {
370
23
				let actual_weight =
371
23
					<T as Config>::WeightInfo::execute_delegator_revoke_delegation_worst();
372

            
373
				// revoking last delegation => leaving set of delegators
374
23
				let leaving = if state.delegations.0.len() == 1usize {
375
12
					true
376
				} else {
377
11
					ensure!(
378
11
						state.total().saturating_sub(T::MinDelegation::get().into()) >= amount,
379
						DispatchErrorWithPostInfo {
380
							post_info: Some(actual_weight).into(),
381
							error: <Error<T>>::DelegatorBondBelowMin.into(),
382
						}
383
					);
384
11
					false
385
				};
386

            
387
				// remove from pending requests
388
				// `BoundedVec::remove` can panic, but we make sure it will not happen by checking above that `scheduled_requests` is not empty.
389
23
				let amount = scheduled_requests.remove(0).action.amount();
390
23
				state.less_total = state.less_total.saturating_sub(amount);
391

            
392
				// remove delegation from delegator state
393
23
				state.rm_delegation::<T>(&collator);
394

            
395
				// remove delegation from auto-compounding info
396
23
				<AutoCompoundDelegations<T>>::remove_auto_compound(&collator, &delegator);
397

            
398
				// remove delegation from collator state delegations
399
23
				Self::delegator_leaves_candidate(collator.clone(), delegator.clone(), amount)
400
23
					.map_err(|err| DispatchErrorWithPostInfo {
401
						post_info: Some(actual_weight).into(),
402
						error: err,
403
					})?;
404
23
				Self::deposit_event(Event::DelegationRevoked {
405
23
					delegator: delegator.clone(),
406
23
					candidate: collator.clone(),
407
23
					unstaked_amount: amount,
408
23
				});
409
23
				if scheduled_requests.is_empty() {
410
23
					<DelegationScheduledRequests<T>>::remove(&collator, &delegator);
411
23
					<DelegationScheduledRequestsPerCollator<T>>::mutate(&collator, |c| {
412
23
						*c = c.saturating_sub(1);
413
23
					});
414
				} else {
415
					<DelegationScheduledRequests<T>>::insert(
416
						collator.clone(),
417
						delegator.clone(),
418
						scheduled_requests,
419
					);
420
				}
421
23
				if leaving {
422
12
					<DelegatorState<T>>::remove(&delegator);
423
12
					Self::deposit_event(Event::DelegatorLeft {
424
12
						delegator,
425
12
						unstaked_amount: amount,
426
12
					});
427
12
				} else {
428
11
					<DelegatorState<T>>::insert(&delegator, state);
429
11
				}
430
23
				Ok(Some(actual_weight).into())
431
			}
432
			DelegationAction::Decrease(_) => {
433
16
				let actual_weight =
434
16
					<T as Config>::WeightInfo::execute_delegator_revoke_delegation_worst();
435

            
436
				// remove from pending requests
437
				// `BoundedVec::remove` can panic, but we make sure it will not happen by checking above that `scheduled_requests` is not empty.
438
16
				let amount = scheduled_requests.remove(0).action.amount();
439
16
				state.less_total = state.less_total.saturating_sub(amount);
440

            
441
				// decrease delegation
442
16
				for bond in &mut state.delegations.0 {
443
16
					if bond.owner == collator {
444
16
						return if bond.amount > amount {
445
16
							let amount_before: BalanceOf<T> = bond.amount.into();
446
16
							bond.amount = bond.amount.saturating_sub(amount);
447
16
							let mut collator_info = <CandidateInfo<T>>::get(&collator)
448
16
								.ok_or(<Error<T>>::CandidateDNE)
449
16
								.map_err(|err| DispatchErrorWithPostInfo {
450
									post_info: Some(actual_weight).into(),
451
									error: err.into(),
452
								})?;
453

            
454
16
							state
455
16
								.total_sub_if::<T, _>(amount, |total| {
456
16
									let new_total: BalanceOf<T> = total.into();
457
16
									ensure!(
458
16
										new_total >= T::MinDelegation::get(),
459
										<Error<T>>::DelegationBelowMin
460
									);
461

            
462
16
									Ok(())
463
16
								})
464
16
								.map_err(|err| DispatchErrorWithPostInfo {
465
									post_info: Some(actual_weight).into(),
466
									error: err,
467
								})?;
468

            
469
							// need to go into decrease_delegation
470
16
							let in_top = collator_info
471
16
								.decrease_delegation::<T>(
472
16
									&collator,
473
16
									delegator.clone(),
474
16
									amount_before,
475
16
									amount,
476
								)
477
16
								.map_err(|err| DispatchErrorWithPostInfo {
478
									post_info: Some(actual_weight).into(),
479
									error: err,
480
								})?;
481
16
							<CandidateInfo<T>>::insert(&collator, collator_info);
482
16
							let new_total_staked = <Total<T>>::get().saturating_sub(amount);
483
16
							<Total<T>>::put(new_total_staked);
484

            
485
16
							if scheduled_requests.is_empty() {
486
15
								<DelegationScheduledRequests<T>>::remove(&collator, &delegator);
487
15
								<DelegationScheduledRequestsPerCollator<T>>::mutate(
488
15
									&collator,
489
15
									|c| {
490
15
										*c = c.saturating_sub(1);
491
15
									},
492
								);
493
1
							} else {
494
1
								<DelegationScheduledRequests<T>>::insert(
495
1
									collator.clone(),
496
1
									delegator.clone(),
497
1
									scheduled_requests,
498
1
								);
499
1
							}
500
16
							<DelegatorState<T>>::insert(delegator.clone(), state);
501
16
							Self::deposit_event(Event::DelegationDecreased {
502
16
								delegator,
503
16
								candidate: collator.clone(),
504
16
								amount,
505
16
								in_top,
506
16
							});
507
16
							Ok(Some(actual_weight).into())
508
						} else {
509
							// must rm entire delegation if bond.amount <= less or cancel request
510
							Err(DispatchErrorWithPostInfo {
511
								post_info: Some(actual_weight).into(),
512
								error: <Error<T>>::DelegationBelowMin.into(),
513
							})
514
						};
515
					}
516
				}
517
				Err(DispatchErrorWithPostInfo {
518
					post_info: Some(actual_weight).into(),
519
					error: <Error<T>>::DelegationDNE.into(),
520
				})
521
			}
522
		}
523
39
	}
524

            
525
	/// Removes the delegator's existing [ScheduledRequest] towards a given collator, if exists.
526
	/// The state needs to be persisted by the caller of this function.
527
19
	pub(crate) fn delegation_remove_request_with_state(
528
19
		collator: &T::AccountId,
529
19
		delegator: &T::AccountId,
530
19
		state: &mut Delegator<T::AccountId, BalanceOf<T>>,
531
19
	) {
532
19
		let scheduled_requests = <DelegationScheduledRequests<T>>::get(collator, delegator);
533

            
534
19
		if scheduled_requests.is_empty() {
535
15
			return;
536
4
		}
537

            
538
		// Calculate total amount across all scheduled requests
539
4
		let total_amount: BalanceOf<T> = scheduled_requests
540
4
			.iter()
541
4
			.map(|request| request.action.amount())
542
4
			.fold(BalanceOf::<T>::zero(), |acc, amount| {
543
4
				acc.saturating_add(amount)
544
4
			});
545

            
546
4
		state.less_total = state.less_total.saturating_sub(total_amount);
547
4
		<DelegationScheduledRequests<T>>::remove(collator, delegator);
548
4
		<DelegationScheduledRequestsPerCollator<T>>::mutate(collator, |c| {
549
4
			*c = c.saturating_sub(1);
550
4
		});
551
19
	}
552

            
553
	/// Returns true if a [ScheduledRequest] exists for a given delegation
554
6
	pub fn delegation_request_exists(collator: &T::AccountId, delegator: &T::AccountId) -> bool {
555
6
		!<DelegationScheduledRequests<T>>::get(collator, delegator).is_empty()
556
6
	}
557

            
558
	/// Returns true if a [DelegationAction::Revoke] [ScheduledRequest] exists for a given delegation
559
26
	pub fn delegation_request_revoke_exists(
560
26
		collator: &T::AccountId,
561
26
		delegator: &T::AccountId,
562
26
	) -> bool {
563
26
		<DelegationScheduledRequests<T>>::get(collator, delegator)
564
26
			.iter()
565
26
			.any(|req| matches!(req.action, DelegationAction::Revoke(_)))
566
26
	}
567
}
568

            
569
#[cfg(test)]
570
mod tests {
571
	use super::*;
572
	use crate::{mock::Test, set::OrderedSet, Bond};
573

            
574
	#[test]
575
1
	fn test_cancel_request_with_state_removes_request_for_correct_delegator_and_updates_state() {
576
1
		let mut state = Delegator {
577
1
			id: 1,
578
1
			delegations: OrderedSet::from(vec![Bond {
579
1
				amount: 100,
580
1
				owner: 2,
581
1
			}]),
582
1
			total: 100,
583
1
			less_total: 150,
584
1
			status: crate::DelegatorStatus::Active,
585
1
		};
586
1
		let mut scheduled_requests = vec![
587
1
			ScheduledRequest {
588
1
				when_executable: 1,
589
1
				action: DelegationAction::Revoke(100),
590
1
			},
591
1
			ScheduledRequest {
592
1
				when_executable: 1,
593
1
				action: DelegationAction::Decrease(50),
594
1
			},
595
		]
596
1
		.try_into()
597
1
		.expect("must succeed");
598
1
		let removed_request =
599
1
			<Pallet<Test>>::cancel_request_with_state(&mut state, &mut scheduled_requests);
600

            
601
1
		assert_eq!(
602
			removed_request,
603
			Some(ScheduledRequest {
604
				when_executable: 1,
605
				action: DelegationAction::Revoke(100),
606
			})
607
		);
608
1
		assert_eq!(
609
			scheduled_requests,
610
1
			vec![ScheduledRequest {
611
1
				when_executable: 1,
612
1
				action: DelegationAction::Decrease(50),
613
1
			},]
614
		);
615
1
		assert_eq!(
616
			state.less_total, 50,
617
			"less_total should be reduced by the amount of the cancelled request"
618
		);
619
1
	}
620

            
621
	#[test]
622
1
	fn test_cancel_request_with_state_does_nothing_when_request_does_not_exist() {
623
1
		let mut state = Delegator {
624
1
			id: 1,
625
1
			delegations: OrderedSet::from(vec![Bond {
626
1
				amount: 100,
627
1
				owner: 2,
628
1
			}]),
629
1
			total: 100,
630
1
			less_total: 100,
631
1
			status: crate::DelegatorStatus::Active,
632
1
		};
633
1
		let mut scheduled_requests: BoundedVec<
634
1
			ScheduledRequest<u128>,
635
1
			<Test as crate::pallet::Config>::MaxScheduledRequestsPerDelegator,
636
1
		> = BoundedVec::default();
637
1
		let removed_request =
638
1
			<Pallet<Test>>::cancel_request_with_state(&mut state, &mut scheduled_requests);
639

            
640
1
		assert_eq!(removed_request, None,);
641
1
		assert_eq!(
642
1
			scheduled_requests.len(),
643
			0,
644
			"scheduled_requests should remain empty"
645
		);
646
1
		assert_eq!(
647
			state.less_total, 100,
648
			"less_total should remain unchanged when there is nothing to cancel"
649
		);
650
1
	}
651
}