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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
//! Transfer Funds as Frozen with a Time Delayed Release
//!
//! ## Quick Links
//! - [Configuration: `Config`](Config)
//! - [Extrinsics: `Call`](Call)
//! - [Event Enum: `Event`](Event)
//! - [Error Enum: `Error`](Error)
#![doc = include_str!("../README.md")]
// Substrate macros are tripping the clippy::expect_used lint.
#![allow(clippy::expect_used)]
#![cfg_attr(not(feature = "std"), no_std)]
// Strong Documentation Lints
#![deny(
	rustdoc::broken_intra_doc_links,
	rustdoc::missing_crate_level_docs,
	rustdoc::invalid_codeblock_attributes,
	missing_docs
)]

use frame_support::{
	dispatch::DispatchResult,
	ensure,
	pallet_prelude::*,
	traits::{
		tokens::{
			fungible::{Inspect as InspectFungible, Mutate, MutateFreeze},
			Balance, Preservation,
		},
		BuildGenesisConfig, EnsureOrigin, Get,
	},
	BoundedVec,
};
use frame_system::{ensure_root, ensure_signed, pallet_prelude::*};
use sp_runtime::{
	traits::{BlockNumberProvider, CheckedAdd, StaticLookup, Zero},
	ArithmeticError,
};
use sp_std::vec::Vec;

#[cfg(test)]
mod mock;
#[cfg(test)]
mod tests;

/// storage migrations
pub mod migration;

mod types;
pub use types::*;

pub mod weights;
pub use weights::*;

#[cfg(feature = "runtime-benchmarks")]
mod benchmarking;

pub use module::*;

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

	pub(crate) type BalanceOf<T> = <<T as Config>::Currency as InspectFungible<
		<T as frame_system::Config>::AccountId,
	>>::Balance;
	pub(crate) type ReleaseScheduleOf<T> = ReleaseSchedule<BlockNumberFor<T>, BalanceOf<T>>;

	/// Scheduled item used for configuring genesis.
	pub type ScheduledItem<T> = (
		<T as frame_system::Config>::AccountId,
		BlockNumberFor<T>,
		BlockNumberFor<T>,
		u32,
		BalanceOf<T>,
	);

	/// A reason for freezing funds.
	/// Creates a freeze reason for this pallet that is aggregated by `construct_runtime`.
	#[pallet::composite_enum]
	pub enum FreezeReason {
		/// Funds are currently frozen and are not yet liquid.
		TimeReleaseVesting,
	}

	/// the storage version for this pallet
	pub const STORAGE_VERSION: StorageVersion = StorageVersion::new(2);

	#[pallet::config]
	pub trait Config: frame_system::Config {
		/// The overarching event type.
		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;

		/// The overarching freeze reason.
		type RuntimeFreezeReason: From<FreezeReason>;

		/// We need MaybeSerializeDeserialize because of the genesis config.
		type Balance: Balance + MaybeSerializeDeserialize;

		/// The currency trait used to set a freeze on a balance.
		type Currency: MutateFreeze<Self::AccountId, Id = Self::RuntimeFreezeReason>
			+ InspectFungible<Self::AccountId, Balance = Self::Balance>
			+ Mutate<Self::AccountId>;

		#[pallet::constant]
		/// The minimum amount transferred to call `transfer`.
		type MinReleaseTransfer: Get<BalanceOf<Self>>;

		/// Required origin for time-release transfer.
		type TransferOrigin: EnsureOrigin<Self::RuntimeOrigin, Success = Self::AccountId>;

		/// Weight information for extrinsics in this module.
		type WeightInfo: WeightInfo;

		/// The maximum release schedules.
		type MaxReleaseSchedules: Get<u32>;

		/// The block-number provider.
		type BlockNumberProvider: BlockNumberProvider<BlockNumber = BlockNumberFor<Self>>;
	}

	#[pallet::error]
	pub enum Error<T> {
		/// Release period is zero
		ZeroReleasePeriod,
		/// Period-count is zero
		ZeroReleasePeriodCount,
		/// Insufficient amount of balance to freeze
		InsufficientBalanceToFreeze,
		/// This account have too many release schedules
		TooManyReleaseSchedules,
		/// The transfer amount is too low
		AmountLow,
		/// Failed because the maximum release schedules was exceeded
		MaxReleaseSchedulesExceeded,
	}

	#[pallet::event]
	#[pallet::generate_deposit(fn deposit_event)]
	pub enum Event<T: Config> {
		/// Added new release schedule.
		ReleaseScheduleAdded {
			/// The account-id of the sender.
			from: T::AccountId,
			/// The account-id of the receiver.
			to: T::AccountId,
			/// The schedule indicating when transfer releases happen.
			release_schedule: ReleaseScheduleOf<T>,
		},
		/// Claimed release.
		Claimed {
			/// The account-id of the claimed amount.
			who: T::AccountId,
			/// The amount claimed.
			amount: BalanceOf<T>,
		},
		/// Updated release schedules.
		ReleaseSchedulesUpdated {
			/// The account-id for which a release schedule updated was made for.
			who: T::AccountId,
		},
	}

	/// Release schedules of an account.
	///
	/// ReleaseSchedules: `map AccountId => Vec<ReleaseSchedule>`
	#[pallet::storage]
	pub type ReleaseSchedules<T: Config> = StorageMap<
		_,
		Blake2_128Concat,
		T::AccountId,
		BoundedVec<ReleaseScheduleOf<T>, T::MaxReleaseSchedules>,
		ValueQuery,
	>;

	#[pallet::genesis_config]
	#[derive(frame_support::DefaultNoBound)]
	pub struct GenesisConfig<T: Config> {
		/// Phantom data.
		#[serde(skip)]
		pub _config: sp_std::marker::PhantomData<T>,
		/// A list of schedules to include.
		pub schedules: Vec<ScheduledItem<T>>,
	}

	#[pallet::genesis_build]
	impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
		fn build(&self) {
			self.schedules
				.iter()
				.for_each(|(who, start, period, period_count, per_period)| {
					let mut bounded_schedules = ReleaseSchedules::<T>::get(who);
					bounded_schedules
						.try_push(ReleaseSchedule {
							start: *start,
							period: *period,
							period_count: *period_count,
							per_period: *per_period,
						})
						.expect("Max release schedules exceeded");
					let total_amount = bounded_schedules
						.iter()
						.try_fold::<_, _, Result<BalanceOf<T>, DispatchError>>(
							Zero::zero(),
							|acc_amount, schedule| {
								let amount = ensure_valid_release_schedule::<T>(schedule)?;
								acc_amount
									.checked_add(&amount)
									.ok_or_else(|| ArithmeticError::Overflow.into())
							},
						)
						.expect("Invalid release schedule");

					assert!(
						T::Currency::balance(who) >= total_amount,
						"Account does not have enough balance."
					);

					T::Currency::set_freeze(
						&FreezeReason::TimeReleaseVesting.into(),
						who,
						total_amount,
					)
					.expect("Failed to set freeze");
					ReleaseSchedules::<T>::insert(who, bounded_schedules);
				});
		}
	}

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

	#[pallet::hooks]
	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {}

	#[pallet::call]
	impl<T: Config> Pallet<T> {
		/// Claim thawed balances.
		///
		/// # Events
		/// * [`Event::Claimed`]
		///
		#[pallet::call_index(0)]
		#[pallet::weight(T::WeightInfo::claim(<T as Config>::MaxReleaseSchedules::get() / 2))]
		pub fn claim(origin: OriginFor<T>) -> DispatchResult {
			let who = ensure_signed(origin)?;
			let frozen_amount = Self::do_claim(&who)?;

			Self::deposit_event(Event::Claimed { who, amount: frozen_amount });
			Ok(())
		}

		/// Add a new release schedule for an account.
		///
		/// # Events
		/// * [`Event::ReleaseScheduleAdded]
		///
		/// # Errors
		///
		/// * [`Error::InsufficientBalanceToFreeze] - Insufficient amount of balance to freeze.
		/// * [`Error::MaxReleaseSchedulesExceeded] - Failed because the maximum release schedules was exceeded-
		/// * [`ArithmeticError::Overflow] - Failed because of an overflow.
		///
		#[pallet::call_index(1)]
		#[pallet::weight(T::WeightInfo::transfer())]
		pub fn transfer(
			origin: OriginFor<T>,
			dest: <T::Lookup as StaticLookup>::Source,
			schedule: ReleaseScheduleOf<T>,
		) -> DispatchResult {
			let from = T::TransferOrigin::ensure_origin(origin)?;
			let to = T::Lookup::lookup(dest)?;

			if to == from {
				ensure!(
					T::Currency::balance(&from) >=
						schedule.total_amount().ok_or(ArithmeticError::Overflow)?,
					Error::<T>::InsufficientBalanceToFreeze,
				);
			}

			Self::do_transfer(&from, &to, schedule.clone())?;

			Self::deposit_event(Event::ReleaseScheduleAdded {
				from,
				to,
				release_schedule: schedule,
			});
			Ok(())
		}

		/// Update all release schedules under an account, `root` origin required.
		///
		/// # Events
		/// * [`Event::ReleaseSchedulesUpdated] - Updated release schedules.
		///
		/// # Errors
		///
		/// * [`Error::InsufficientBalanceToFreeze] - Insufficient amount of balance to freeze.
		/// * [`Error::MaxReleaseSchedulesExceeded] - Failed because the maximum release schedules was exceeded-
		/// * [`ArithmeticError::Overflow] - Failed because of an overflow.
		///
		#[pallet::call_index(2)]
		#[pallet::weight(T::WeightInfo::update_release_schedules(release_schedules.len() as u32))]
		pub fn update_release_schedules(
			origin: OriginFor<T>,
			who: <T::Lookup as StaticLookup>::Source,
			release_schedules: Vec<ReleaseScheduleOf<T>>,
		) -> DispatchResult {
			ensure_root(origin)?;

			let account = T::Lookup::lookup(who)?;
			Self::do_update_release_schedules(&account, release_schedules)?;

			Self::deposit_event(Event::ReleaseSchedulesUpdated { who: account });
			Ok(())
		}

		/// Claim thawed balances on behalf for an account.
		///
		/// # Events
		/// * [`Event::Claimed`]
		///
		#[pallet::call_index(3)]
		#[pallet::weight(T::WeightInfo::claim(<T as Config>::MaxReleaseSchedules::get() / 2))]
		pub fn claim_for(
			origin: OriginFor<T>,
			dest: <T::Lookup as StaticLookup>::Source,
		) -> DispatchResult {
			ensure_signed(origin)?;
			let who = T::Lookup::lookup(dest)?;
			let frozen_amount = Self::do_claim(&who)?;

			Self::deposit_event(Event::Claimed { who, amount: frozen_amount });
			Ok(())
		}
	}
}

impl<T: Config> Pallet<T> {
	fn do_claim(who: &T::AccountId) -> Result<BalanceOf<T>, DispatchError> {
		let frozen = Self::prune_and_get_frozen_balance(who);
		if frozen.is_zero() {
			Self::delete_freeze(who)?;
		} else {
			Self::update_freeze(who, frozen)?;
		}

		Ok(frozen)
	}

	/// Deletes schedules that have released all funds up to a block-number.
	fn prune_schedules_for(
		who: &T::AccountId,
		block_number: BlockNumberFor<T>,
	) -> BoundedVec<ReleaseScheduleOf<T>, T::MaxReleaseSchedules> {
		let mut schedules = ReleaseSchedules::<T>::get(who);
		schedules.retain(|schedule| !schedule.frozen_amount(block_number).is_zero());

		if schedules.is_empty() {
			ReleaseSchedules::<T>::remove(who);
		} else {
			Self::set_schedules_for(who, schedules.clone());
		}

		schedules
	}

	/// Returns frozen balance based on current block number.
	fn prune_and_get_frozen_balance(who: &T::AccountId) -> BalanceOf<T> {
		let now = T::BlockNumberProvider::current_block_number();

		let schedules = Self::prune_schedules_for(&who, now);

		let total = schedules
			.iter()
			.fold(BalanceOf::<T>::zero(), |acc, schedule| acc + schedule.frozen_amount(now));

		total
	}

	fn do_transfer(
		from: &T::AccountId,
		to: &T::AccountId,
		schedule: ReleaseScheduleOf<T>,
	) -> DispatchResult {
		let schedule_amount = ensure_valid_release_schedule::<T>(&schedule)?;

		let total_amount = Self::prune_and_get_frozen_balance(to)
			.checked_add(&schedule_amount)
			.ok_or(ArithmeticError::Overflow)?;

		T::Currency::transfer(from, to, schedule_amount, Preservation::Expendable)?;

		Self::update_freeze(&to, total_amount)?;

		<ReleaseSchedules<T>>::try_append(to, schedule)
			.map_err(|_| Error::<T>::MaxReleaseSchedulesExceeded)?;

		Ok(())
	}

	fn do_update_release_schedules(
		who: &T::AccountId,
		schedules: Vec<ReleaseScheduleOf<T>>,
	) -> DispatchResult {
		let bounded_schedules =
			BoundedVec::<ReleaseScheduleOf<T>, T::MaxReleaseSchedules>::try_from(schedules)
				.map_err(|_| Error::<T>::MaxReleaseSchedulesExceeded)?;

		// empty release schedules cleanup the storage and thaw the funds
		if bounded_schedules.is_empty() {
			Self::delete_release_schedules(who)?;
			return Ok(())
		}

		let total_amount =
			bounded_schedules.iter().try_fold::<_, _, Result<BalanceOf<T>, DispatchError>>(
				Zero::zero(),
				|acc_amount, schedule| {
					let amount = ensure_valid_release_schedule::<T>(schedule)?;
					acc_amount.checked_add(&amount).ok_or_else(|| ArithmeticError::Overflow.into())
				},
			)?;

		ensure!(T::Currency::balance(who) >= total_amount, Error::<T>::InsufficientBalanceToFreeze,);

		Self::update_freeze(&who, total_amount)?;
		Self::set_schedules_for(who, bounded_schedules);

		Ok(())
	}

	fn update_freeze(who: &T::AccountId, frozen: BalanceOf<T>) -> DispatchResult {
		T::Currency::set_freeze(&FreezeReason::TimeReleaseVesting.into(), who, frozen)?;
		Ok(())
	}

	fn delete_freeze(who: &T::AccountId) -> DispatchResult {
		T::Currency::thaw(&FreezeReason::TimeReleaseVesting.into(), who)?;
		Ok(())
	}

	fn set_schedules_for(
		who: &T::AccountId,
		schedules: BoundedVec<ReleaseScheduleOf<T>, T::MaxReleaseSchedules>,
	) {
		ReleaseSchedules::<T>::insert(who, schedules);
	}

	fn delete_release_schedules(who: &T::AccountId) -> DispatchResult {
		<ReleaseSchedules<T>>::remove(who);
		Self::delete_freeze(who)?;
		Ok(())
	}
}

/// Returns `Ok(total_total)` if valid schedule, or error.
fn ensure_valid_release_schedule<T: Config>(
	schedule: &ReleaseScheduleOf<T>,
) -> Result<BalanceOf<T>, DispatchError> {
	ensure!(!schedule.period.is_zero(), Error::<T>::ZeroReleasePeriod);
	ensure!(!schedule.period_count.is_zero(), Error::<T>::ZeroReleasePeriodCount);
	ensure!(schedule.end().is_some(), ArithmeticError::Overflow);

	let total_total = schedule.total_amount().ok_or(ArithmeticError::Overflow)?;

	ensure!(total_total >= T::MinReleaseTransfer::get(), Error::<T>::AmountLow);

	Ok(total_total)
}