forked from MettaChain/PropChain-contract
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlib.rs
More file actions
1716 lines (1493 loc) · 61.8 KB
/
Copy pathlib.rs
File metadata and controls
1716 lines (1493 loc) · 61.8 KB
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
#![allow(clippy::clone_on_copy)] // fires inside ink! generated storage code
#![cfg_attr(not(feature = "std"), no_std, no_main)]
#![allow(
unused_imports,
dead_code,
clippy::needless_borrows_for_generic_args,
clippy::too_many_arguments
)]
#[ink::contract]
mod staking {
use ink::prelude::vec::Vec;
use ink::storage::Mapping;
use propchain_traits::constants;
use propchain_traits::errors::*;
include!("errors.rs");
include!("types.rs");
impl From<propchain_traits::ReentrancyError> for Error {
fn from(_: propchain_traits::ReentrancyError) -> Self {
Error::ReentrantCall
}
}
// Defaults for the on-chain governance module. They are themselves
// changeable via parameter proposals (ParamKind::VotingPeriodBlocks /
// QuorumBps), so any clearly-wrong choice here can be voted out.
const DEFAULT_VOTING_PERIOD_BLOCKS: u64 = 28_800; // ~2 days at 6s blocks
const DEFAULT_QUORUM_BPS: u32 = 1_000; // 10%
const MAX_ACTIVE_PARAM_PROPOSALS: u32 = 50;
const BPS_DENOMINATOR: u32 = 10_000;
// =========================================================================
// Events
// =========================================================================
#[ink(event)]
pub struct Staked {
#[ink(topic)]
pub staker: AccountId,
pub amount: u128,
pub lock_period: LockPeriod,
pub lock_until: u64,
}
#[ink(event)]
pub struct Unstaked {
#[ink(topic)]
pub staker: AccountId,
pub amount: u128,
}
#[ink(event)]
pub struct RewardsClaimed {
#[ink(topic)]
pub staker: AccountId,
pub amount: u128,
}
#[ink(event)]
pub struct GovernanceDelegated {
#[ink(topic)]
pub staker: AccountId,
#[ink(topic)]
pub delegate: AccountId,
}
#[ink(event)]
pub struct RewardPoolFunded {
#[ink(topic)]
pub funder: AccountId,
pub amount: u128,
}
#[ink(event)]
pub struct StakingConfigUpdated {
#[ink(topic)]
pub min_stake: u128,
#[ink(topic)]
pub reward_rate_bps: u128,
}
#[ink(event)]
pub struct AutoCompoundUpdated {
#[ink(topic)]
pub staker: AccountId,
pub auto_compound: bool,
}
#[ink(event)]
pub struct RewardsReinvested {
#[ink(topic)]
pub staker: AccountId,
pub amount: u128,
}
#[ink(event)]
pub struct ParamProposalCreated {
#[ink(topic)]
pub proposal_id: u64,
#[ink(topic)]
pub proposer: AccountId,
pub kind: ParamKind,
pub voting_end: u64,
}
#[ink(event)]
pub struct ParamVoteCast {
#[ink(topic)]
pub proposal_id: u64,
#[ink(topic)]
pub voter: AccountId,
pub support: bool,
pub weight: u128,
}
#[ink(event)]
pub struct EarlyWithdrawal {
#[ink(topic)]
pub staker: AccountId,
pub amount_returned: u128,
pub penalty: u128,
}
#[ink(event)]
pub struct VestingScheduleCreated {
#[ink(topic)]
pub staker: AccountId,
pub total_amount: u128,
pub cliff_block: u64,
pub end_block: u64,
}
#[ink(event)]
pub struct VestingRewardsClaimed {
#[ink(topic)]
pub staker: AccountId,
pub amount: u128,
pub total_vested: u128,
}
#[ink(event)]
pub struct ParamProposalExecuted {
#[ink(topic)]
pub proposal_id: u64,
pub kind: ParamKind,
pub executed_at: u64,
}
#[ink(event)]
pub struct ParamProposalRejected {
#[ink(topic)]
pub proposal_id: u64,
}
#[ink(event)]
pub struct ParamProposalCancelled {
#[ink(topic)]
pub proposal_id: u64,
}
// =========================================================================
// Storage
// =========================================================================
// =========================================================================
// Delegation Events
// =========================================================================
#[ink(event)]
pub struct ValidatorRegistered {
#[ink(topic)]
pub validator: AccountId,
pub self_stake: u128,
pub commission_rate: u32,
}
#[ink(event)]
pub struct CommissionRateUpdated {
#[ink(topic)]
pub validator: AccountId,
pub old_rate: u32,
pub new_rate: u32,
}
#[ink(event)]
pub struct StakeDelegated {
#[ink(topic)]
pub delegator: AccountId,
#[ink(topic)]
pub validator: AccountId,
pub amount: u128,
}
#[ink(event)]
pub struct UndelegationInitiated {
#[ink(topic)]
pub delegator: AccountId,
#[ink(topic)]
pub validator: AccountId,
pub amount: u128,
pub claimable_at: u64,
}
#[ink(event)]
pub struct UndelegatedTokensClaimed {
#[ink(topic)]
pub delegator: AccountId,
pub amount: u128,
}
#[ink(event)]
pub struct DelegationRewardsClaimed {
#[ink(topic)]
pub delegator: AccountId,
#[ink(topic)]
pub validator: AccountId,
pub amount: u128,
}
#[ink(event)]
pub struct ValidatorCommissionClaimed {
#[ink(topic)]
pub validator: AccountId,
pub amount: u128,
}
#[ink(event)]
pub struct ValidatorSlashed {
#[ink(topic)]
pub validator: AccountId,
pub slash_amount: u128,
pub delegated_reduction: u128,
}
#[ink(event)]
pub struct ValidatorDeactivated {
#[ink(topic)]
pub validator: AccountId,
pub reason: DeactivationReason,
}
#[ink(event)]
pub struct ValidatorReactivated {
#[ink(topic)]
pub validator: AccountId,
}
// =========================================================================
// Storage
// =========================================================================
#[ink(storage)]
pub struct Staking {
admin: AccountId,
stakes: Mapping<AccountId, StakeInfo>,
total_staked: u128,
reward_pool: u128,
reward_rate_bps: u128,
min_stake: u128,
acc_reward_per_share: u128,
last_reward_block: u64,
governance_power: Mapping<AccountId, u128>,
staker_list: Vec<AccountId>,
reentrancy_guard: propchain_traits::ReentrancyGuard,
slashing_coordinator: Option<AccountId>,
// ----- Parameter governance -----
proposal_counter: u64,
active_proposal_count: u32,
param_proposals: Mapping<u64, ParamProposal>,
param_votes: Mapping<(u64, AccountId), bool>,
voting_period_blocks: u64,
quorum_bps: u32,
early_withdrawal_penalty_bps: u128,
boost_curve: BoostCurve,
// ----- Validator / Delegation -----
validators: Mapping<AccountId, ValidatorInfo>,
delegations: Mapping<(AccountId, AccountId), DelegationRecord>,
validator_list: Vec<AccountId>,
total_delegated_stake: u128,
validator_delegators: Mapping<AccountId, Vec<AccountId>>,
delegator_validator: Mapping<AccountId, AccountId>,
}
// =========================================================================
// Implementation
// =========================================================================
impl Staking {
/// Creates a new Staking contract.
///
/// # Arguments
/// * `reward_rate_bps` - Annual reward rate in basis points (e.g. 500 = 5%)
/// * `min_stake` - Minimum stake amount
/// Create a new staking contract with the default Linear boost curve.
#[ink(constructor)]
pub fn new(reward_rate_bps: u128, min_stake: u128) -> Self {
let caller = Self::env().caller();
let safe_min = if min_stake == 0 {
constants::STAKING_MIN_AMOUNT
} else {
min_stake
};
Self {
admin: caller,
stakes: Mapping::default(),
total_staked: 0,
reward_pool: 0,
reward_rate_bps,
min_stake: safe_min,
acc_reward_per_share: 0,
last_reward_block: 0,
governance_power: Mapping::default(),
staker_list: Vec::new(),
reentrancy_guard: propchain_traits::ReentrancyGuard::new(),
slashing_coordinator: None,
proposal_counter: 0,
active_proposal_count: 0,
param_proposals: Mapping::default(),
param_votes: Mapping::default(),
voting_period_blocks: DEFAULT_VOTING_PERIOD_BLOCKS,
quorum_bps: DEFAULT_QUORUM_BPS,
early_withdrawal_penalty_bps: constants::DEFAULT_EARLY_WITHDRAWAL_PENALTY_BPS,
boost_curve: BoostCurve::Linear,
validators: Mapping::default(),
delegations: Mapping::default(),
validator_list: Vec::new(),
total_delegated_stake: 0,
validator_delegators: Mapping::default(),
delegator_validator: Mapping::default(),
}
}
// ----- Queries -----
/// Returns the stake info for an account.
#[ink(message)]
pub fn get_stake(&self, staker: AccountId) -> Option<StakeInfo> {
self.stakes.get(staker)
}
/// Returns total amount staked across all stakers.
#[ink(message)]
pub fn get_total_staked(&self) -> u128 {
self.total_staked
}
/// Returns the current reward pool balance.
#[ink(message)]
pub fn get_reward_pool(&self) -> u128 {
self.reward_pool
}
/// Returns the admin address.
#[ink(message)]
pub fn get_admin(&self) -> AccountId {
self.admin
}
/// Calculates pending rewards for a staker.
#[ink(message)]
pub fn get_pending_rewards(&self, staker: AccountId) -> u128 {
if let Some(stake) = self.stakes.get(staker) {
self.calculate_rewards(&stake)
} else {
0
}
}
/// Returns the governance power for an account (own + delegated).
#[ink(message)]
pub fn get_governance_power(&self, account: AccountId) -> u128 {
self.governance_power.get(account).unwrap_or(0)
}
/// Returns the minimum stake amount.
#[ink(message)]
pub fn get_min_stake(&self) -> u128 {
self.min_stake
}
/// Get the vested amount for a staker with a vesting schedule.
/// Returns the total amount vested so far (at current block).
#[ink(message)]
pub fn get_vested_amount(&self, staker: AccountId) -> u128 {
if let Some(stake) = self.stakes.get(staker) {
if let Some(vesting) = stake.vesting_schedule {
let now = self.env().block_number() as u64;
vesting.calculate_vested_at_block(now)
} else {
0
}
} else {
0
}
}
/// Get the unvested amount for a staker with a vesting schedule.
/// Returns the total amount still locked and not yet claimable.
#[ink(message)]
pub fn get_unvested_amount(&self, staker: AccountId) -> u128 {
if let Some(stake) = self.stakes.get(staker) {
if let Some(vesting) = stake.vesting_schedule {
let now = self.env().block_number() as u64;
let vested = vesting.calculate_vested_at_block(now);
vesting.total_amount.saturating_sub(vested)
} else {
0
}
} else {
0
}
}
/// Get claimable vested amount (vested but not yet claimed).
#[ink(message)]
pub fn get_claimable_vested_amount(&self, staker: AccountId) -> u128 {
if let Some(stake) = self.stakes.get(staker) {
if let Some(vesting) = stake.vesting_schedule {
let now = self.env().block_number() as u64;
let total_vested = if now < vesting.cliff_block {
0
} else if now >= vesting.end_block {
stake.original_amount
} else {
let blocks_elapsed = (now - vesting.cliff_block) as u128;
let total_blocks = (vesting.end_block - vesting.start_block) as u128;
stake
.original_amount
.saturating_mul(blocks_elapsed)
.checked_div(total_blocks)
.unwrap_or(0)
};
total_vested.saturating_sub(vesting.vested_amount)
} else {
0
}
} else {
0
}
}
/// Estimate projected staking rewards for a given amount, lock period, and duration.
/// This is a read-only calculator — no state is modified.
#[ink(message)]
pub fn calculate_projected_rewards(
&self,
amount: u128,
lock_period: LockPeriod,
duration_blocks: u64,
) -> u128 {
if amount == 0 || duration_blocks == 0 {
return 0;
}
let blocks = duration_blocks as u128;
// base_reward = amount * reward_rate_bps * blocks / REWARD_RATE_PRECISION / blocks_per_year
let base_reward = amount
.saturating_mul(self.reward_rate_bps)
.saturating_mul(blocks)
/ constants::REWARD_RATE_PRECISION
/ 5_256_000;
if base_reward == 0 {
return 0;
}
// Apply lock period multiplier
let multiplier = lock_period.multiplier_with_curve(Some(self.boost_curve));
let reward = base_reward.saturating_mul(multiplier) / 100;
// Apply staking tier bonus
let tier = self.get_tier_internal(amount);
let tier_multiplier = tier.reward_multiplier();
reward.saturating_mul(tier_multiplier) / 100
}
/// Returns the current boost curve configuration.
#[ink(message)]
pub fn get_boost_curve(&self) -> BoostCurve {
self.boost_curve
}
/// Returns the estimated reward plus the staking tier for a projected stake.
#[ink(message)]
pub fn calculate_projected_rewards_with_tier(
&self,
amount: u128,
lock_period: LockPeriod,
duration_blocks: u64,
) -> (u128, StakingTier) {
let reward = self.calculate_projected_rewards(amount, lock_period, duration_blocks);
let tier = self.get_tier_internal(amount);
(reward, tier)
}
// ----- Mutations -----
/// Stake tokens with a chosen lock period.
#[ink(message)]
pub fn stake(&mut self, amount: u128, lock_period: LockPeriod) -> Result<(), Error> {
let caller = self.env().caller();
if amount == 0 {
return Err(Error::ZeroAmount);
}
if amount < self.min_stake {
return Err(Error::InsufficientAmount);
}
if self.stakes.contains(caller) {
return Err(Error::AlreadyStaked);
}
let now = self.env().block_number() as u64;
let lock_until = now.saturating_add(lock_period.duration_blocks());
let stake_info = StakeInfo {
staker: caller,
amount,
original_amount: amount,
staked_at: now,
lock_until,
lock_period,
reward_debt: self.acc_reward_per_share,
governance_delegate: None,
auto_compound: false,
vesting_schedule: None,
};
self.stakes.insert(caller, &stake_info);
self.total_staked = self.total_staked.saturating_add(amount);
self.staker_list.push(caller);
// Grant governance power to self by default
let current_power = self.governance_power.get(caller).unwrap_or(0);
self.governance_power
.insert(caller, ¤t_power.saturating_add(amount));
self.env().emit_event(Staked {
staker: caller,
amount,
lock_period,
lock_until,
});
Ok(())
}
/// Stake tokens with a vesting schedule for rewards.
/// Rewards are distributed according to the vesting schedule instead of being immediately claimable.
///
/// # Arguments
/// * `amount` - The amount to stake
/// * `lock_period` - The lock period for the stake
/// * `total_reward_amount` - Total reward amount to vest over time
/// * `cliff_blocks` - Number of blocks until cliff (no rewards claimable before)
/// * `vesting_blocks` - Total number of blocks for linear vesting (from cliff to full vesting)
#[ink(message)]
pub fn stake_with_vesting(
&mut self,
amount: u128,
lock_period: LockPeriod,
total_reward_amount: u128,
cliff_blocks: u64,
vesting_blocks: u64,
) -> Result<(), Error> {
let caller = self.env().caller();
if amount == 0 {
return Err(Error::ZeroAmount);
}
if amount < self.min_stake {
return Err(Error::InsufficientAmount);
}
if self.stakes.contains(caller) {
return Err(Error::AlreadyStaked);
}
if total_reward_amount == 0 {
return Err(Error::ZeroAmount);
}
if total_reward_amount > self.reward_pool {
return Err(Error::InsufficientPool);
}
if vesting_blocks == 0 {
return Err(Error::InvalidConfig);
}
let now = self.env().block_number() as u64;
let lock_until = now.saturating_add(lock_period.duration_blocks());
let cliff_block = now.saturating_add(cliff_blocks);
let end_block = cliff_block.saturating_add(vesting_blocks);
let vesting_schedule = VestingSchedule {
total_amount: total_reward_amount,
vested_amount: 0,
start_block: now,
cliff_block,
end_block,
};
let stake_info = StakeInfo {
staker: caller,
amount,
original_amount: total_reward_amount,
staked_at: now,
lock_until,
lock_period,
reward_debt: self.acc_reward_per_share,
governance_delegate: None,
auto_compound: false,
vesting_schedule: Some(vesting_schedule),
};
// Reserve the reward amount from the pool
self.reward_pool = self.reward_pool.saturating_sub(total_reward_amount);
self.stakes.insert(caller, &stake_info);
self.total_staked = self.total_staked.saturating_add(amount);
self.staker_list.push(caller);
// Grant governance power to self by default
let current_power = self.governance_power.get(caller).unwrap_or(0);
self.governance_power
.insert(caller, ¤t_power.saturating_add(amount));
self.env().emit_event(Staked {
staker: caller,
amount,
lock_period,
lock_until,
});
self.env().emit_event(VestingScheduleCreated {
staker: caller,
total_amount: total_reward_amount,
cliff_block,
end_block,
});
Ok(())
}
/// Unstake tokens. If called before the lock period expires, a penalty
/// of `early_withdrawal_penalty_bps` is deducted from the returned amount.
/// The penalty amount is retained in the reward pool.
/// If vesting schedule exists, unvested rewards are returned to the reward pool.
#[ink(message)]
pub fn unstake(&mut self) -> Result<(), Error> {
propchain_traits::non_reentrant!(self, {
let caller = self.env().caller();
let stake = self.stakes.get(caller).ok_or(Error::StakeNotFound)?;
let now = self.env().block_number() as u64;
// Lock period is over, or we'll apply early withdrawal penalty
let amount = stake.amount;
let is_early = now < stake.lock_until;
// Calculate penalty for early withdrawal (zero for on-time or flexible)
let penalty = if is_early && stake.lock_period != LockPeriod::Flexible {
amount
.saturating_mul(self.early_withdrawal_penalty_bps)
.saturating_div(constants::BASIS_POINTS_DENOMINATOR as u128)
} else {
0
};
let amount_returned = amount.saturating_sub(penalty);
// Return unvested rewards to the pool if vesting schedule exists
if let Some(vesting) = stake.vesting_schedule {
let unvested = vesting.total_amount.saturating_sub(vesting.vested_amount);
self.reward_pool = self.reward_pool.saturating_add(unvested);
}
// Remove governance power
self.remove_governance_power(&stake);
self.stakes.remove(caller);
self.total_staked = self.total_staked.saturating_sub(amount);
// Penalty stays in the reward pool to benefit remaining stakers
if penalty > 0 {
self.reward_pool = self.reward_pool.saturating_add(penalty);
}
// Remove from staker list
if let Some(pos) = self.staker_list.iter().position(|s| *s == caller) {
self.staker_list.swap_remove(pos);
}
if is_early && stake.lock_period != LockPeriod::Flexible {
self.env().emit_event(EarlyWithdrawal {
staker: caller,
amount_returned,
penalty,
});
} else {
self.env().emit_event(Unstaked {
staker: caller,
amount,
});
}
Ok(())
})
}
/// Update the early withdrawal penalty rate. Admin only.
/// `penalty_bps` must not exceed `MAX_EARLY_WITHDRAWAL_PENALTY_BPS`.
///
#[ink(message)]
pub fn set_early_withdrawal_penalty(&mut self, penalty_bps: u128) -> Result<(), Error> {
if self.env().caller() != self.admin {
return Err(Error::Unauthorized);
}
if penalty_bps > constants::MAX_EARLY_WITHDRAWAL_PENALTY_BPS {
return Err(Error::InvalidConfig);
}
self.early_withdrawal_penalty_bps = penalty_bps;
Ok(())
}
/// Get the current early withdrawal penalty rate in basis points.
#[ink(message)]
pub fn get_early_withdrawal_penalty_bps(&self) -> u128 {
self.early_withdrawal_penalty_bps
}
/// Claim accumulated rewards.
#[ink(message)]
pub fn claim_rewards(&mut self) -> Result<u128, Error> {
propchain_traits::non_reentrant!(self, {
let caller = self.env().caller();
let mut stake = self.stakes.get(caller).ok_or(Error::StakeNotFound)?;
// Determine how much can be claimed
let claimable_amount = if let Some(vesting) = stake.vesting_schedule {
let now = self.env().block_number() as u64;
let total_vested = if now < vesting.cliff_block {
0
} else if now >= vesting.end_block {
stake.original_amount
} else {
let blocks_elapsed = (now - vesting.cliff_block) as u128;
let total_blocks = (vesting.end_block - vesting.start_block) as u128;
stake
.original_amount
.saturating_mul(blocks_elapsed)
.checked_div(total_blocks)
.unwrap_or(0)
};
let claimable = total_vested.saturating_sub(vesting.vested_amount);
if claimable == 0 {
return Err(Error::NoRewards);
}
claimable
} else {
// No vesting schedule, claim all accumulated rewards
let rewards = self.calculate_rewards(&stake);
if rewards == 0 {
return Err(Error::NoRewards);
}
rewards
};
if claimable_amount == 0 {
return Err(Error::NoRewards);
}
if claimable_amount > self.reward_pool {
return Err(Error::InsufficientPool);
}
let now = self.env().block_number() as u64;
self.reward_pool = self.reward_pool.saturating_sub(claimable_amount);
// Update vesting schedule if present
if let Some(mut vesting) = stake.vesting_schedule {
vesting.vested_amount = vesting.vested_amount.saturating_add(claimable_amount);
stake.vesting_schedule = Some(vesting);
self.stakes.insert(caller, &stake);
self.env().emit_event(VestingRewardsClaimed {
staker: caller,
amount: claimable_amount,
total_vested: vesting.vested_amount,
});
} else if stake.auto_compound {
stake.amount = stake.amount.saturating_add(claimable_amount);
self.total_staked = self.total_staked.saturating_add(claimable_amount);
// Update governance power
let power_holder = stake.governance_delegate.unwrap_or(stake.staker);
let current_power = self.governance_power.get(power_holder).unwrap_or(0);
self.governance_power.insert(
power_holder,
¤t_power.saturating_add(claimable_amount),
);
stake.staked_at = now;
stake.reward_debt = self.acc_reward_per_share;
self.stakes.insert(caller, &stake);
self.env().emit_event(RewardsReinvested {
staker: caller,
amount: claimable_amount,
});
} else {
stake.staked_at = now;
stake.reward_debt = self.acc_reward_per_share;
self.stakes.insert(caller, &stake);
self.env().emit_event(RewardsClaimed {
staker: caller,
amount: claimable_amount,
});
}
Ok(claimable_amount)
})
}
/// Opt-in or opt-out of automatic compounding.
#[ink(message)]
pub fn set_auto_compound(&mut self, auto_compound: bool) -> Result<(), Error> {
let caller = self.env().caller();
let mut stake = self.stakes.get(caller).ok_or(Error::StakeNotFound)?;
stake.auto_compound = auto_compound;
self.stakes.insert(caller, &stake);
self.env().emit_event(AutoCompoundUpdated {
staker: caller,
auto_compound,
});
Ok(())
}
/// Returns the staking tier for a staker.
#[ink(message)]
pub fn get_staker_tier(&self, staker: AccountId) -> StakingTier {
if let Some(stake) = self.stakes.get(staker) {
self.get_tier_internal(stake.amount)
} else {
StakingTier::Bronze
}
}
/// Delegate governance power to another address.
#[ink(message)]
pub fn delegate_governance(&mut self, delegate: AccountId) -> Result<(), Error> {
let caller = self.env().caller();
let mut stake = self.stakes.get(caller).ok_or(Error::StakeNotFound)?;
if delegate == caller {
return Err(Error::InvalidDelegate);
}
// Remove old delegation
self.remove_governance_power(&stake);
// Set new delegate
stake.governance_delegate = Some(delegate);
self.stakes.insert(caller, &stake);
// Grant power to delegate
let delegate_power = self.governance_power.get(delegate).unwrap_or(0);
self.governance_power
.insert(delegate, &delegate_power.saturating_add(stake.amount));
self.env().emit_event(GovernanceDelegated {
staker: caller,
delegate,
});
Ok(())
}
/// Fund the reward pool. Only admin may call.
#[ink(message)]
pub fn fund_reward_pool(&mut self, amount: u128) -> Result<(), Error> {
self.ensure_admin()?;
if amount == 0 {
return Err(Error::ZeroAmount);
}
self.reward_pool = self.reward_pool.saturating_add(amount);
self.env().emit_event(RewardPoolFunded {
funder: self.env().caller(),
amount,
});
Ok(())
}
/// Update staking configuration. Only admin may call.
#[ink(message)]
pub fn update_config(
&mut self,
min_stake: u128,
reward_rate_bps: u128,
) -> Result<(), Error> {
self.ensure_admin()?;
if min_stake == 0 {
return Err(Error::InvalidConfig);
}
self.min_stake = min_stake;
self.reward_rate_bps = reward_rate_bps;
self.env().emit_event(StakingConfigUpdated {
min_stake,
reward_rate_bps,
});
Ok(())
}
// ----- Parameter governance -----
/// Returns the current voting period (in blocks) and quorum (in bps).
#[ink(message)]
pub fn get_voting_config(&self) -> (u64, u32) {
(self.voting_period_blocks, self.quorum_bps)
}
/// Returns a parameter proposal by id, if any.
#[ink(message)]
pub fn get_param_proposal(&self, proposal_id: u64) -> Option<ParamProposal> {
self.param_proposals.get(proposal_id)
}
/// Total number of parameter proposals ever created.
#[ink(message)]
pub fn get_proposal_count(&self) -> u64 {
self.proposal_counter
}
/// Whether `voter` has already voted on `proposal_id`.
#[ink(message)]
pub fn has_voted(&self, proposal_id: u64, voter: AccountId) -> bool {
self.param_votes.contains((proposal_id, voter))
}
/// Propose a change to a staking parameter. Caller must hold governance
/// power (i.e. be a staker or hold delegated power).
#[ink(message)]
pub fn propose_param_change(&mut self, kind: ParamKind) -> Result<u64, Error> {
let caller = self.env().caller();
if self.governance_power.get(caller).unwrap_or(0) == 0 {
return Err(Error::NoVotingPower);
}
if self.active_proposal_count >= MAX_ACTIVE_PARAM_PROPOSALS {
return Err(Error::TooManyProposals);
}
Self::validate_param(&kind)?;
let now = self.env().block_number() as u64;
let proposal_id = self.proposal_counter;
self.proposal_counter = self.proposal_counter.saturating_add(1);
let proposal = ParamProposal {
id: proposal_id,
proposer: caller,
kind,
votes_for: 0,
votes_against: 0,
voting_end: now.saturating_add(self.voting_period_blocks),
total_power_snapshot: self.total_staked,
status: ProposalStatus::Active,
created_at: now,
};
self.param_proposals.insert(proposal_id, &proposal);
self.active_proposal_count = self.active_proposal_count.saturating_add(1);
self.env().emit_event(ParamProposalCreated {
proposal_id,
proposer: caller,
kind,
voting_end: proposal.voting_end,
});
Ok(proposal_id)
}
/// Cast a vote on an active parameter proposal, weighted by the
/// caller's current governance power.
#[ink(message)]
pub fn vote_on_proposal(&mut self, proposal_id: u64, support: bool) -> Result<(), Error> {
let caller = self.env().caller();
let weight = self.governance_power.get(caller).unwrap_or(0);
if weight == 0 {
return Err(Error::NoVotingPower);
}
let mut proposal = self