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
use frame_support::{pallet_prelude::*, traits::tokens};
use num_traits::Signed;
pub use pallet::*;
use sp_runtime::{
	traits::{
		EnsureAdd, EnsureAddAssign, EnsureFixedPointNumber, EnsureInto, EnsureSub, EnsureSubAssign,
		One, Saturating, Zero,
	},
	ArithmeticError, FixedPointNumber, FixedPointOperand,
};

use super::{base, MoveCurrencyError, RewardMechanism};

/// Type that contains the stake properties of a stake group
#[derive(Encode, Decode, TypeInfo, MaxEncodedLen, RuntimeDebug)]
#[cfg_attr(test, derive(PartialEq, Clone))]
pub struct Group<T: Config> {
	base: base::Group<T::Balance, T::Rate>,
	last_rate: T::Rate,
	lost_reward: T::Balance,
	distribution_id: T::DistributionId,
}

impl<T: Config> Default for Group<T> {
	fn default() -> Self {
		Self {
			base: base::Group::default(),
			last_rate: T::Rate::zero(),
			lost_reward: T::Balance::zero(),
			distribution_id: T::DistributionId::default(),
		}
	}
}

impl<T: Config> Group<T> {
	fn get_last_rate(&self, currency: &Currency<T>) -> T::Rate {
		if self.distribution_id == currency.next_distribution_id {
			currency.prev_last_rate
		} else {
			self.last_rate
		}
	}
}

/// Type that contains the stake properties of an account
#[derive(Encode, Decode, TypeInfo, MaxEncodedLen, RuntimeDebug)]
#[cfg_attr(test, derive(PartialEq, Clone))]
pub struct Account<T: Config> {
	base: base::Account<T::Balance, T::IBalance>,
	rewarded_stake: T::Balance,
	distribution_id: T::DistributionId,
}

impl<T: Config> Default for Account<T> {
	fn default() -> Self {
		Self {
			base: base::Account::default(),
			rewarded_stake: T::Balance::zero(),
			distribution_id: T::DistributionId::default(),
		}
	}
}

impl<T: Config> Account<T> {
	fn was_distribution(&self, group: &Group<T>, currency: &Currency<T>) -> bool {
		if self.base.last_currency_movement as usize == currency.base.rpt_changes.len() {
			self.distribution_id != group.distribution_id
		} else {
			self.distribution_id != currency.prev_distribution_id
				|| group.distribution_id != currency.next_distribution_id
		}
	}

	fn get_rewarded_stake(&self, group: &Group<T>, currency: &Currency<T>) -> T::Balance {
		if self.was_distribution(group, currency) {
			self.base.stake
		} else {
			self.rewarded_stake
		}
	}

	fn update_rewarded_stake(&mut self, group: &Group<T>, currency: &Currency<T>) {
		self.rewarded_stake = self.get_rewarded_stake(group, currency);
		self.distribution_id = group.distribution_id;
	}

	fn last_rewarded_stake(
		&self,
		group: &Group<T>,
		currency: &Currency<T>,
	) -> Result<T::Balance, ArithmeticError> {
		group
			.get_last_rate(currency)
			.ensure_mul_int(self.get_rewarded_stake(group, currency))
	}
}

/// Type that contains the stake properties of stake class
#[derive(Encode, Decode, TypeInfo, MaxEncodedLen, RuntimeDebug)]
#[cfg_attr(test, derive(PartialEq, Clone))]
pub struct Currency<T: Config> {
	base: base::Currency<T::Balance, T::Rate, T::MaxCurrencyMovements>,
	prev_distribution_id: T::DistributionId,
	next_distribution_id: T::DistributionId,
	prev_last_rate: T::Rate,
}

impl<T: Config> Default for Currency<T> {
	fn default() -> Self {
		Self {
			base: base::Currency::default(),
			prev_distribution_id: T::DistributionId::default(),
			next_distribution_id: T::DistributionId::default(),
			prev_last_rate: T::Rate::default(),
		}
	}
}

pub struct Mechanism<Balance, IBalance, Rate, MaxCurrencyMovements>(
	sp_std::marker::PhantomData<(Balance, IBalance, Rate, MaxCurrencyMovements)>,
);

#[frame_support::pallet]
pub mod pallet {
	use frame_support::pallet_prelude::*;

	use super::*;

	#[pallet::config]
	pub trait Config: frame_system::Config {
		type DistributionId: PartialEq
			+ Copy
			+ parity_scale_codec::FullCodec
			+ MaxEncodedLen
			+ Default
			+ TypeInfo
			+ One
			+ EnsureAdd
			+ sp_std::fmt::Debug;

		type Balance: tokens::Balance
			+ FixedPointOperand
			+ TryFrom<Self::IBalance>
			+ parity_scale_codec::FullCodec
			+ TypeInfo
			+ MaxEncodedLen;

		type IBalance: FixedPointOperand
			+ TryFrom<Self::Balance>
			+ parity_scale_codec::FullCodec
			+ TypeInfo
			+ MaxEncodedLen
			+ EnsureAdd
			+ EnsureSub
			+ Copy
			+ Signed
			+ sp_std::fmt::Debug
			+ Default;

		type Rate: FixedPointNumber + parity_scale_codec::FullCodec + TypeInfo + MaxEncodedLen;

		type MaxCurrencyMovements: Get<u32> + sp_std::fmt::Debug;
	}

	#[pallet::pallet]
	pub struct Pallet<T>(_);

	#[pallet::storage]
	pub(super) type LastDistributionId<T: Config> = StorageValue<_, T::DistributionId, ValueQuery>;

	impl<T: Config> RewardMechanism for Pallet<T>
	where
		<T::Rate as FixedPointNumber>::Inner: Signed,
	{
		type Account = Account<T>;
		type Balance = T::Balance;
		type Currency = Currency<T>;
		type Group = Group<T>;
		type MaxCurrencyMovements = T::MaxCurrencyMovements;

		fn is_ready(group: &Self::Group) -> bool {
			group.base.total_stake > Self::Balance::zero()
		}

		fn reward_group(
			group: &mut Self::Group,
			amount: Self::Balance,
		) -> Result<Self::Balance, DispatchError> {
			let mut reward_used = Self::Balance::zero();

			if group.base.total_stake > Self::Balance::zero() {
				let reward = amount.ensure_add(group.lost_reward)?;
				base::Mechanism::<T::Balance, T::IBalance, T::Rate, T::MaxCurrencyMovements>::reward_group(
                    &mut group.base,
                    reward,
                )?;

				group.lost_reward = T::Balance::zero();
				group.last_rate = T::Rate::ensure_from_rational(reward, group.base.total_stake)?;

				reward_used = reward
			}

			group.distribution_id = LastDistributionId::<T>::try_mutate(
				|distribution_id| -> Result<T::DistributionId, DispatchError> {
					distribution_id.ensure_add_assign(One::one())?;
					Ok(*distribution_id)
				},
			)?;

			Ok(reward_used)
		}

		fn deposit_stake(
			account: &mut Self::Account,
			currency: &mut Self::Currency,
			group: &mut Self::Group,
			amount: Self::Balance,
		) -> DispatchResult {
			account.update_rewarded_stake(group, currency);

			base::Mechanism::deposit_stake(
				&mut account.base,
				&mut currency.base,
				&mut group.base,
				amount,
			)
		}

		fn withdraw_stake(
			account: &mut Self::Account,
			currency: &mut Self::Currency,
			group: &mut Self::Group,
			amount: Self::Balance,
		) -> DispatchResult {
			account.update_rewarded_stake(group, currency);

			let rewarded_amount = {
				let unrewarded_stake = account.base.stake.saturating_sub(account.rewarded_stake);
				let unrewarded_amount = amount.min(unrewarded_stake);
				amount.ensure_sub(unrewarded_amount)
			}?;

			base::Mechanism::withdraw_stake(
				&mut account.base,
				&mut currency.base,
				&mut group.base,
				amount,
			)?;

			let lost_reward = group
				.get_last_rate(currency)
				.ensure_mul_int(rewarded_amount)?;

			account.rewarded_stake.ensure_sub_assign(rewarded_amount)?;
			account
				.base
				.reward_tally
				.ensure_add_assign(lost_reward.ensure_into()?)?;

			group.lost_reward.ensure_add_assign(lost_reward)?;

			Ok(())
		}

		fn compute_reward(
			account: &Self::Account,
			currency: &Self::Currency,
			group: &Self::Group,
		) -> Result<Self::Balance, DispatchError> {
			base::Mechanism::compute_reward(&account.base, &currency.base, &group.base)?
				.ensure_sub(account.last_rewarded_stake(group, currency)?)
				.map_err(|e| e.into())
		}

		fn claim_reward(
			account: &mut Self::Account,
			currency: &Self::Currency,
			group: &Self::Group,
		) -> Result<Self::Balance, DispatchError> {
			let last_rewarded_stake = account.last_rewarded_stake(group, currency)?;

			let reward =
				base::Mechanism::claim_reward(&mut account.base, &currency.base, &group.base)?
					.ensure_sub(last_rewarded_stake)?;

			account
				.base
				.reward_tally
				.ensure_sub_assign(last_rewarded_stake.ensure_into()?)?;

			Ok(reward)
		}

		fn move_currency(
			currency: &mut Self::Currency,
			from_group: &mut Self::Group,
			to_group: &mut Self::Group,
		) -> Result<(), MoveCurrencyError> {
			base::Mechanism::<_, T::IBalance, _, _>::move_currency(
				&mut currency.base,
				&mut from_group.base,
				&mut to_group.base,
			)?;

			// Only if there was a distribution from last move, we update the previous
			// related data.
			if currency.next_distribution_id != from_group.distribution_id {
				currency.prev_distribution_id = from_group.distribution_id;
				currency.prev_last_rate = from_group.last_rate;
			}
			currency.next_distribution_id = to_group.distribution_id;

			Ok(())
		}

		fn account_stake(account: &Self::Account) -> Self::Balance {
			account.base.stake
		}

		fn group_stake(group: &Self::Group) -> Self::Balance {
			group.base.total_stake
		}
	}
}