-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
proposal.rs
2545 lines (2119 loc) · 89.9 KB
/
proposal.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
//! Proposal Account
use borsh::maybestd::io::Write;
use solana_program::account_info::next_account_info;
use std::cmp::Ordering;
use std::slice::Iter;
use solana_program::borsh::try_from_slice_unchecked;
use solana_program::clock::{Slot, UnixTimestamp};
use solana_program::{
account_info::AccountInfo, program_error::ProgramError, program_pack::IsInitialized,
pubkey::Pubkey,
};
use spl_governance_tools::account::{get_account_data, AccountMaxSize};
use crate::addins::max_voter_weight::{
assert_is_valid_max_voter_weight,
get_max_voter_weight_record_data_for_realm_and_governing_token_mint,
};
use crate::state::legacy::ProposalV1;
use crate::tools::spl_token::get_spl_token_mint_supply;
use crate::{
error::GovernanceError,
state::{
enums::{
GovernanceAccountType, InstructionExecutionFlags, MintMaxVoterWeightSource,
ProposalState, TransactionExecutionStatus, VoteThreshold, VoteTipping,
},
governance::GovernanceConfig,
proposal_transaction::ProposalTransactionV2,
realm::RealmV2,
vote_record::Vote,
vote_record::VoteKind,
},
PROGRAM_AUTHORITY_SEED,
};
use borsh::{BorshDeserialize, BorshSchema, BorshSerialize};
use crate::state::realm_config::RealmConfigAccount;
/// Proposal option vote result
#[derive(Clone, Debug, PartialEq, Eq, BorshDeserialize, BorshSerialize, BorshSchema)]
pub enum OptionVoteResult {
/// Vote on the option is not resolved yet
None,
/// Vote on the option is completed and the option passed
Succeeded,
/// Vote on the option is completed and the option was defeated
Defeated,
}
/// Proposal Option
#[derive(Clone, Debug, PartialEq, Eq, BorshDeserialize, BorshSerialize, BorshSchema)]
pub struct ProposalOption {
/// Option label
pub label: String,
/// Vote weight for the option
pub vote_weight: u64,
/// Vote result for the option
pub vote_result: OptionVoteResult,
/// The number of the transactions already executed
pub transactions_executed_count: u16,
/// The number of transactions included in the option
pub transactions_count: u16,
/// The index of the the next transaction to be added
pub transactions_next_index: u16,
}
/// Proposal vote type
#[derive(Clone, Debug, PartialEq, Eq, BorshDeserialize, BorshSerialize, BorshSchema)]
pub enum VoteType {
/// Single choice vote with mutually exclusive choices
/// In the SingeChoice mode there can ever be a single winner
/// If multiple options score the same highest vote then the Proposal is not resolved and considered as Failed
/// Note: Yes/No vote is a single choice (Yes) vote with the deny option (No)
SingleChoice,
/// Multiple options can be selected with up to max_voter_options per voter
/// and with up to max_winning_options of successful options
/// Ex. voters are given 5 options, can choose up to 3 (max_voter_options)
/// and only 1 (max_winning_options) option can win and be executed
MultiChoice {
/// The max number of options a voter can choose
/// By default it equals to the number of available options
/// Note: In the current version the limit is not supported and not enforced yet
#[allow(dead_code)]
max_voter_options: u8,
/// The max number of wining options
/// For executable proposals it limits how many options can be executed for a Proposal
/// By default it equals to the number of available options
/// Note: In the current version the limit is not supported and not enforced yet
#[allow(dead_code)]
max_winning_options: u8,
},
}
/// Governance Proposal
#[derive(Clone, Debug, PartialEq, Eq, BorshDeserialize, BorshSerialize, BorshSchema)]
pub struct ProposalV2 {
/// Governance account type
pub account_type: GovernanceAccountType,
/// Governance account the Proposal belongs to
pub governance: Pubkey,
/// Indicates which Governing Token is used to vote on the Proposal
/// Whether the general Community token owners or the Council tokens owners vote on this Proposal
pub governing_token_mint: Pubkey,
/// Current proposal state
pub state: ProposalState,
// TODO: add state_at timestamp to have single field to filter recent proposals in the UI
/// The TokenOwnerRecord representing the user who created and owns this Proposal
pub token_owner_record: Pubkey,
/// The number of signatories assigned to the Proposal
pub signatories_count: u8,
/// The number of signatories who already signed
pub signatories_signed_off_count: u8,
/// Vote type
pub vote_type: VoteType,
/// Proposal options
pub options: Vec<ProposalOption>,
/// The total weight of the Proposal rejection votes
/// If the proposal has no deny option then the weight is None
/// Only proposals with the deny option can have executable instructions attached to them
/// Without the deny option a proposal is only non executable survey
pub deny_vote_weight: Option<u64>,
/// Reserved space for future versions
/// This field is a leftover from unused veto_vote_weight: Option<u64>
pub reserved1: u8,
/// The total weight of votes
/// Note: Abstain is not supported in the current version
pub abstain_vote_weight: Option<u64>,
/// Optional start time if the Proposal should not enter voting state immediately after being signed off
/// Note: start_at is not supported in the current version
pub start_voting_at: Option<UnixTimestamp>,
/// When the Proposal was created and entered Draft state
pub draft_at: UnixTimestamp,
/// When Signatories started signing off the Proposal
pub signing_off_at: Option<UnixTimestamp>,
/// When the Proposal began voting as UnixTimestamp
pub voting_at: Option<UnixTimestamp>,
/// When the Proposal began voting as Slot
/// Note: The slot is not currently used but the exact slot is going to be required to support snapshot based vote weights
pub voting_at_slot: Option<Slot>,
/// When the Proposal ended voting and entered either Succeeded or Defeated
pub voting_completed_at: Option<UnixTimestamp>,
/// When the Proposal entered Executing state
pub executing_at: Option<UnixTimestamp>,
/// When the Proposal entered final state Completed or Cancelled and was closed
pub closed_at: Option<UnixTimestamp>,
/// Instruction execution flag for ordered and transactional instructions
/// Note: This field is not used in the current version
pub execution_flags: InstructionExecutionFlags,
/// The max vote weight for the Governing Token mint at the time Proposal was decided
/// It's used to show correct vote results for historical proposals in cases when the mint supply or max weight source changed
/// after vote was completed.
pub max_vote_weight: Option<u64>,
/// Max voting time for the proposal if different from parent Governance (only higher value possible)
/// Note: This field is not used in the current version
pub max_voting_time: Option<u32>,
/// The vote threshold at the time Proposal was decided
/// It's used to show correct vote results for historical proposals in cases when the threshold
/// was changed for governance config after vote was completed.
/// TODO: Use this field to override the threshold from parent Governance (only higher value possible)
pub vote_threshold: Option<VoteThreshold>,
/// Reserved space for future versions
pub reserved: [u8; 64],
/// Proposal name
pub name: String,
/// Link to proposal's description
pub description_link: String,
/// The total weight of Veto votes
pub veto_vote_weight: u64,
}
impl AccountMaxSize for ProposalV2 {
fn get_max_size(&self) -> Option<usize> {
let options_size: usize = self.options.iter().map(|o| o.label.len() + 19).sum();
Some(self.name.len() + self.description_link.len() + options_size + 295)
}
}
impl IsInitialized for ProposalV2 {
fn is_initialized(&self) -> bool {
self.account_type == GovernanceAccountType::ProposalV2
}
}
impl ProposalV2 {
/// Checks if Signatories can be edited (added or removed) for the Proposal in the given state
pub fn assert_can_edit_signatories(&self) -> Result<(), ProgramError> {
self.assert_is_draft_state()
.map_err(|_| GovernanceError::InvalidStateCannotEditSignatories.into())
}
/// Checks if Proposal can be singed off
pub fn assert_can_sign_off(&self) -> Result<(), ProgramError> {
match self.state {
ProposalState::Draft | ProposalState::SigningOff => Ok(()),
ProposalState::Executing
| ProposalState::ExecutingWithErrors
| ProposalState::Completed
| ProposalState::Cancelled
| ProposalState::Voting
| ProposalState::Succeeded
| ProposalState::Defeated
| ProposalState::Vetoed => Err(GovernanceError::InvalidStateCannotSignOff.into()),
}
}
/// Checks the Proposal is in Voting state
fn assert_is_voting_state(&self) -> Result<(), ProgramError> {
if self.state != ProposalState::Voting {
return Err(GovernanceError::InvalidProposalState.into());
}
Ok(())
}
/// Checks the Proposal is in Draft state
fn assert_is_draft_state(&self) -> Result<(), ProgramError> {
if self.state != ProposalState::Draft {
return Err(GovernanceError::InvalidProposalState.into());
}
Ok(())
}
/// Checks if Proposal can be voted on
pub fn assert_can_cast_vote(
&self,
config: &GovernanceConfig,
current_unix_timestamp: UnixTimestamp,
) -> Result<(), ProgramError> {
self.assert_is_voting_state()
.map_err(|_| GovernanceError::InvalidStateCannotVote)?;
// Check if we are still within the configured max_voting_time period
if self.has_vote_time_ended(config, current_unix_timestamp) {
return Err(GovernanceError::ProposalVotingTimeExpired.into());
}
Ok(())
}
/// Vote end time determined by the configured max_voting_time period
pub fn vote_end_time(&self, config: &GovernanceConfig) -> UnixTimestamp {
self.voting_at
.unwrap()
.checked_add(config.max_voting_time as i64)
.unwrap()
}
/// Checks whether the voting time has ended for the proposal
pub fn has_vote_time_ended(
&self,
config: &GovernanceConfig,
current_unix_timestamp: UnixTimestamp,
) -> bool {
// Check if we passed vote_end_time
self.vote_end_time(config) < current_unix_timestamp
}
/// Checks if Proposal can be finalized
pub fn assert_can_finalize_vote(
&self,
config: &GovernanceConfig,
current_unix_timestamp: UnixTimestamp,
) -> Result<(), ProgramError> {
self.assert_is_voting_state()
.map_err(|_| GovernanceError::InvalidStateCannotFinalize)?;
// We can only finalize the vote after the configured max_voting_time has expired and vote time ended
if !self.has_vote_time_ended(config, current_unix_timestamp) {
return Err(GovernanceError::CannotFinalizeVotingInProgress.into());
}
Ok(())
}
/// Finalizes vote by moving it to final state Succeeded or Defeated if max_voting_time has passed
/// If Proposal is still within max_voting_time period then error is returned
pub fn finalize_vote(
&mut self,
max_voter_weight: u64,
config: &GovernanceConfig,
current_unix_timestamp: UnixTimestamp,
vote_threshold: &VoteThreshold,
) -> Result<(), ProgramError> {
self.assert_can_finalize_vote(config, current_unix_timestamp)?;
self.state = self.resolve_final_vote_state(max_voter_weight, vote_threshold)?;
self.voting_completed_at = Some(self.vote_end_time(config));
// Capture vote params to correctly display historical results
self.max_vote_weight = Some(max_voter_weight);
self.vote_threshold = Some(vote_threshold.clone());
Ok(())
}
/// Resolves final proposal state after vote ends
/// It inspects all proposals options and resolves their final vote results
fn resolve_final_vote_state(
&mut self,
max_vote_weight: u64,
vote_threshold: &VoteThreshold,
) -> Result<ProposalState, ProgramError> {
// Get the min vote weight required for options to pass
let min_vote_threshold_weight =
get_min_vote_threshold_weight(vote_threshold, max_vote_weight).unwrap();
// If the proposal has a reject option then any other option must beat it regardless of the configured min_vote_threshold_weight
let deny_vote_weight = self.deny_vote_weight.unwrap_or(0);
let mut best_succeeded_option_weight = 0;
let mut best_succeeded_option_count = 0u16;
for option in self.options.iter_mut() {
// Any positive vote (Yes) must be equal or above the required min_vote_threshold_weight and higher than the reject option vote (No)
// The same number of positive (Yes) and rejecting (No) votes is a tie and resolved as Defeated
// In other words +1 vote as a tie breaker is required to succeed for the positive option vote
if option.vote_weight >= min_vote_threshold_weight
&& option.vote_weight > deny_vote_weight
{
option.vote_result = OptionVoteResult::Succeeded;
match option.vote_weight.cmp(&best_succeeded_option_weight) {
Ordering::Greater => {
best_succeeded_option_weight = option.vote_weight;
best_succeeded_option_count = 1;
}
Ordering::Equal => {
best_succeeded_option_count =
best_succeeded_option_count.checked_add(1).unwrap()
}
Ordering::Less => {}
}
} else {
option.vote_result = OptionVoteResult::Defeated;
}
}
let mut final_state = if best_succeeded_option_count == 0 {
// If none of the individual options succeeded then the proposal as a whole is defeated
ProposalState::Defeated
} else {
match self.vote_type {
VoteType::SingleChoice => {
let proposal_state = if best_succeeded_option_count > 1 {
// If there is more than one winning option then the single choice proposal is considered as defeated
best_succeeded_option_weight = u64::MAX; // no winning option
ProposalState::Defeated
} else {
ProposalState::Succeeded
};
// Coerce options vote results based on the winning score (best_succeeded_vote_weight)
for option in self.options.iter_mut() {
option.vote_result = if option.vote_weight == best_succeeded_option_weight {
OptionVoteResult::Succeeded
} else {
OptionVoteResult::Defeated
};
}
proposal_state
}
VoteType::MultiChoice {
max_voter_options: _n,
max_winning_options: _m,
} => {
// If any option succeeded for multi choice then the proposal as a whole succeeded as well
ProposalState::Succeeded
}
}
};
// None executable proposal is just a survey and is considered Completed once the vote ends and no more actions are available
// There is no overall Success or Failure status for the Proposal however individual options still have their own status
if self.deny_vote_weight.is_none() {
final_state = ProposalState::Completed;
}
Ok(final_state)
}
/// Calculates max voter weight for given mint supply and realm config
fn get_max_voter_weight_from_mint_supply(
&mut self,
realm_data: &RealmV2,
governing_token_mint: &Pubkey,
governing_token_mint_supply: u64,
vote_kind: &VoteKind,
) -> Result<u64, ProgramError> {
// max vote weight fraction is only used for community mint
if Some(*governing_token_mint) == realm_data.config.council_mint {
return Ok(governing_token_mint_supply);
}
let max_voter_weight = match realm_data.config.community_mint_max_voter_weight_source {
MintMaxVoterWeightSource::SupplyFraction(fraction) => {
if fraction == MintMaxVoterWeightSource::SUPPLY_FRACTION_BASE {
return Ok(governing_token_mint_supply);
}
(governing_token_mint_supply as u128)
.checked_mul(fraction as u128)
.unwrap()
.checked_div(MintMaxVoterWeightSource::SUPPLY_FRACTION_BASE as u128)
.unwrap() as u64
}
MintMaxVoterWeightSource::Absolute(value) => value,
};
// When the fraction or absolute value is used it's possible we can go over the calculated max_vote_weight
// and we have to adjust it in case more votes have been cast
Ok(self.coerce_max_voter_weight(max_voter_weight, vote_kind))
}
/// Adjusts max voter weight to ensure it's not lower than total cast votes
fn coerce_max_voter_weight(&self, max_voter_weight: u64, vote_kind: &VoteKind) -> u64 {
let total_vote_weight = match vote_kind {
VoteKind::Electorate => {
let deny_vote_weight = self.deny_vote_weight.unwrap_or(0);
let max_option_vote_weight =
self.options.iter().map(|o| o.vote_weight).max().unwrap();
max_option_vote_weight
.checked_add(deny_vote_weight)
.unwrap()
}
VoteKind::Veto => self.veto_vote_weight,
};
max_voter_weight.max(total_vote_weight)
}
/// Resolves max voter weight using either 1) voting governing_token_mint supply or 2) max voter weight if configured for the token mint
#[allow(clippy::too_many_arguments)]
pub fn resolve_max_voter_weight(
&mut self,
account_info_iter: &mut Iter<AccountInfo>,
realm: &Pubkey,
realm_data: &RealmV2,
realm_config_data: &RealmConfigAccount,
vote_governing_token_mint_info: &AccountInfo,
vote_kind: &VoteKind,
) -> Result<u64, ProgramError> {
// if the Realm is configured to use max voter weight for the given voting governing_token_mint then use the externally provided max_voter_weight
// instead of the supply based max
if let Some(max_voter_weight_addin) = realm_config_data
.get_token_config(realm_data, vote_governing_token_mint_info.key)?
.max_voter_weight_addin
{
let max_voter_weight_record_info = next_account_info(account_info_iter)?;
let max_voter_weight_record_data =
get_max_voter_weight_record_data_for_realm_and_governing_token_mint(
&max_voter_weight_addin,
max_voter_weight_record_info,
realm,
vote_governing_token_mint_info.key,
)?;
assert_is_valid_max_voter_weight(&max_voter_weight_record_data)?;
// When the max voter weight addin is used it's possible it can be inaccurate and we can have more votes then the max provided by the addin
// and we have to adjust it to whatever result is higher
return Ok(self.coerce_max_voter_weight(
max_voter_weight_record_data.max_voter_weight,
vote_kind,
));
}
let vote_governing_token_mint_supply =
get_spl_token_mint_supply(vote_governing_token_mint_info)?;
let max_voter_weight = self.get_max_voter_weight_from_mint_supply(
realm_data,
vote_governing_token_mint_info.key,
vote_governing_token_mint_supply,
vote_kind,
)?;
Ok(max_voter_weight)
}
/// Checks if vote can be tipped and automatically transitioned to Succeeded or Defeated state
/// If the conditions are met the state is updated accordingly
pub fn try_tip_vote(
&mut self,
max_voter_weight: u64,
vote_tipping: &VoteTipping,
current_unix_timestamp: UnixTimestamp,
vote_threshold: &VoteThreshold,
vote_kind: &VoteKind,
) -> Result<bool, ProgramError> {
if let Some(tipped_state) = self.try_get_tipped_vote_state(
max_voter_weight,
vote_tipping,
vote_threshold,
vote_kind,
) {
self.state = tipped_state;
self.voting_completed_at = Some(current_unix_timestamp);
// Capture vote params to correctly display historical results
// Note: For Veto vote the captured params are from the Veto config
self.max_vote_weight = Some(max_voter_weight);
self.vote_threshold = Some(vote_threshold.clone());
Ok(true)
} else {
Ok(false)
}
}
/// Checks if vote can be tipped and automatically transitioned to Succeeded, Defeated or Vetoed state
/// If yes then Some(ProposalState) is returned and None otherwise
pub fn try_get_tipped_vote_state(
&mut self,
max_voter_weight: u64,
vote_tipping: &VoteTipping,
vote_threshold: &VoteThreshold,
vote_kind: &VoteKind,
) -> Option<ProposalState> {
let min_vote_threshold_weight =
get_min_vote_threshold_weight(vote_threshold, max_voter_weight).unwrap();
match vote_kind {
VoteKind::Electorate => self.try_get_tipped_electorate_vote_state(
max_voter_weight,
vote_tipping,
min_vote_threshold_weight,
),
VoteKind::Veto => self.try_get_tipped_veto_vote_state(min_vote_threshold_weight),
}
}
/// Checks if Electorate vote can be tipped and automatically transitioned to Succeeded or Defeated state
/// If yes then Some(ProposalState) is returned and None otherwise
fn try_get_tipped_electorate_vote_state(
&mut self,
max_voter_weight: u64,
vote_tipping: &VoteTipping,
min_vote_threshold_weight: u64,
) -> Option<ProposalState> {
// Vote tipping is currently supported for SingleChoice votes with single Yes and No (rejection) options only
// Note: Tipping for multiple options (single choice and multiple choices) should be possible but it requires a great deal of considerations
// and I decided to fight it another day
if self.vote_type != VoteType::SingleChoice
// Tipping should not be allowed for opinion only proposals (surveys without rejection) to allow everybody's voice to be heard
|| self.deny_vote_weight.is_none()
|| self.options.len() != 1
{
return None;
};
let mut yes_option = &mut self.options[0];
let yes_vote_weight = yes_option.vote_weight;
let deny_vote_weight = self.deny_vote_weight.unwrap();
match vote_tipping {
VoteTipping::Disabled => {}
VoteTipping::Strict => {
if yes_vote_weight >= min_vote_threshold_weight
&& yes_vote_weight > (max_voter_weight.saturating_sub(yes_vote_weight))
{
yes_option.vote_result = OptionVoteResult::Succeeded;
return Some(ProposalState::Succeeded);
}
}
VoteTipping::Early => {
if yes_vote_weight >= min_vote_threshold_weight
&& yes_vote_weight > deny_vote_weight
{
yes_option.vote_result = OptionVoteResult::Succeeded;
return Some(ProposalState::Succeeded);
}
}
}
// If vote tipping isn't disabled entirely, allow a vote to complete as
// "defeated" if there is no possible way of reaching majority or the
// min_vote_threshold_weight for another option. This tipping is always
// strict, there's no equivalent to "early" tipping for deny votes.
if *vote_tipping != VoteTipping::Disabled
&& (deny_vote_weight > (max_voter_weight.saturating_sub(min_vote_threshold_weight))
|| deny_vote_weight >= (max_voter_weight.saturating_sub(deny_vote_weight)))
{
yes_option.vote_result = OptionVoteResult::Defeated;
return Some(ProposalState::Defeated);
}
None
}
/// Checks if vote can be tipped and transitioned to Vetoed state
/// If yes then Some(ProposalState::Vetoed) is returned and None otherwise
fn try_get_tipped_veto_vote_state(
&mut self,
min_vote_threshold_weight: u64,
) -> Option<ProposalState> {
// Veto vote tips as soon as the required threshold is reached
// It's irrespectively of vote_tipping config because the outcome of the Proposal can't change any longer after being vetoed
if self.veto_vote_weight >= min_vote_threshold_weight {
// Note: Since we don't tip multi option votes all options vote_result would remain as None
Some(ProposalState::Vetoed)
} else {
None
}
}
/// Checks if Proposal can be canceled in the given state
pub fn assert_can_cancel(
&self,
config: &GovernanceConfig,
current_unix_timestamp: UnixTimestamp,
) -> Result<(), ProgramError> {
match self.state {
ProposalState::Draft | ProposalState::SigningOff => Ok(()),
ProposalState::Voting => {
// Note: If there is no tipping point the proposal can be still in Voting state but already past the configured max_voting_time
// In that case we treat the proposal as finalized and it's no longer allowed to be canceled
if self.has_vote_time_ended(config, current_unix_timestamp) {
return Err(GovernanceError::ProposalVotingTimeExpired.into());
}
Ok(())
}
ProposalState::Executing
| ProposalState::ExecutingWithErrors
| ProposalState::Completed
| ProposalState::Cancelled
| ProposalState::Succeeded
| ProposalState::Defeated
| ProposalState::Vetoed => {
Err(GovernanceError::InvalidStateCannotCancelProposal.into())
}
}
}
/// Checks if Instructions can be edited (inserted or removed) for the Proposal in the given state
/// It also asserts whether the Proposal is executable (has the reject option)
pub fn assert_can_edit_instructions(&self) -> Result<(), ProgramError> {
if self.assert_is_draft_state().is_err() {
return Err(GovernanceError::InvalidStateCannotEditTransactions.into());
}
// For security purposes only proposals with the reject option can have executable instructions
if self.deny_vote_weight.is_none() {
return Err(GovernanceError::ProposalIsNotExecutable.into());
}
Ok(())
}
/// Checks if Instructions can be executed for the Proposal in the given state
pub fn assert_can_execute_transaction(
&self,
proposal_transaction_data: &ProposalTransactionV2,
current_unix_timestamp: UnixTimestamp,
) -> Result<(), ProgramError> {
match self.state {
ProposalState::Succeeded
| ProposalState::Executing
| ProposalState::ExecutingWithErrors => {}
ProposalState::Draft
| ProposalState::SigningOff
| ProposalState::Completed
| ProposalState::Voting
| ProposalState::Cancelled
| ProposalState::Defeated
| ProposalState::Vetoed => {
return Err(GovernanceError::InvalidStateCannotExecuteTransaction.into())
}
}
if self.options[proposal_transaction_data.option_index as usize].vote_result
!= OptionVoteResult::Succeeded
{
return Err(GovernanceError::CannotExecuteDefeatedOption.into());
}
if self
.voting_completed_at
.unwrap()
.checked_add(proposal_transaction_data.hold_up_time as i64)
.unwrap()
>= current_unix_timestamp
{
return Err(GovernanceError::CannotExecuteTransactionWithinHoldUpTime.into());
}
if proposal_transaction_data.executed_at.is_some() {
return Err(GovernanceError::TransactionAlreadyExecuted.into());
}
Ok(())
}
/// Checks if the instruction can be flagged with error for the Proposal in the given state
pub fn assert_can_flag_transaction_error(
&self,
proposal_transaction_data: &ProposalTransactionV2,
current_unix_timestamp: UnixTimestamp,
) -> Result<(), ProgramError> {
// Instruction can be flagged for error only when it's eligible for execution
self.assert_can_execute_transaction(proposal_transaction_data, current_unix_timestamp)?;
if proposal_transaction_data.execution_status == TransactionExecutionStatus::Error {
return Err(GovernanceError::TransactionAlreadyFlaggedWithError.into());
}
Ok(())
}
/// Asserts the given vote is valid for the proposal
pub fn assert_valid_vote(&self, vote: &Vote) -> Result<(), ProgramError> {
match vote {
Vote::Approve(choices) => {
if self.options.len() != choices.len() {
return Err(GovernanceError::InvalidVote.into());
}
let mut choice_count = 0u16;
for choice in choices {
if choice.rank > 0 {
return Err(GovernanceError::InvalidVote.into());
}
if choice.weight_percentage == 100 {
choice_count = choice_count.checked_add(1).unwrap();
} else if choice.weight_percentage != 0 {
return Err(GovernanceError::InvalidVote.into());
}
}
match self.vote_type {
VoteType::SingleChoice => {
if choice_count != 1 {
return Err(GovernanceError::InvalidVote.into());
}
}
VoteType::MultiChoice {
max_voter_options: _n,
max_winning_options: _m,
} => {
if choice_count == 0 {
return Err(GovernanceError::InvalidVote.into());
}
}
}
}
Vote::Deny => {
if self.deny_vote_weight.is_none() {
return Err(GovernanceError::InvalidVote.into());
}
}
Vote::Abstain => {
return Err(GovernanceError::NotSupportedVoteType.into());
}
Vote::Veto => {}
}
Ok(())
}
/// Serializes account into the target buffer
pub fn serialize<W: Write>(self, writer: &mut W) -> Result<(), ProgramError> {
if self.account_type == GovernanceAccountType::ProposalV2 {
BorshSerialize::serialize(&self, writer)?
} else if self.account_type == GovernanceAccountType::ProposalV1 {
// V1 account can't be resized and we have to translate it back to the original format
if self.abstain_vote_weight.is_some() {
panic!("ProposalV1 doesn't support Abstain vote")
}
if self.veto_vote_weight > 0 {
panic!("ProposalV1 doesn't support Veto vote")
}
if self.start_voting_at.is_some() {
panic!("ProposalV1 doesn't support start time")
}
if self.max_voting_time.is_some() {
panic!("ProposalV1 doesn't support max voting time")
}
if self.options.len() != 1 {
panic!("ProposalV1 doesn't support multiple options")
}
let proposal_data_v1 = ProposalV1 {
account_type: self.account_type,
governance: self.governance,
governing_token_mint: self.governing_token_mint,
state: self.state,
token_owner_record: self.token_owner_record,
signatories_count: self.signatories_count,
signatories_signed_off_count: self.signatories_signed_off_count,
yes_votes_count: self.options[0].vote_weight,
no_votes_count: self.deny_vote_weight.unwrap(),
instructions_executed_count: self.options[0].transactions_executed_count,
instructions_count: self.options[0].transactions_count,
instructions_next_index: self.options[0].transactions_next_index,
draft_at: self.draft_at,
signing_off_at: self.signing_off_at,
voting_at: self.voting_at,
voting_at_slot: self.voting_at_slot,
voting_completed_at: self.voting_completed_at,
executing_at: self.executing_at,
closed_at: self.closed_at,
execution_flags: self.execution_flags,
max_vote_weight: self.max_vote_weight,
vote_threshold: self.vote_threshold,
name: self.name,
description_link: self.description_link,
};
BorshSerialize::serialize(&proposal_data_v1, writer)?;
}
Ok(())
}
}
/// Converts given vote threshold (ex. in percentages) to absolute vote weight
/// and returns the min weight required for a proposal option to pass
fn get_min_vote_threshold_weight(
vote_threshold: &VoteThreshold,
max_voter_weight: u64,
) -> Result<u64, ProgramError> {
let yes_vote_threshold_percentage = match vote_threshold {
VoteThreshold::YesVotePercentage(yes_vote_threshold_percentage) => {
*yes_vote_threshold_percentage
}
_ => {
return Err(GovernanceError::VoteThresholdTypeNotSupported.into());
}
};
let numerator = (yes_vote_threshold_percentage as u128)
.checked_mul(max_voter_weight as u128)
.unwrap();
let mut yes_vote_threshold = numerator.checked_div(100).unwrap();
if yes_vote_threshold.checked_mul(100).unwrap() < numerator {
yes_vote_threshold = yes_vote_threshold.checked_add(1).unwrap();
}
Ok(yes_vote_threshold as u64)
}
/// Deserializes Proposal account and checks owner program
pub fn get_proposal_data(
program_id: &Pubkey,
proposal_info: &AccountInfo,
) -> Result<ProposalV2, ProgramError> {
let account_type: GovernanceAccountType =
try_from_slice_unchecked(&proposal_info.data.borrow())?;
// If the account is V1 version then translate to V2
if account_type == GovernanceAccountType::ProposalV1 {
let proposal_data_v1 = get_account_data::<ProposalV1>(program_id, proposal_info)?;
let vote_result = match proposal_data_v1.state {
ProposalState::Draft
| ProposalState::SigningOff
| ProposalState::Voting
| ProposalState::Cancelled => OptionVoteResult::None,
ProposalState::Succeeded
| ProposalState::Executing
| ProposalState::ExecutingWithErrors
| ProposalState::Completed => OptionVoteResult::Succeeded,
ProposalState::Vetoed | ProposalState::Defeated => OptionVoteResult::None,
};
return Ok(ProposalV2 {
account_type,
governance: proposal_data_v1.governance,
governing_token_mint: proposal_data_v1.governing_token_mint,
state: proposal_data_v1.state,
token_owner_record: proposal_data_v1.token_owner_record,
signatories_count: proposal_data_v1.signatories_count,
signatories_signed_off_count: proposal_data_v1.signatories_signed_off_count,
vote_type: VoteType::SingleChoice,
options: vec![ProposalOption {
label: "Yes".to_string(),
vote_weight: proposal_data_v1.yes_votes_count,
vote_result,
transactions_executed_count: proposal_data_v1.instructions_executed_count,
transactions_count: proposal_data_v1.instructions_count,
transactions_next_index: proposal_data_v1.instructions_next_index,
}],
deny_vote_weight: Some(proposal_data_v1.no_votes_count),
veto_vote_weight: 0,
abstain_vote_weight: None,
start_voting_at: None,
draft_at: proposal_data_v1.draft_at,
signing_off_at: proposal_data_v1.signing_off_at,
voting_at: proposal_data_v1.voting_at,
voting_at_slot: proposal_data_v1.voting_at_slot,
voting_completed_at: proposal_data_v1.voting_completed_at,
executing_at: proposal_data_v1.executing_at,
closed_at: proposal_data_v1.closed_at,
execution_flags: proposal_data_v1.execution_flags,
max_vote_weight: proposal_data_v1.max_vote_weight,
max_voting_time: None,
vote_threshold: proposal_data_v1.vote_threshold,
name: proposal_data_v1.name,
description_link: proposal_data_v1.description_link,
reserved: [0; 64],
reserved1: 0,
});
}
get_account_data::<ProposalV2>(program_id, proposal_info)
}
/// Deserializes Proposal and validates it belongs to the given Governance and governing_token_mint
pub fn get_proposal_data_for_governance_and_governing_mint(
program_id: &Pubkey,
proposal_info: &AccountInfo,
governance: &Pubkey,
governing_token_mint: &Pubkey,
) -> Result<ProposalV2, ProgramError> {
let proposal_data = get_proposal_data_for_governance(program_id, proposal_info, governance)?;
if proposal_data.governing_token_mint != *governing_token_mint {
return Err(GovernanceError::InvalidGoverningMintForProposal.into());
}
Ok(proposal_data)
}
/// Deserializes Proposal and validates it belongs to the given Governance
pub fn get_proposal_data_for_governance(
program_id: &Pubkey,
proposal_info: &AccountInfo,
governance: &Pubkey,
) -> Result<ProposalV2, ProgramError> {
let proposal_data = get_proposal_data(program_id, proposal_info)?;
if proposal_data.governance != *governance {
return Err(GovernanceError::InvalidGovernanceForProposal.into());
}
Ok(proposal_data)
}
/// Returns Proposal PDA seeds
pub fn get_proposal_address_seeds<'a>(
governance: &'a Pubkey,
governing_token_mint: &'a Pubkey,
proposal_index_le_bytes: &'a [u8],
) -> [&'a [u8]; 4] {
[
PROGRAM_AUTHORITY_SEED,
governance.as_ref(),