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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
#![cfg_attr(not(feature = "std"), no_std)]
#![allow(clippy::unused_unit)]
#![allow(clippy::too_many_arguments)]

mod mock;
mod tests;

use frame_support::pallet_prelude::*;
use orml_traits::{GetByKey, RewardHandler};
use parity_scale_codec::{FullCodec, HasCompact};
use scale_info::TypeInfo;
use sp_core::U256;
use sp_runtime::{
	traits::{AtLeast32BitUnsigned, MaybeSerializeDeserialize, Member, Saturating, UniqueSaturatedInto, Zero},
	FixedPointOperand, RuntimeDebug, SaturatedConversion,
};
use sp_std::{borrow::ToOwned, collections::btree_map::BTreeMap, fmt::Debug, prelude::*};

/// The Reward Pool Info.
#[derive(Clone, Encode, Decode, PartialEq, Eq, RuntimeDebug, TypeInfo)]
pub struct PoolInfo<Share: HasCompact, Balance: HasCompact, CurrencyId: Ord> {
	/// Total shares amount
	pub total_shares: Share,
	/// Reward infos <reward_currency, (total_reward, total_withdrawn_reward)>
	pub rewards: BTreeMap<CurrencyId, (Balance, Balance)>,
}

impl<Share, Balance, CurrencyId> Default for PoolInfo<Share, Balance, CurrencyId>
where
	Share: Default + HasCompact,
	Balance: HasCompact,
	CurrencyId: Ord,
{
	fn default() -> Self {
		Self {
			total_shares: Default::default(),
			rewards: BTreeMap::new(),
		}
	}
}

pub use module::*;

#[frame_support::pallet]
pub mod module {

	use super::*;

	#[pallet::config]
	pub trait Config: frame_system::Config {
		/// The share type of pool.
		type Share: Parameter
			+ Member
			+ AtLeast32BitUnsigned
			+ Default
			+ Copy
			+ MaybeSerializeDeserialize
			+ Debug
			+ FixedPointOperand;

		/// The reward balance type.
		type Balance: Parameter
			+ Member
			+ AtLeast32BitUnsigned
			+ Default
			+ Copy
			+ MaybeSerializeDeserialize
			+ Debug
			+ FixedPointOperand;

		/// The reward pool ID type.
		type PoolId: Parameter + Member + Clone + FullCodec;

		type CurrencyId: Parameter + Member + Copy + MaybeSerializeDeserialize + Ord;

		/// The minimal amount of shares an account can hold.
		/// Transactions that would result in an account holding shares fewer
		/// than this amount but non zero are invalid.
		type MinimalShares: GetByKey<Self::PoolId, Self::Share>;

		/// The `RewardHandler`
		type Handler: RewardHandler<Self::AccountId, Self::CurrencyId, Balance = Self::Balance, PoolId = Self::PoolId>;
	}

	type WithdrawnRewards<T> = BTreeMap<<T as Config>::CurrencyId, <T as Config>::Balance>;

	#[pallet::error]
	pub enum Error<T> {
		/// Pool does not exist
		PoolDoesNotExist,
		/// Account does not have share
		ShareDoesNotExist,
		/// Can split only less than share
		CanSplitOnlyLessThanShare,
		/// Share amount below minimal
		ShareBelowMinimal,
	}

	/// Record reward pool info.
	///
	/// map PoolId => PoolInfo
	#[pallet::storage]
	#[pallet::getter(fn pool_infos)]
	pub type PoolInfos<T: Config> =
		StorageMap<_, Twox64Concat, T::PoolId, PoolInfo<T::Share, T::Balance, T::CurrencyId>, ValueQuery>;

	/// Record share amount, reward currency and withdrawn reward amount for
	/// specific `AccountId` under `PoolId`.
	///
	/// double_map (PoolId, AccountId) => (Share, BTreeMap<CurrencyId, Balance>)
	#[pallet::storage]
	#[pallet::getter(fn shares_and_withdrawn_rewards)]
	pub type SharesAndWithdrawnRewards<T: Config> = StorageDoubleMap<
		_,
		Twox64Concat,
		T::PoolId,
		Twox64Concat,
		T::AccountId,
		(T::Share, WithdrawnRewards<T>),
		ValueQuery,
	>;

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

impl<T: Config> Pallet<T> {
	pub fn accumulate_reward(
		pool: &T::PoolId,
		reward_currency: T::CurrencyId,
		reward_increment: T::Balance,
	) -> DispatchResult {
		if reward_increment.is_zero() {
			return Ok(());
		}
		PoolInfos::<T>::mutate_exists(pool, |maybe_pool_info| -> DispatchResult {
			let pool_info = maybe_pool_info.as_mut().ok_or(Error::<T>::PoolDoesNotExist)?;

			pool_info
				.rewards
				.entry(reward_currency)
				.and_modify(|(total_reward, _)| {
					*total_reward = total_reward.saturating_add(reward_increment);
				})
				.or_insert((reward_increment, Zero::zero()));

			Ok(())
		})
	}

	pub fn add_share(who: &T::AccountId, pool: &T::PoolId, add_amount: T::Share) -> DispatchResult {
		if add_amount.is_zero() {
			return Ok(());
		}

		PoolInfos::<T>::try_mutate(pool, |pool_info| {
			let initial_total_shares = pool_info.total_shares;
			pool_info.total_shares = pool_info.total_shares.saturating_add(add_amount);

			let mut withdrawn_inflation = Vec::<(T::CurrencyId, T::Balance)>::new();

			pool_info
				.rewards
				.iter_mut()
				.for_each(|(reward_currency, (total_reward, total_withdrawn_reward))| {
					let reward_inflation = if initial_total_shares.is_zero() {
						Zero::zero()
					} else {
						U256::from(add_amount.to_owned().saturated_into::<u128>())
							.saturating_mul(total_reward.to_owned().saturated_into::<u128>().into())
							.checked_div(initial_total_shares.to_owned().saturated_into::<u128>().into())
							.unwrap_or_default()
							.as_u128()
							.saturated_into()
					};
					*total_reward = total_reward.saturating_add(reward_inflation);
					*total_withdrawn_reward = total_withdrawn_reward.saturating_add(reward_inflation);

					withdrawn_inflation.push((*reward_currency, reward_inflation));
				});

			SharesAndWithdrawnRewards::<T>::try_mutate(pool, who, |(share, withdrawn_rewards)| {
				*share = share.saturating_add(add_amount);

				ensure!(*share >= T::MinimalShares::get(pool), Error::<T>::ShareBelowMinimal);

				// update withdrawn inflation for each reward currency
				withdrawn_inflation
					.into_iter()
					.for_each(|(reward_currency, reward_inflation)| {
						withdrawn_rewards
							.entry(reward_currency)
							.and_modify(|withdrawn_reward| {
								*withdrawn_reward = withdrawn_reward.saturating_add(reward_inflation);
							})
							.or_insert(reward_inflation);
					});

				Ok(())
			})
		})
	}

	pub fn remove_share(who: &T::AccountId, pool: &T::PoolId, remove_amount: T::Share) -> DispatchResult {
		if remove_amount.is_zero() {
			return Ok(());
		}

		// claim rewards firstly
		Self::claim_rewards(who, pool);

		SharesAndWithdrawnRewards::<T>::try_mutate_exists(pool, who, |share_info| {
			if let Some((mut share, mut withdrawn_rewards)) = share_info.take() {
				let remove_amount = remove_amount.min(share);

				if remove_amount.is_zero() {
					return Ok(());
				}

				let old_share = share;

				share = share.saturating_sub(remove_amount);
				if !share.is_zero() {
					ensure!(share >= T::MinimalShares::get(pool), Error::<T>::ShareBelowMinimal);
				}

				PoolInfos::<T>::try_mutate_exists(pool, |maybe_pool_info| -> DispatchResult {
					if let Some(mut pool_info) = maybe_pool_info.take() {
						let removing_share = U256::from(remove_amount.saturated_into::<u128>());

						pool_info.total_shares = pool_info.total_shares.saturating_sub(remove_amount);

						// update withdrawn rewards for each reward currency
						withdrawn_rewards
							.iter_mut()
							.for_each(|(reward_currency, withdrawn_reward)| {
								let withdrawn_reward_to_remove: T::Balance = removing_share
									.saturating_mul(withdrawn_reward.to_owned().saturated_into::<u128>().into())
									.checked_div(old_share.saturated_into::<u128>().into())
									.unwrap_or_default()
									.as_u128()
									.saturated_into();

								if let Some((total_reward, total_withdrawn_reward)) =
									pool_info.rewards.get_mut(reward_currency)
								{
									*total_reward = total_reward.saturating_sub(withdrawn_reward_to_remove);
									*total_withdrawn_reward =
										total_withdrawn_reward.saturating_sub(withdrawn_reward_to_remove);

									// remove if all reward is withdrawn
									if total_reward.is_zero() {
										pool_info.rewards.remove(reward_currency);
									}
								}
								*withdrawn_reward = withdrawn_reward.saturating_sub(withdrawn_reward_to_remove);
							});

						if !pool_info.total_shares.is_zero() {
							*maybe_pool_info = Some(pool_info);
						}
					}

					if !share.is_zero() {
						*share_info = Some((share, withdrawn_rewards));
					}

					Ok(())
				})?;
			}

			Ok(())
		})
	}

	pub fn set_share(who: &T::AccountId, pool: &T::PoolId, new_share: T::Share) -> DispatchResult {
		let (share, _) = Self::shares_and_withdrawn_rewards(pool, who);

		if new_share > share {
			Self::add_share(who, pool, new_share.saturating_sub(share))
		} else {
			Self::remove_share(who, pool, share.saturating_sub(new_share))
		}
	}

	pub fn claim_rewards(who: &T::AccountId, pool: &T::PoolId) {
		SharesAndWithdrawnRewards::<T>::mutate_exists(pool, who, |maybe_share_withdrawn| {
			if let Some((share, withdrawn_rewards)) = maybe_share_withdrawn {
				if share.is_zero() {
					return;
				}

				PoolInfos::<T>::mutate_exists(pool, |maybe_pool_info| {
					if let Some(pool_info) = maybe_pool_info {
						let total_shares = U256::from(pool_info.total_shares.to_owned().saturated_into::<u128>());
						pool_info.rewards.iter_mut().for_each(
							|(reward_currency, (total_reward, total_withdrawn_reward))| {
								Self::claim_one(
									withdrawn_rewards,
									*reward_currency,
									share.to_owned(),
									total_reward.to_owned(),
									total_shares,
									total_withdrawn_reward,
									who,
									pool,
								);
							},
						);
					}
				});
			}
		});
	}

	pub fn claim_reward(who: &T::AccountId, pool: &T::PoolId, reward_currency: T::CurrencyId) {
		SharesAndWithdrawnRewards::<T>::mutate_exists(pool, who, |maybe_share_withdrawn| {
			if let Some((share, withdrawn_rewards)) = maybe_share_withdrawn {
				if share.is_zero() {
					return;
				}

				PoolInfos::<T>::mutate(pool, |pool_info| {
					let total_shares = U256::from(pool_info.total_shares.to_owned().saturated_into::<u128>());
					if let Some((total_reward, total_withdrawn_reward)) = pool_info.rewards.get_mut(&reward_currency) {
						Self::claim_one(
							withdrawn_rewards,
							reward_currency,
							share.to_owned(),
							total_reward.to_owned(),
							total_shares,
							total_withdrawn_reward,
							who,
							pool,
						);
					}
				});
			}
		});
	}

	/// Splits share into two parts.
	///
	/// `move_share` - amount of share to remove and put into `other` share
	/// `other` - new account who will own new share
	///
	/// Similar too claim and add 2 shares later, but does not requires pool
	/// inflation and is more efficient.
	pub fn transfer_share_and_rewards(
		who: &T::AccountId,
		pool: &T::PoolId,
		move_share: T::Share,
		other: &T::AccountId,
	) -> DispatchResult {
		if move_share.is_zero() {
			return Ok(());
		}

		SharesAndWithdrawnRewards::<T>::try_mutate(pool, other, |increased_share| {
			let (increased_share, increased_rewards) = increased_share;
			SharesAndWithdrawnRewards::<T>::try_mutate_exists(pool, who, |share| {
				let (share, rewards) = share.as_mut().ok_or(Error::<T>::ShareDoesNotExist)?;
				ensure!(move_share < *share, Error::<T>::CanSplitOnlyLessThanShare);
				if who == other {
					// self transfer is noop
					return Ok(());
				}
				for (reward_currency, balance) in rewards {
					// u128 * u128 is always less than u256
					// move_share / share always less then 1 and share > 0
					// so final results is computable and is always less or equal than u128
					let move_balance = U256::from(balance.to_owned().saturated_into::<u128>())
						* U256::from(move_share.to_owned().saturated_into::<u128>())
						/ U256::from(share.to_owned().saturated_into::<u128>());
					let move_balance: Option<u128> = move_balance.try_into().ok();
					if let Some(move_balance) = move_balance {
						let move_balance: T::Balance = move_balance.unique_saturated_into();
						*balance = balance.saturating_sub(move_balance);
						increased_rewards
							.entry(*reward_currency)
							.and_modify(|increased_reward| {
								*increased_reward = increased_reward.saturating_add(move_balance);
							})
							.or_insert(move_balance);
					}
				}
				*share = share.saturating_sub(move_share);
				*increased_share = increased_share.saturating_add(move_share);

				ensure!(
					*share >= T::MinimalShares::get(pool) || share.is_zero(),
					Error::<T>::ShareBelowMinimal
				);
				ensure!(
					*increased_share >= T::MinimalShares::get(pool),
					Error::<T>::ShareBelowMinimal
				);

				Ok(())
			})
		})
	}

	#[allow(clippy::too_many_arguments)] // just we need to have all these to do the stuff
	fn claim_one(
		withdrawn_rewards: &mut BTreeMap<T::CurrencyId, T::Balance>,
		reward_currency: T::CurrencyId,
		share: T::Share,
		total_reward: T::Balance,
		total_shares: U256,
		total_withdrawn_reward: &mut T::Balance,
		who: &T::AccountId,
		pool: &T::PoolId,
	) {
		let withdrawn_reward = withdrawn_rewards.get(&reward_currency).copied().unwrap_or_default();
		let reward_to_withdraw = Self::reward_to_withdraw(
			share,
			total_reward,
			total_shares,
			withdrawn_reward,
			total_withdrawn_reward.to_owned(),
		);
		if !reward_to_withdraw.is_zero() {
			*total_withdrawn_reward = total_withdrawn_reward.saturating_add(reward_to_withdraw);
			withdrawn_rewards.insert(reward_currency, withdrawn_reward.saturating_add(reward_to_withdraw));

			// pay reward to `who`
			T::Handler::payout(who, pool, reward_currency, reward_to_withdraw);
		}
	}

	fn reward_to_withdraw(
		share: T::Share,
		total_reward: T::Balance,
		total_shares: U256,
		withdrawn_reward: T::Balance,
		total_withdrawn_reward: T::Balance,
	) -> T::Balance {
		let total_reward_proportion: T::Balance = U256::from(share.saturated_into::<u128>())
			.saturating_mul(U256::from(total_reward.saturated_into::<u128>()))
			.checked_div(total_shares)
			.unwrap_or_default()
			.as_u128()
			.unique_saturated_into();
		total_reward_proportion
			.saturating_sub(withdrawn_reward)
			.min(total_reward.saturating_sub(total_withdrawn_reward))
	}
}