This repository was archived by the owner on Nov 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
Copy pathlib.rs
1893 lines (1696 loc) · 65.6 KB
/
lib.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
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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This file is part of Substrate.
// Copyright (C) 2019-2021 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! # Vesting Pallet
//!
//! - [`Config`]
//! - [`Call`]
//!
//! ## Overview
//!
//! A simple pallet providing a means of placing a linear curve on an account's locked balance. This
//! pallet ensures that there is a lock in place preventing the balance to drop below the *unvested*
//! amount for any reason other than transaction fee payment.
//!
//! As the amount vested increases over time, the amount unvested reduces. However, locks remain in
//! place and explicit action is needed on behalf of the user to ensure that the amount locked is
//! equivalent to the amount remaining to be vested. This is done through a dispatchable function,
//! either `vest` (in typical case where the sender is calling on their own behalf) or `vest_other`
//! in case the sender is calling on another account's behalf.
//!
//! ## Interface
//!
//! This pallet implements the `VestingSchedule` trait.
//!
//! ### Dispatchable Functions
//!
//! - `vest` - Update the lock, reducing it in line with the amount "vested" so far.
//! - `vest_other` - Update the lock of another account, reducing it in line with the amount
//! "vested" so far.
#![cfg_attr(not(feature = "std"), no_std)]
mod benchmarking;
pub mod weights;
use sp_std::{prelude::*, fmt::Debug, convert::TryInto};
use codec::{Encode, Decode};
use sp_runtime::{RuntimeDebug, traits::{
StaticLookup, Zero, AtLeast32BitUnsigned, MaybeSerializeDeserialize, Convert, Saturating, CheckedDiv
}};
use frame_support::{ensure, pallet_prelude::*};
use frame_support::traits::{
Currency, LockableCurrency, VestingSchedule, WithdrawReasons, LockIdentifier,
ExistenceRequirement, Get,
};
use frame_system::{ensure_signed, ensure_root, pallet_prelude::*};
pub use weights::WeightInfo;
pub use pallet::*;
pub use vesting_info::*;
type BalanceOf<T> = <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
type MaxLocksOf<T> = <<T as Config>::Currency as LockableCurrency<<T as frame_system::Config>::AccountId>>::MaxLocks;
const VESTING_ID: LockIdentifier = *b"vesting ";
// Module to enforce private fields on `VestingInfo`
mod vesting_info {
use super::*;
/// Struct to encode the vesting schedule of an individual account.
#[derive(Encode, Decode, Copy, Clone, PartialEq, Eq, RuntimeDebug)]
pub struct VestingInfo<Balance, BlockNumber> {
/// Locked amount at genesis.
locked: Balance,
/// Amount that gets unlocked every block after `starting_block`.
per_block: Balance,
/// Starting block for unlocking(vesting).
starting_block: BlockNumber,
}
impl<Balance: AtLeast32BitUnsigned + Copy, BlockNumber: AtLeast32BitUnsigned + Copy>
VestingInfo<Balance, BlockNumber>
{
/// Instantiate a new `VestingInfo` and validate parameters
pub fn try_new<T: Config>(
locked: Balance,
per_block: Balance,
starting_block: BlockNumber,
) -> Result<VestingInfo<Balance, BlockNumber>, Error<T>> {
Self::validate_params(locked, per_block, starting_block)?;
let per_block = if per_block > locked { locked } else { per_block };
Ok(VestingInfo { locked, per_block, starting_block })
}
/// Validate parameters for `VestingInfo`.
pub fn validate_params<T: Config>(
locked: Balance,
per_block: Balance,
_starting_block: BlockNumber,
) -> Result<(), Error<T>> {
ensure!(!locked.is_zero() && !per_block.is_zero(), Error::<T>::InvalidScheduleParams);
let min_transfer: u32 = T::MinVestedTransfer::get().try_into().unwrap_or(u32::MAX);
let min_transfer = Balance::from(min_transfer);
ensure!(locked >= min_transfer, Error::<T>::AmountLow);
Ok(())
}
/// Instantiate a new `VestingInfo` without param validation. Useful for
/// mocking bad inputs in testing.
pub fn unsafe_new(
locked: Balance,
per_block: Balance,
starting_block: BlockNumber,
) -> VestingInfo<Balance, BlockNumber> {
VestingInfo { locked, per_block, starting_block }
}
/// Locked amount at genesis.
pub fn locked(&self) -> Balance {
self.locked
}
/// Amount that gets unlocked every block after `starting_block`.
pub fn per_block(&self) -> Balance {
self.per_block
}
/// Starting block for unlocking(vesting).
pub fn starting_block(&self) -> BlockNumber {
self.starting_block
}
/// Amount locked at block `n`.
pub fn locked_at<BlockNumberToBalance: Convert<BlockNumber, Balance>>(
&self,
n: BlockNumber,
) -> Balance {
// Number of blocks that count toward vesting
// Saturating to 0 when n < starting_block
let vested_block_count = n.saturating_sub(self.starting_block);
let vested_block_count = BlockNumberToBalance::convert(vested_block_count);
// Return amount that is still locked in vesting
let maybe_balance = vested_block_count.checked_mul(&self.per_block);
if let Some(balance) = maybe_balance {
self.locked.saturating_sub(balance)
} else {
Zero::zero()
}
}
/// Block number at which the schedule ends
pub fn ending_block<BlockNumberToBalance: Convert<BlockNumber, Balance>>(&self) -> Balance {
let starting_block = BlockNumberToBalance::convert(self.starting_block);
let duration = if self.per_block > self.locked {
// If `per_block` is bigger than `locked`, the schedule will end
// the block after starting
1u32.into()
} else if self.per_block.is_zero() {
// Check for div by 0 errors, which should only be from legacy
// vesting schedules since new ones are validated for this.
self.locked
} else {
let has_remainder = !(self.locked % self.per_block).is_zero();
let maybe_duration = self.locked / self.per_block;
if has_remainder {
maybe_duration + 1u32.into()
} else {
maybe_duration
}
};
starting_block.saturating_add(duration)
}
}
}
/// The indexes of vesting schedules to remove from an accounts vesting schedule collection.
enum Filter {
/// Do not filter out any schedules.
Zero,
/// Filter out 1 schedule.
One(usize),
/// Filter out 2 schedules.
Two((usize, usize)),
}
impl Filter {
/// Wether or not the filter says the schedule index should be removed.
fn should_remove(&self, index: &usize) -> bool {
match self {
Self::Zero => false,
Self::One(index1) => index1 == index,
Self::Two((index1, index2)) => index1 == index || index2 == index,
}
}
}
#[frame_support::pallet]
pub mod pallet {
use super::*;
#[pallet::config]
pub trait Config: frame_system::Config {
/// The overarching event type.
type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;
/// The currency trait.
type Currency: LockableCurrency<Self::AccountId>;
/// Convert the block number into a balance.
type BlockNumberToBalance: Convert<Self::BlockNumber, BalanceOf<Self>>;
/// The minimum amount transferred to call `vested_transfer`.
#[pallet::constant]
type MinVestedTransfer: Get<BalanceOf<Self>>;
/// Weight information for extrinsics in this pallet.
type WeightInfo: WeightInfo;
/// Maximum number of vesting schedules an account may have at a given moment.
#[pallet::constant]
type MaxVestingSchedules: Get<u32>;
}
/// Information regarding the vesting of a given account.
#[pallet::storage]
#[pallet::getter(fn vesting)]
pub type Vesting<T: Config> = StorageMap<
_,
Blake2_128Concat,
T::AccountId,
BoundedVec<VestingInfo<BalanceOf<T>, T::BlockNumber>, T::MaxVestingSchedules>
>;
#[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
pub struct Pallet<T>(_);
#[pallet::genesis_config]
pub struct GenesisConfig<T: Config> {
pub vesting: Vec<(T::AccountId, T::BlockNumber, T::BlockNumber, BalanceOf<T>)>,
}
#[cfg(feature = "std")]
impl<T: Config> Default for GenesisConfig<T> {
fn default() -> Self {
GenesisConfig {
vesting: Default::default(),
}
}
}
#[pallet::genesis_build]
impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {
fn build(&self) {
use sp_runtime::traits::Saturating;
// Generate initial vesting configuration
// * who - Account which we are generating vesting configuration for
// * begin - Block when the account will start to vest
// * length - Number of blocks from `begin` until fully vested
// * liquid - Number of units which can be spent before vesting begins
for &(ref who, begin, length, liquid) in self.vesting.iter() {
let balance = T::Currency::free_balance(who);
assert!(!balance.is_zero(), "Currencies must be init'd before vesting");
// Total genesis `balance` minus `liquid` equals funds locked for vesting
let locked = balance.saturating_sub(liquid);
let length_as_balance = T::BlockNumberToBalance::convert(length);
let per_block = locked / length_as_balance.max(sp_runtime::traits::One::one());
let vesting_info = VestingInfo::try_new::<T>(locked, per_block, begin)
.expect("Invalid VestingInfo params at genesis");
Vesting::<T>::try_append(who, vesting_info)
.expect("Too many vesting schedules at genesis.");
let reasons = WithdrawReasons::TRANSFER | WithdrawReasons::RESERVE;
T::Currency::set_lock(VESTING_ID, who, locked, reasons);
}
}
}
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
#[pallet::metadata(
T::AccountId = "AccountId", BalanceOf<T> = "Balance", T::BlockNumber = "BlockNumber"
)]
pub enum Event<T: Config> {
/// The amount vested has been updated. This could indicate more funds are available. The
/// balance given is the amount which is left unvested (and thus locked).
/// \[account, unvested\]
VestingUpdated(T::AccountId, BalanceOf<T>),
/// An \[account\] has become fully vested. No further vesting can happen.
VestingCompleted(T::AccountId),
/// 2 vesting schedules where successfully merged together.
///\[locked, per_block, starting_block\]
VestingMergeSuccess(BalanceOf<T>, BalanceOf<T>, T::BlockNumber),
}
/// Error for the vesting pallet.
#[pallet::error]
pub enum Error<T> {
/// The account given is not vesting.
NotVesting,
/// The account already has `MaxVestingSchedules` number of schedules and thus
/// cannot add another one. Consider merging existing schedules in order to add another.
AtMaxVestingSchedules,
/// Amount being transferred is too low to create a vesting schedule.
AmountLow,
/// At least one of the indexes is out of bounds of the vesting schedules.
ScheduleIndexOutOfBounds,
/// Failed to create a new schedule because the parameters where invalid. i.e. `per_block` or
/// `locked` was 0.
InvalidScheduleParams,
}
#[pallet::call]
impl<T: Config> Pallet<T> {
/// Unlock any vested funds of the sender account.
///
/// The dispatch origin for this call must be _Signed_ and the sender must have funds still
/// locked under this pallet.
///
/// Emits either `VestingCompleted` or `VestingUpdated`.
///
/// # <weight>
/// - `O(1)`.
/// - DbWeight: 2 Reads, 2 Writes
/// - Reads: Vesting Storage, Balances Locks, [Sender Account]
/// - Writes: Vesting Storage, Balances Locks, [Sender Account]
/// # </weight>
#[pallet::weight(T::WeightInfo::vest_locked(MaxLocksOf::<T>::get())
.max(T::WeightInfo::vest_unlocked(MaxLocksOf::<T>::get()))
)]
pub fn vest(origin: OriginFor<T>) -> DispatchResult {
let who = ensure_signed(origin)?;
Self::do_vest(who)
}
/// Unlock any vested funds of a `target` account.
///
/// The dispatch origin for this call must be _Signed_.
///
/// - `target`: The account whose vested funds should be unlocked. Must have funds still
/// locked under this pallet.
///
/// Emits either `VestingCompleted` or `VestingUpdated`.
///
/// # <weight>
/// - `O(1)`.
/// - DbWeight: 3 Reads, 3 Writes
/// - Reads: Vesting Storage, Balances Locks, Target Account
/// - Writes: Vesting Storage, Balances Locks, Target Account
/// # </weight>
#[pallet::weight(T::WeightInfo::vest_other_locked(MaxLocksOf::<T>::get())
.max(T::WeightInfo::vest_other_unlocked(MaxLocksOf::<T>::get()))
)]
pub fn vest_other(
origin: OriginFor<T>,
target: <T::Lookup as StaticLookup>::Source,
) -> DispatchResult {
ensure_signed(origin)?;
let who = T::Lookup::lookup(target)?;
Self::do_vest(who)
}
/// Create a vested transfer.
///
/// The dispatch origin for this call must be _Signed_.
///
/// - `target`: The account that should be transferred the vested funds.
/// - `schedule`: The vesting schedule attached to the transfer.
///
/// Emits `VestingCreated`.
///
/// # <weight>
/// - `O(1)`.
/// - DbWeight: 3 Reads, 3 Writes
/// - Reads: Vesting Storage, Balances Locks, Target Account, [Sender Account]
/// - Writes: Vesting Storage, Balances Locks, Target Account, [Sender Account]
/// # </weight>
#[pallet::weight(
T::WeightInfo::last_vested_transfer(MaxLocksOf::<T>::get())
.max(T::WeightInfo::first_vested_transfer(MaxLocksOf::<T>::get()))
)]
pub fn vested_transfer(
origin: OriginFor<T>,
target: <T::Lookup as StaticLookup>::Source,
schedule: VestingInfo<BalanceOf<T>, T::BlockNumber>,
) -> DispatchResult {
let transactor = ensure_signed(origin)?;
let transactor = <T::Lookup as StaticLookup>::unlookup(transactor);
Self::do_vested_transfer(transactor, target, schedule)
}
/// Force a vested transfer.
///
/// The dispatch origin for this call must be _Root_.
///
/// - `source`: The account whose funds should be transferred.
/// - `target`: The account that should be transferred the vested funds.
/// - `schedule`: The vesting schedule attached to the transfer.
///
/// Emits `VestingCreated`.
///
/// # <weight>
/// - `O(1)`.
/// - DbWeight: 4 Reads, 4 Writes
/// - Reads: Vesting Storage, Balances Locks, Target Account, Source Account
/// - Writes: Vesting Storage, Balances Locks, Target Account, Source Account
/// # </weight>
#[pallet::weight(
T::WeightInfo::first_force_vested_transfer(MaxLocksOf::<T>::get())
.max(T::WeightInfo::last_force_vested_transfer(MaxLocksOf::<T>::get()))
)]
pub fn force_vested_transfer(
origin: OriginFor<T>,
source: <T::Lookup as StaticLookup>::Source,
target: <T::Lookup as StaticLookup>::Source,
schedule: VestingInfo<BalanceOf<T>, T::BlockNumber>,
) -> DispatchResult {
ensure_root(origin)?;
Self::do_vested_transfer(source, target, schedule)
}
/// Merge two vesting schedules together, creating a new vesting schedule that unlocks over
/// highest possible start and end blocks. If both schedules have already started the current
/// block will be used as the schedule start; with the caveat that if one schedule is finishes by
/// the current block, the other will be treated as the new merged schedule, unmodified.
///
/// NOTE: If `schedule1_index == schedule2_index` this is a no-op.
/// NOTE: This will unlock all schedules through the current block prior to merging.
/// NOTE: If both schedules have ended by the current block, no new schedule will be created.
///
/// Merged schedule attributes:
/// starting_block: `MAX(schedule1.starting_block, scheduled2.starting_block, current_block)`.
/// ending_block: `MAX(schedule1.ending_block, schedule2.ending_block)`.
/// locked: `schedule1.locked_at(current_block) + schedule2.locked_at(current_block)`.
///
/// The dispatch origin for this call must be _Signed_.
///
/// - `schedule1_index`: index of the first schedule to merge.
/// - `schedule2_index`: index of the second schedule to merge.
///
/// # <weight>
/// - `O(1)`.
/// - DbWeight: TODO Reads, TODO Writes
/// - Reads: TODO
/// - Writes: TODO
/// # </weight>
#[pallet::weight(
T::WeightInfo::not_unlocking_merge_schedules(MaxLocksOf::<T>::get())
.max(T::WeightInfo::unlocking_merge_schedules(MaxLocksOf::<T>::get()))
)]
pub fn merge_schedules(
origin: OriginFor<T>,
schedule1_index: u32,
schedule2_index: u32,
) -> DispatchResult {
if schedule1_index == schedule2_index {
return Ok(());
};
let who = ensure_signed(origin)?;
let schedule1_index = schedule1_index as usize;
let schedule2_index = schedule2_index as usize;
let vesting = Self::vesting(&who).ok_or(Error::<T>::NotVesting)?;
let len = vesting.len();
ensure!(
schedule1_index < len && schedule2_index < len,
Error::<T>::ScheduleIndexOutOfBounds
);
// The schedule index is based off of the schedule ordering prior to filtering out any
// schedules that may be ending at this block.
let schedule1 = vesting[schedule1_index];
let schedule2 = vesting[schedule2_index];
let filter = Filter::Two((schedule1_index, schedule2_index));
// The length of vesting decreases by 2 here since we filter out 2 schedules. Thus we know
// below that we can safely insert the new merged schedule.
let maybe_vesting = Self::update_lock_and_schedules(who.clone(), vesting, filter);
// We can't fail from here on because we have potentially removed two schedules.
let now = <frame_system::Pallet<T>>::block_number();
if let Some(s) = Self::merge_vesting_info(now, schedule1, schedule2) {
let mut vesting = maybe_vesting.unwrap_or_default();
// It shouldn't be possible for this to fail because we removed 2 schedules above.
ensure!(vesting.try_push(s).is_ok(), Error::<T>::AtMaxVestingSchedules);
Self::deposit_event(Event::<T>::VestingMergeSuccess(
s.locked(),
s.per_block(),
s.starting_block(),
));
Vesting::<T>::insert(&who, vesting);
} else if maybe_vesting.is_some() {
Vesting::<T>::insert(&who, maybe_vesting.unwrap());
} else {
Vesting::<T>::remove(&who);
}
Ok(())
}
}
}
impl<T: Config> Pallet<T> {
// Create a new `VestingInfo`, based off of two other `VestingInfo`s.
// NOTE: We assume both schedules have been vested up through the current block.
fn merge_vesting_info(
now: T::BlockNumber,
schedule1: VestingInfo<BalanceOf<T>, T::BlockNumber>,
schedule2: VestingInfo<BalanceOf<T>, T::BlockNumber>,
) -> Option<VestingInfo<BalanceOf<T>, T::BlockNumber>> {
let schedule1_ending_block = schedule1.ending_block::<T::BlockNumberToBalance>();
let schedule2_ending_block = schedule2.ending_block::<T::BlockNumberToBalance>();
let now_as_balance = T::BlockNumberToBalance::convert(now);
if schedule1_ending_block <= now_as_balance && schedule2_ending_block <= now_as_balance {
// If both schedules hav ended, we don't merge and exit early.
return None;
} else if schedule1_ending_block <= now_as_balance {
// If one schedule has ended, we treat the one that has not ended as the new
// merged schedule.
return Some(schedule2);
} else if schedule2_ending_block <= now_as_balance {
return Some(schedule1);
}
let locked = schedule1
.locked_at::<T::BlockNumberToBalance>(now)
.saturating_add(schedule2.locked_at::<T::BlockNumberToBalance>(now));
// This shouldn't happen because we know at least one ending block is greater than now.
if locked.is_zero() {
return None;
}
let ending_block = schedule1_ending_block.max(schedule2_ending_block);
let starting_block = now.max(schedule1.starting_block()).max(schedule2.starting_block());
let duration =
ending_block.saturating_sub(T::BlockNumberToBalance::convert(starting_block));
let per_block = if duration.is_zero() {
// The logic of `ending_block` guarantees that each schedule ends at least a block
// after it starts and since we take the max starting and ending_block we should never
// get here
locked
} else if duration > locked {
// This would mean we have a per_block of less than 1, which should not be not possible
// because when we create the new schedule is at most the same duration as the longest,
// but never greater.
1u32.into()
} else {
locked.checked_div(&duration)?
};
// At this point inputs have been validated, so this should always be `Some`.
VestingInfo::try_new::<T>(locked, per_block, starting_block).ok()
}
// Execute a vested transfer from `source` to `target` with the given `schedule`.
fn do_vested_transfer(
source: <T::Lookup as StaticLookup>::Source,
target: <T::Lookup as StaticLookup>::Source,
schedule: VestingInfo<BalanceOf<T>, T::BlockNumber>,
) -> DispatchResult {
VestingInfo::validate_params::<T>(
schedule.locked(),
schedule.per_block(),
schedule.starting_block(),
)?;
let target = T::Lookup::lookup(target)?;
let source = T::Lookup::lookup(source)?;
if let Some(len) = Vesting::<T>::decode_len(&target) {
ensure!(
len < T::MaxVestingSchedules::get() as usize,
Error::<T>::AtMaxVestingSchedules
);
}
T::Currency::transfer(
&source,
&target,
schedule.locked(),
ExistenceRequirement::AllowDeath,
)?;
// We can't let this fail because the currency transfer has already happened
Self::add_vesting_schedule(
&target,
schedule.locked(),
schedule.per_block(),
schedule.starting_block(),
)
.expect("schedule inputs and vec bounds have been validated. q.e.d.");
Ok(())
}
/// (Re)set or remove the pallet's currency lock on `who`'s account in accordance with their
/// current unvested amount and prune any vesting schedules that have completed.
///
/// NOTE: This will update the users lock, but will not read/write the `Vesting` storage item.
fn update_lock_and_schedules(
who: T::AccountId,
vesting: BoundedVec<VestingInfo<BalanceOf<T>, T::BlockNumber>, T::MaxVestingSchedules>,
filter: Filter,
) -> Option<BoundedVec<VestingInfo<BalanceOf<T>, T::BlockNumber>, T::MaxVestingSchedules>> {
let now = <frame_system::Pallet<T>>::block_number();
let mut total_locked_now: BalanceOf<T> = Zero::zero();
let still_vesting = vesting
.into_iter()
.enumerate()
.filter_map(|(index, schedule)| {
let locked_now = schedule.locked_at::<T::BlockNumberToBalance>(now);
total_locked_now = total_locked_now.saturating_add(locked_now);
if locked_now.is_zero() || filter.should_remove(&index) {
None
} else {
Some(schedule)
}
})
.collect::<Vec<_>>()
.try_into()
.expect("`BoundedVec` is created from another `BoundedVec` with same bound; q.e.d.");
if total_locked_now.is_zero() {
T::Currency::remove_lock(VESTING_ID, &who);
Vesting::<T>::remove(&who);
Self::deposit_event(Event::<T>::VestingCompleted(who));
None
} else {
let reasons = WithdrawReasons::TRANSFER | WithdrawReasons::RESERVE;
T::Currency::set_lock(VESTING_ID, &who, total_locked_now, reasons);
Self::deposit_event(Event::<T>::VestingUpdated(who, total_locked_now));
Some(still_vesting)
}
}
/// Unlock any vested funds of `who`.
fn do_vest(who: T::AccountId) -> DispatchResult {
let vesting = Self::vesting(&who).ok_or(Error::<T>::NotVesting)?;
let maybe_vesting = Self::update_lock_and_schedules(who.clone(), vesting, Filter::Zero);
if let Some(vesting) = maybe_vesting {
Vesting::<T>::insert(&who, vesting);
} else {
Vesting::<T>::remove(&who);
}
Ok(())
}
}
impl<T: Config> VestingSchedule<T::AccountId> for Pallet<T>
where
BalanceOf<T>: MaybeSerializeDeserialize + Debug,
{
type Currency = T::Currency;
type Moment = T::BlockNumber;
/// Get the amount that is currently being vested and cannot be transferred out of this account.
fn vesting_balance(who: &T::AccountId) -> Option<BalanceOf<T>> {
if let Some(v) = Self::vesting(who) {
let now = <frame_system::Pallet<T>>::block_number();
let total_locked_now = v.iter().fold(Zero::zero(), |total, schedule| {
schedule.locked_at::<T::BlockNumberToBalance>(now).saturating_add(total)
});
Some(T::Currency::free_balance(who).min(total_locked_now))
} else {
None
}
}
/// Adds a vesting schedule to a given account.
///
/// If there are already `MaxVestingSchedules`, an Error is returned and nothing
/// is updated.
///
/// On success, a linearly reducing amount of funds will be locked. In order to realise any
/// reduction of the lock over time as it diminishes, the account owner must use `vest` or
/// `vest_other`.
///
/// Is a no-op if the amount to be vested is zero.
fn add_vesting_schedule(
who: &T::AccountId,
locked: BalanceOf<T>,
per_block: BalanceOf<T>,
starting_block: T::BlockNumber,
) -> DispatchResult {
if locked.is_zero() {
return Ok(());
}
let vesting_schedule = VestingInfo::try_new::<T>(locked, per_block, starting_block)?;
let mut vesting = if let Some(v) = Self::vesting(who) { v } else { BoundedVec::default() };
ensure!(vesting.try_push(vesting_schedule).is_ok(), Error::<T>::AtMaxVestingSchedules);
if let Some(v) = Self::update_lock_and_schedules(who.clone(), vesting, Filter::Zero) {
Vesting::<T>::insert(&who, v);
} else {
Vesting::<T>::remove(&who);
}
Ok(())
}
/// Remove a vesting schedule for a given account. Will error if `schedule_index` is `None`.
fn remove_vesting_schedule(who: &T::AccountId, schedule_index: Option<u32>) -> DispatchResult {
let schedule_index = schedule_index.ok_or(Error::<T>::ScheduleIndexOutOfBounds)?;
let filter = Filter::One(schedule_index as usize);
let vesting = Self::vesting(who).ok_or(Error::<T>::NotVesting)?;
if let Some(v) = Self::update_lock_and_schedules(who.clone(), vesting, filter) {
Vesting::<T>::insert(&who, v);
} else {
Vesting::<T>::remove(&who);
};
Ok(())
}
}
#[cfg(test)]
mod tests {
use frame_support::{assert_noop, assert_ok, assert_storage_noop, parameter_types};
use frame_system::RawOrigin;
use sp_core::H256;
use sp_runtime::{
testing::Header,
traits::{BadOrigin, BlakeTwo256, Identity, IdentityLookup},
};
use super::*;
use crate as pallet_vesting;
type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
type Block = frame_system::mocking::MockBlock<Test>;
frame_support::construct_runtime!(
pub enum Test where
Block = Block,
NodeBlock = Block,
UncheckedExtrinsic = UncheckedExtrinsic,
{
System: frame_system::{Pallet, Call, Config, Storage, Event<T>},
Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>},
Vesting: pallet_vesting::{Pallet, Call, Storage, Event<T>, Config<T>},
}
);
parameter_types! {
pub const BlockHashCount: u64 = 250;
pub BlockWeights: frame_system::limits::BlockWeights =
frame_system::limits::BlockWeights::simple_max(1024);
}
impl frame_system::Config for Test {
type BaseCallFilter = ();
type BlockWeights = ();
type BlockLength = ();
type DbWeight = ();
type Origin = Origin;
type Index = u64;
type BlockNumber = u64;
type Hash = H256;
type Call = Call;
type Hashing = BlakeTwo256;
type AccountId = u64;
type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header;
type Event = Event;
type BlockHashCount = BlockHashCount;
type Version = ();
type PalletInfo = PalletInfo;
type AccountData = pallet_balances::AccountData<u64>;
type OnNewAccount = ();
type OnKilledAccount = ();
type SystemWeightInfo = ();
type SS58Prefix = ();
type OnSetCode = ();
}
parameter_types! {
pub const MaxLocks: u32 = 10;
}
impl pallet_balances::Config for Test {
type Balance = u64;
type DustRemoval = ();
type Event = Event;
type ExistentialDeposit = ExistentialDeposit;
type AccountStore = System;
type MaxLocks = MaxLocks;
type MaxReserves = ();
type ReserveIdentifier = [u8; 8];
type WeightInfo = ();
}
parameter_types! {
pub const MinVestedTransfer: u64 = 10;
pub static ExistentialDeposit: u64 = 0;
pub const MaxVestingSchedules: u32 = 3;
}
impl Config for Test {
type Event = Event;
type Currency = Balances;
type BlockNumberToBalance = Identity;
type MinVestedTransfer = MinVestedTransfer;
type WeightInfo = ();
type MaxVestingSchedules = MaxVestingSchedules;
}
pub struct ExtBuilder {
existential_deposit: u64,
vesting_genesis_config: Option<Vec<(u64, u64, u64, u64)>>,
}
impl Default for ExtBuilder {
fn default() -> Self {
Self {
existential_deposit: 1,
vesting_genesis_config: None,
}
}
}
impl ExtBuilder {
pub fn existential_deposit(mut self, existential_deposit: u64) -> Self {
self.existential_deposit = existential_deposit;
self
}
pub fn vesting_genesis_config(mut self, config: Vec<(u64, u64, u64, u64)>) -> Self {
self.vesting_genesis_config = Some(config);
self
}
pub fn build(self) -> sp_io::TestExternalities {
EXISTENTIAL_DEPOSIT.with(|v| *v.borrow_mut() = self.existential_deposit);
let mut t = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap();
pallet_balances::GenesisConfig::<Test> {
balances: vec![
(1, 10 * self.existential_deposit),
(2, 20 * self.existential_deposit),
(3, 30 * self.existential_deposit),
(4, 40 * self.existential_deposit),
(12, 10 * self.existential_deposit)
],
}.assimilate_storage(&mut t).unwrap();
let vesting = if let Some(vesting_config) = self.vesting_genesis_config {
vesting_config
} else {
vec![
(1, 0, 10, 5 * self.existential_deposit),
(2, 10, 20, 0),
(12, 10, 20, 5 * self.existential_deposit)
]
};
pallet_vesting::GenesisConfig::<Test> {
vesting
}.assimilate_storage(&mut t).unwrap();
let mut ext = sp_io::TestExternalities::new(t);
ext.execute_with(|| System::set_block_number(1));
ext
}
}
/// A default existential deposit.
const ED: u64 = 256;
#[test]
fn check_vesting_status() {
ExtBuilder::default()
.existential_deposit(256)
.build()
.execute_with(|| {
let user1_free_balance = Balances::free_balance(&1);
let user2_free_balance = Balances::free_balance(&2);
let user12_free_balance = Balances::free_balance(&12);
assert_eq!(user1_free_balance, 256 * 10); // Account 1 has free balance
assert_eq!(user2_free_balance, 256 * 20); // Account 2 has free balance
assert_eq!(user12_free_balance, 256 * 10); // Account 12 has free balance
let user1_vesting_schedule = VestingInfo::try_new::<Test>(
256 * 5,
128, // Vesting over 10 blocks
0,
)
.unwrap();
let user2_vesting_schedule = VestingInfo::try_new::<Test>(
256 * 20,
256, // Vesting over 20 blocks
10,
)
.unwrap();
let user12_vesting_schedule = VestingInfo::try_new::<Test>(
256 * 5,
64, // Vesting over 20 blocks
10,
)
.unwrap();
assert_eq!(Vesting::vesting(&1).unwrap(), vec![user1_vesting_schedule]); // Account 1 has a vesting schedule
assert_eq!(Vesting::vesting(&2).unwrap(), vec![user2_vesting_schedule]); // Account 2 has a vesting schedule
assert_eq!(Vesting::vesting(&12).unwrap(), vec![user12_vesting_schedule]); // Account 12 has a vesting schedule
// Account 1 has only 128 units vested from their illiquid 256 * 5 units at block 1
assert_eq!(Vesting::vesting_balance(&1), Some(128 * 9));
// Account 2 has their full balance locked
assert_eq!(Vesting::vesting_balance(&2), Some(user2_free_balance));
// Account 12 has only their illiquid funds locked
assert_eq!(Vesting::vesting_balance(&12), Some(user12_free_balance - 256 * 5));
System::set_block_number(10);
assert_eq!(System::block_number(), 10);
// Account 1 has fully vested by block 10
assert_eq!(Vesting::vesting_balance(&1), Some(0));
// Account 2 has started vesting by block 10
assert_eq!(Vesting::vesting_balance(&2), Some(user2_free_balance));
// Account 12 has started vesting by block 10
assert_eq!(Vesting::vesting_balance(&12), Some(user12_free_balance - 256 * 5));
System::set_block_number(30);
assert_eq!(System::block_number(), 30);
assert_eq!(Vesting::vesting_balance(&1), Some(0)); // Account 1 is still fully vested, and not negative
assert_eq!(Vesting::vesting_balance(&2), Some(0)); // Account 2 has fully vested by block 30
assert_eq!(Vesting::vesting_balance(&12), Some(0)); // Account 2 has fully vested by block 30
});
}
#[test]
fn check_vesting_status_for_multi_schedule_account() {
ExtBuilder::default().existential_deposit(ED).build().execute_with(|| {
assert_eq!(System::block_number(), 1);
let sched0 = VestingInfo::try_new::<Test>(
ED * 20,
ED, // Vesting over 20 blocks
10,
)
.unwrap();
// Use 2 already has a vesting schedule.
assert_eq!(Vesting::vesting(&2).unwrap(), vec![sched0]);
// User 2's free balance is from sched0
let free_balance = Balances::free_balance(&2);
assert_eq!(free_balance, ED * (20));
assert_eq!(Vesting::vesting_balance(&2), Some(free_balance));
// Add a 2nd schedule that is already unlocking by block #1
let sched1 = VestingInfo::try_new::<Test>(
ED * 10,
ED, // Vesting over 10 blocks
0,
)
.unwrap();
assert_ok!(Vesting::vested_transfer(Some(4).into(), 2, sched1));
// Free balance is equal to the two existing schedules total amount.
let free_balance = Balances::free_balance(&2);
assert_eq!(free_balance, ED * (10 + 20));
// The most recently added schedule exists.
assert_eq!(Vesting::vesting(&2).unwrap(), vec![sched0, sched1]);
// sched1 has free funds at block #1, but nothing else.
assert_eq!(Vesting::vesting_balance(&2), Some(free_balance - sched1.per_block()));
// Add a 3rd schedule
let sched2 = VestingInfo::try_new::<Test>(
ED * 30,
ED, // Vesting over 30 blocks
5,
)
.unwrap();
assert_ok!(Vesting::vested_transfer(Some(4).into(), 2, sched2));
System::set_block_number(9);
// Free balance is equal to the 3 existing schedules total amount.
let free_balance = Balances::free_balance(&2);
assert_eq!(free_balance, ED * (10 + 20 + 30));
// sched1 and sched2 are freeing funds at block #9.
assert_eq!(
Vesting::vesting_balance(&2),
Some(free_balance - sched1.per_block() * 9 - sched2.per_block() * 4)
);
System::set_block_number(20);
// At block #20 sched1 is fully unlocked while sched2 and sched0 are partially unlocked.
assert_eq!(
Vesting::vesting_balance(&2),
Some(
free_balance -
sched1.locked() - sched2.per_block() * 15 -
sched0.per_block() * 10
)
);
System::set_block_number(30);
// At block #30 sched0 and sched1 are fully unlocked while sched2 is partially unlocked.
assert_eq!(
Vesting::vesting_balance(&2),
Some(
free_balance - sched1.locked() - sched2.per_block() * 25 - sched0.locked()
)
);