stellar-governance 0.7.1

Governance Utilities for Stellar contracts.
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
//! # Governor Storage Module
//!
//! This module provides storage utilities for the Governor contract.
//! It defines storage keys and helper functions for managing proposal state,
//! votes, and configuration parameters.

use soroban_sdk::{
    contracttype, panic_with_error, xdr::ToXdr, Address, Bytes, BytesN, Env, String, Symbol, Val,
    Vec,
};

use crate::{
    governor::{
        emit_proposal_cancelled, emit_proposal_created, emit_proposal_executed,
        emit_proposal_queued, emit_quorum_changed, emit_vote_cast, GovernorError, ProposalState,
        GOVERNOR_EXTEND_AMOUNT, GOVERNOR_TTL_THRESHOLD, MAX_DESCRIPTION_LENGTH,
    },
    votes::VotesClient,
};

// ################## STORAGE KEYS ##################

/// Storage keys for the Governor contract.
#[derive(Clone)]
#[contracttype]
pub enum GovernorStorageKey {
    /// The name of the governor.
    Name,
    /// The version of the governor contract.
    Version,
    /// The voting delay in ledgers.
    VotingDelay,
    /// The voting period in ledgers.
    VotingPeriod,
    /// Minimum voting power required to propose.
    ProposalThreshold,
    /// Proposal data indexed by proposal ID.
    Proposal(BytesN<32>),
    /// Number of quorum checkpoints.
    NumQuorumCheckpoints,
    /// Individual quorum checkpoint at index.
    QuorumCheckpoint(u32),
    /// Vote tallies for a proposal, indexed by proposal ID.
    ProposalVote(BytesN<32>),
    /// Whether an account has voted on a proposal.
    HasVoted(BytesN<32>, Address),
    /// The address of the token contract that implements the Votes trait.
    TokenContract,
}

// ################## STORAGE TYPES ##################

/// Core proposal data stored on-chain.
#[derive(Clone)]
#[contracttype]
pub struct ProposalCore {
    /// The address that created the proposal.
    pub proposer: Address,
    /// The ledger at which voting power is snapshotted. Voting opens on
    /// the next ledger (`vote_snapshot + 1`).
    pub vote_snapshot: u32,
    /// The last ledger where voting is active (inclusive).
    pub vote_end: u32,
    /// The current state of the proposal.
    pub state: ProposalState,
}

/// A quorum checkpoint recording the quorum value at a specific ledger.
#[derive(Clone)]
#[contracttype]
pub struct QuorumCheckpoint {
    /// The ledger at which this quorum value took effect.
    pub ledger: u32,
    /// The quorum value.
    pub quorum: u128,
}

/// Vote tallies for a proposal.
#[derive(Clone)]
#[contracttype]
pub struct ProposalVoteCounts {
    /// Total voting power cast against the proposal.
    pub against_votes: u128,
    /// Total voting power cast in favor of the proposal.
    pub for_votes: u128,
    /// Total voting power cast as abstain.
    pub abstain_votes: u128,
}

// ################## CONSTANTS ##################

/// Vote type: Against the proposal.
pub const VOTE_AGAINST: u32 = 0;

/// Vote type: In favor of the proposal.
pub const VOTE_FOR: u32 = 1;

/// Vote type: Abstain from voting for or against.
pub const VOTE_ABSTAIN: u32 = 2;

// ################## QUERY_STATE ##################

/// Returns the name of the governor.
///
/// # Arguments
///
/// * `e` - Access to the Soroban environment.
///
/// # Errors
///
/// * [`GovernorError::NameNotSet`] - Occurs if the name has not been set.
pub fn get_name(e: &Env) -> String {
    e.storage()
        .instance()
        .get(&GovernorStorageKey::Name)
        .unwrap_or_else(|| panic_with_error!(e, GovernorError::NameNotSet))
}

/// Returns the version of the governor contract.
///
/// # Arguments
///
/// * `e` - Access to the Soroban environment.
///
/// # Errors
///
/// * [`GovernorError::VersionNotSet`] - Occurs if the version has not been set.
pub fn get_version(e: &Env) -> String {
    e.storage()
        .instance()
        .get(&GovernorStorageKey::Version)
        .unwrap_or_else(|| panic_with_error!(e, GovernorError::VersionNotSet))
}

/// Returns the proposal threshold.
///
/// # Arguments
///
/// * `e` - Access to the Soroban environment.
///
/// # Errors
///
/// * [`GovernorError::ProposalThresholdNotSet`] - Occurs if the proposal
///   threshold has not been set.
pub fn get_proposal_threshold(e: &Env) -> u128 {
    e.storage()
        .instance()
        .get(&GovernorStorageKey::ProposalThreshold)
        .unwrap_or_else(|| panic_with_error!(e, GovernorError::ProposalThresholdNotSet))
}

/// Returns the voting delay in ledgers.
///
/// # Arguments
///
/// * `e` - Access to the Soroban environment.
///
/// # Errors
///
/// * [`GovernorError::VotingDelayNotSet`] - Occurs if the voting delay has not
///   been set.
pub fn get_voting_delay(e: &Env) -> u32 {
    e.storage()
        .instance()
        .get(&GovernorStorageKey::VotingDelay)
        .unwrap_or_else(|| panic_with_error!(e, GovernorError::VotingDelayNotSet))
}

/// Returns the voting period in ledgers.
///
/// # Arguments
///
/// * `e` - Access to the Soroban environment.
///
/// # Errors
///
/// * [`GovernorError::VotingPeriodNotSet`] - Occurs if the voting period has
///   not been set.
pub fn get_voting_period(e: &Env) -> u32 {
    e.storage()
        .instance()
        .get(&GovernorStorageKey::VotingPeriod)
        .unwrap_or_else(|| panic_with_error!(e, GovernorError::VotingPeriodNotSet))
}

/// Returns the core proposal data.
///
/// # Arguments
///
/// * `e` - Access to the Soroban environment.
/// * `proposal_id` - The unique identifier of the proposal.
///
/// # Errors
///
/// * [`GovernorError::ProposalNotFound`] - Occurs if the proposal does not
///   exist.
pub fn get_proposal_core(e: &Env, proposal_id: &BytesN<32>) -> ProposalCore {
    let key = GovernorStorageKey::Proposal(proposal_id.clone());
    let core: ProposalCore = e
        .storage()
        .persistent()
        .get(&key)
        .unwrap_or_else(|| panic_with_error!(e, GovernorError::ProposalNotFound));
    e.storage().persistent().extend_ttl(&key, GOVERNOR_TTL_THRESHOLD, GOVERNOR_EXTEND_AMOUNT);
    core
}

/// Returns the current state of a proposal.
///
/// See [`ProposalState`] for the full lifecycle flowchart.
///
/// # Arguments
///
/// * `e` - Access to the Soroban environment.
/// * `proposal_id` - The unique identifier of the proposal.
/// * `quorum` - The quorum threshold, evaluated at the proposal's
///   `vote_snapshot` ledger via [`Governor::quorum`].
///
/// # Errors
///
/// * [`GovernorError::ProposalNotFound`] - Occurs if the proposal does not
///   exist.
pub fn get_proposal_state(e: &Env, proposal_id: &BytesN<32>, quorum: u128) -> ProposalState {
    let core = get_proposal_core(e, proposal_id);
    derive_proposal_state(e, proposal_id, &core, quorum)
}

/// Returns the snapshot ledger for a proposal.
///
/// # Arguments
///
/// * `e` - Access to the Soroban environment.
/// * `proposal_id` - The unique identifier of the proposal.
///
/// # Errors
///
/// * [`GovernorError::ProposalNotFound`] - Occurs if the proposal does not
///   exist.
pub fn get_proposal_snapshot(e: &Env, proposal_id: &BytesN<32>) -> u32 {
    let core = get_proposal_core(e, proposal_id);
    core.vote_snapshot
}

/// Returns the deadline ledger for a proposal.
///
/// # Arguments
///
/// * `e` - Access to the Soroban environment.
/// * `proposal_id` - The unique identifier of the proposal.
///
/// # Errors
///
/// * [`GovernorError::ProposalNotFound`] - Occurs if the proposal does not
///   exist.
pub fn get_proposal_deadline(e: &Env, proposal_id: &BytesN<32>) -> u32 {
    let core = get_proposal_core(e, proposal_id);
    core.vote_end
}

/// Returns the proposer of a proposal.
///
/// # Arguments
///
/// * `e` - Access to the Soroban environment.
/// * `proposal_id` - The unique identifier of the proposal.
///
/// # Errors
///
/// * [`GovernorError::ProposalNotFound`] - Occurs if the proposal does not
///   exist.
pub fn get_proposal_proposer(e: &Env, proposal_id: &BytesN<32>) -> Address {
    let core = get_proposal_core(e, proposal_id);
    core.proposer
}

/// Returns the address of the token contract that implements the Votes trait.
///
/// # Arguments
///
/// * `e` - Access to the Soroban environment.
///
/// # Errors
///
/// * [`GovernorError::TokenContractNotSet`] - Occurs if the token contract has
///   not been set.
pub fn get_token_contract(e: &Env) -> Address {
    e.storage()
        .instance()
        .get(&GovernorStorageKey::TokenContract)
        .unwrap_or_else(|| panic_with_error!(e, GovernorError::TokenContractNotSet))
}

// ################## CHANGE STATE ##################

/// Sets the name of the governor.
///
/// The name is not validated here. It is the responsibility of the
/// implementer to ensure that the name is appropriate.
///
/// # Arguments
///
/// * `e` - Access to the Soroban environment.
/// * `name` - The name to set.
///
/// # Security Warning
///
/// ⚠️ SECURITY RISK: This function has NO AUTHORIZATION CONTROLS ⚠️
///
/// It is the responsibility of the implementer to establish appropriate
/// access controls to ensure that only authorized accounts can call this
/// function.
pub fn set_name(e: &Env, name: String) {
    e.storage().instance().set(&GovernorStorageKey::Name, &name);
}

/// Sets the version of the governor contract.
///
/// The version is not validated here. It is the responsibility of the
/// implementer to ensure that the version string is appropriate.
///
/// # Arguments
///
/// * `e` - Access to the Soroban environment.
/// * `version` - The version string to set.
///
/// # Security Warning
///
/// ⚠️ SECURITY RISK: This function has NO AUTHORIZATION CONTROLS ⚠️
///
/// It is the responsibility of the implementer to establish appropriate
/// access controls to ensure that only authorized accounts can call this
/// function.
pub fn set_version(e: &Env, version: String) {
    e.storage().instance().set(&GovernorStorageKey::Version, &version);
}

/// Sets the proposal threshold.
///
/// The threshold value is not validated here. It is the responsibility of
/// the implementer to ensure that the threshold is reasonable for the
/// governance use case (e.g., not so high that no one can propose).
///
/// # Arguments
///
/// * `e` - Access to the Soroban environment.
/// * `threshold` - The minimum voting power required to create a proposal.
///
/// # Security Warning
///
/// ⚠️ SECURITY RISK: This function has NO AUTHORIZATION CONTROLS ⚠️
///
/// It is the responsibility of the implementer to establish appropriate
/// access controls to ensure that only authorized accounts can call this
/// function.
pub fn set_proposal_threshold(e: &Env, threshold: u128) {
    e.storage().instance().set(&GovernorStorageKey::ProposalThreshold, &threshold);
}

/// Sets the voting delay.
///
/// The delay value is not validated here. It is the responsibility of
/// the implementer to ensure that the delay is appropriate (e.g., enough
/// time for token holders to prepare, but not so long that governance
/// becomes unresponsive).
///
/// # Arguments
///
/// * `e` - Access to the Soroban environment.
/// * `delay` - The voting delay in ledgers.
///
/// # Security Warning
///
/// ⚠️ SECURITY RISK: This function has NO AUTHORIZATION CONTROLS ⚠️
///
/// It is the responsibility of the implementer to establish appropriate
/// access controls to ensure that only authorized accounts can call this
/// function.
pub fn set_voting_delay(e: &Env, delay: u32) {
    e.storage().instance().set(&GovernorStorageKey::VotingDelay, &delay);
}

/// Sets the voting period.
///
/// The period value is not validated here. It is the responsibility of
/// the implementer to ensure that the period is appropriate (e.g., enough
/// time for voters to participate, but not so long that urgent actions
/// cannot be taken).
///
/// # Arguments
///
/// * `e` - Access to the Soroban environment.
/// * `period` - The voting period in ledgers.
///
/// # Security Warning
///
/// ⚠️ SECURITY RISK: This function has NO AUTHORIZATION CONTROLS ⚠️
///
/// It is the responsibility of the implementer to establish appropriate
/// access controls to ensure that only authorized accounts can call this
/// function.
pub fn set_voting_period(e: &Env, period: u32) {
    e.storage().instance().set(&GovernorStorageKey::VotingPeriod, &period);
}

/// Sets the address of the token contract that implements the Votes trait.
///
/// This function can only be called **once**. It is expected to be called
/// during the constructor of the governor contract. Subsequent calls will
/// fail with [`GovernorError::TokenContractAlreadySet`].
///
/// # Arguments
///
/// * `e` - Access to the Soroban environment.
/// * `token_contract` - The address of the token contract.
///
/// # Errors
///
/// * [`GovernorError::TokenContractAlreadySet`] - Occurs if the token contract
///   has already been set.
///
/// # Security Warning
///
/// ⚠️ SECURITY RISK: This function has NO AUTHORIZATION CONTROLS ⚠️
///
/// It is the responsibility of the implementer to establish appropriate
/// access controls to ensure that only authorized accounts can call this
/// function.
pub fn set_token_contract(e: &Env, token_contract: &Address) {
    let key = GovernorStorageKey::TokenContract;
    if e.storage().instance().has(&key) {
        panic_with_error!(e, GovernorError::TokenContractAlreadySet);
    }
    e.storage().instance().set(&key, token_contract);
}

/// Creates a new proposal and returns its unique identifier (proposal ID).
///
/// Fetches the proposer's voting power from the token contract at the
/// previous ledger (snapshot) to prevent flash-loan-based proposals.
///
/// # Arguments
///
/// * `e` - Access to the Soroban environment.
/// * `targets` - The addresses of contracts to call.
/// * `functions` - The function names to invoke on each target.
/// * `args` - The arguments for each function call.
/// * `description` - A description of the proposal.
/// * `proposer` - The address creating the proposal.
///
/// # Errors
///
/// * [`GovernorError::EmptyProposal`] - Occurs if the proposal contains no
///   actions.
/// * [`GovernorError::InvalidProposalLength`] - Occurs if targets, functions,
///   and args vectors have different lengths.
/// * [`GovernorError::ProposalAlreadyExists`] - Occurs if a proposal with the
///   same parameters already exists.
/// * [`GovernorError::InsufficientProposerVotes`] - Occurs if the proposer
///   lacks sufficient voting power.
/// * [`GovernorError::MathOverflow`] - Occurs if voting schedule calculation
///   overflows.
/// * refer to [`get_proposal_threshold()`] errors.
/// * refer to [`get_voting_delay()`] errors.
/// * refer to [`get_voting_period()`] errors.
/// * refer to [`get_token_contract()`] errors.
///
/// ⚠️ SECURITY RISK: This function has NO AUTHORIZATION CONTROLS ⚠️
///
/// It is the responsibility of the implementer to establish appropriate
/// access controls to ensure that only authorized accounts can call this
/// function.
pub fn propose(
    e: &Env,
    targets: Vec<Address>,
    functions: Vec<Symbol>,
    args: Vec<Vec<Val>>,
    description: String,
    proposer: &Address,
) -> BytesN<32> {
    // Validate proposal length
    let targets_len = targets.len();
    if targets_len == 0 {
        panic_with_error!(e, GovernorError::EmptyProposal);
    }
    if targets_len != functions.len() || targets_len != args.len() {
        panic_with_error!(e, GovernorError::InvalidProposalLength);
    }

    // Validate description length to prevent oversized events.
    if description.len() > MAX_DESCRIPTION_LENGTH {
        panic_with_error!(e, GovernorError::DescriptionTooLong);
    }

    // Use previous ledger to prevent flash loan based proposals
    let snapshot = e.ledger().sequence() - 1;
    let proposer_votes = get_voting_power(e, proposer, snapshot);

    // Check proposer has sufficient voting power
    let threshold = get_proposal_threshold(e);
    if proposer_votes < threshold {
        panic_with_error!(e, GovernorError::InsufficientProposerVotes);
    }

    let current_ledger = e.ledger().sequence();

    // Compute proposal ID
    let description_hash = e.crypto().keccak256(&description.to_bytes()).to_bytes();
    let proposal_id = hash_proposal(e, &targets, &functions, &args, &description_hash);

    // Check proposal doesn't already exist
    if e.storage().persistent().has(&GovernorStorageKey::Proposal(proposal_id.clone())) {
        panic_with_error!(e, GovernorError::ProposalAlreadyExists);
    }

    // Calculate voting schedule
    let voting_delay = get_voting_delay(e);
    let voting_period = get_voting_period(e);
    let Some(vote_snapshot) = current_ledger.checked_add(voting_delay) else {
        panic_with_error!(e, GovernorError::MathOverflow);
    };
    let Some(vote_end) = vote_snapshot.checked_add(voting_period) else {
        panic_with_error!(e, GovernorError::MathOverflow);
    };

    // Store proposal
    let proposal = ProposalCore {
        proposer: proposer.clone(),
        vote_snapshot,
        vote_end,
        state: ProposalState::Pending,
    };
    e.storage().persistent().set(&GovernorStorageKey::Proposal(proposal_id.clone()), &proposal);

    // Emit event
    emit_proposal_created(
        e,
        &proposal_id,
        proposer,
        &targets,
        &functions,
        &args,
        vote_snapshot,
        vote_end,
        &description,
    );

    proposal_id
}

/// Executes a successful proposal and returns its unique identifier (proposal
/// ID).
///
/// # Arguments
///
/// * `e` - Access to the Soroban environment.
/// * `targets` - The addresses of contracts to call.
/// * `functions` - The function names to invoke on each target.
/// * `args` - The arguments for each function call.
/// * `description_hash` - The hash of the proposal description.
/// * `queue_enabled` - Whether queueing is enabled (i.e., whether the proposal
///   must be in the `Queued` state to execute).
/// * `quorum` - The quorum threshold, evaluated at the proposal's
///   `vote_snapshot` ledger via [`Governor::quorum`].
///
/// # Errors
///
/// * [`GovernorError::ProposalNotSuccessful`] - Occurs if the proposal has not
///   succeeded.
/// * [`GovernorError::ProposalAlreadyExecuted`] - Occurs if the proposal has
///   already been executed.
/// * refer to [`get_proposal_core()`] errors.
///
/// ⚠️ SECURITY RISK: This function has NO AUTHORIZATION CONTROLS ⚠️
///
/// It is the responsibility of the implementer to establish appropriate
/// access controls to ensure that only authorized accounts can call this
/// function.
pub fn execute(
    e: &Env,
    targets: Vec<Address>,
    functions: Vec<Symbol>,
    args: Vec<Vec<Val>>,
    description_hash: &BytesN<32>,
    queue_enabled: bool,
    quorum: u128,
) -> BytesN<32> {
    let proposal_id = hash_proposal(e, &targets, &functions, &args, description_hash);

    // Get proposal and verify it exists
    let mut proposal = get_proposal_core(e, &proposal_id);

    // Check proposal state
    let state = derive_proposal_state(e, &proposal_id, &proposal, quorum);
    if state == ProposalState::Executed {
        panic_with_error!(e, GovernorError::ProposalAlreadyExecuted);
    }
    if queue_enabled {
        if state != ProposalState::Queued {
            panic_with_error!(e, GovernorError::ProposalNotQueued);
        }
    } else if state != ProposalState::Succeeded {
        panic_with_error!(e, GovernorError::ProposalNotSuccessful);
    }

    // Execute each action
    //
    // `propose()` ensures the proposals in the storage are in the
    // correct state, no further checks on the proposal integrity are needed.
    // It should be safe to use `get_unchecked` here.
    for i in 0..targets.len() {
        let target = targets.get_unchecked(i);
        let function = functions.get_unchecked(i);
        let func_args = args.get_unchecked(i);
        e.invoke_contract::<Val>(&target, &function, func_args);
    }

    // Mark as executed
    proposal.state = ProposalState::Executed;
    e.storage().persistent().set(&GovernorStorageKey::Proposal(proposal_id.clone()), &proposal);

    // Emit event
    emit_proposal_executed(e, &proposal_id);

    proposal_id
}

/// Queues a succeeded proposal for execution and returns its unique identifier
/// (proposal ID).
///
/// Transitions the proposal from [`ProposalState::Succeeded`] to
/// [`ProposalState::Queued`]. The `eta` (estimated time of arrival) is
/// emitted in the event for off-chain consumers but is **not enforced** by
/// this function or by [`execute`]. Enforcement of the execution delay is
/// the responsibility of the integration layer (e.g., a timelock contract).
/// The `eta` is typically computed by the caller as
/// `current_ledger + timelock_delay`.
///
/// # Arguments
///
/// * `e` - Access to the Soroban environment.
/// * `targets` - The addresses of contracts to call.
/// * `functions` - The function names to invoke on each target.
/// * `args` - The arguments for each function call.
/// * `description_hash` - The hash of the proposal description.
/// * `eta` - The estimated ledger sequence for execution. Emitted in the event
///   only; not stored or enforced by the governor.
/// * `quorum` - The quorum threshold, evaluated at the proposal's
///   `vote_snapshot` ledger via [`Governor::quorum`].
///
/// # Errors
///
/// * [`GovernorError::ProposalNotSuccessful`] - Occurs if the proposal is not
///   in the `Succeeded` state.
/// * refer to [`get_proposal_core()`] errors.
///
/// # Events
///
/// * topics - `["proposal_queued", proposal_id: BytesN<32>]`
/// * data - `[eta: u32]`
///
/// ⚠️ SECURITY RISK: This function has NO AUTHORIZATION CONTROLS ⚠️
///
/// It is the responsibility of the implementer to establish appropriate
/// access controls to ensure that only authorized accounts can call this
/// function.
pub fn queue(
    e: &Env,
    targets: Vec<Address>,
    functions: Vec<Symbol>,
    args: Vec<Vec<Val>>,
    description_hash: &BytesN<32>,
    eta: u32,
    quorum: u128,
) -> BytesN<32> {
    let proposal_id = hash_proposal(e, &targets, &functions, &args, description_hash);
    let mut proposal = get_proposal_core(e, &proposal_id);
    let state = derive_proposal_state(e, &proposal_id, &proposal, quorum);
    if state != ProposalState::Succeeded {
        panic_with_error!(e, GovernorError::ProposalNotSuccessful);
    }

    proposal.state = ProposalState::Queued;
    e.storage().persistent().set(&GovernorStorageKey::Proposal(proposal_id.clone()), &proposal);

    emit_proposal_queued(e, &proposal_id, eta);

    proposal_id
}

/// Cancels a proposal and returns its unique identifier (proposal ID).
///
/// # Arguments
///
/// * `e` - Access to the Soroban environment.
/// * `targets` - The addresses of contracts to call.
/// * `functions` - The function names to invoke on each target.
/// * `args` - The arguments for each function call.
/// * `description_hash` - The hash of the proposal description.
///
/// # Errors
///
/// * [`GovernorError::ProposalNotCancellable`] - Occurs if the proposal is in a
///   non-cancellable state (`Canceled`, `Expired`, or `Executed`).
/// * refer to [`get_proposal_core()`] errors.
///
/// ⚠️ SECURITY RISK: This function has NO AUTHORIZATION CONTROLS ⚠️
///
/// It is the responsibility of the implementer to establish appropriate
/// access controls to ensure that only authorized accounts can call this
/// function.
///
/// # Note
///
/// This function only updates the governor-level proposal state. If the
/// proposal has already been queued in an external timelock, the
/// corresponding timelock operation must be cancelled separately (e.g. via
/// [`crate::timelock::cancel_operation`])
/// to prevent it from remaining executable through the timelock directly.
pub fn cancel(
    e: &Env,
    targets: Vec<Address>,
    functions: Vec<Symbol>,
    args: Vec<Vec<Val>>,
    description_hash: &BytesN<32>,
) -> BytesN<32> {
    let proposal_id = hash_proposal(e, &targets, &functions, &args, description_hash);

    // Get proposal and verify it exists
    let mut proposal = get_proposal_core(e, &proposal_id);

    // Blacklist non-cancellable explicit states.
    // These are always stored directly in `core.state`, so no need to derive
    // the full proposal state (which would also require a vote-count read).
    match proposal.state {
        ProposalState::Canceled | ProposalState::Expired | ProposalState::Executed => {
            panic_with_error!(e, GovernorError::ProposalNotCancellable)
        }
        _ => {}
    }

    // Mark as cancelled
    proposal.state = ProposalState::Canceled;
    e.storage().persistent().set(&GovernorStorageKey::Proposal(proposal_id.clone()), &proposal);

    // Emit event
    emit_proposal_cancelled(e, &proposal_id);

    proposal_id
}

// ################## HELPERS ##################

/// Computes and returns the proposal ID from the proposal parameters.
///
/// The proposal ID is a deterministic keccak256 hash of the XDR-serialized
/// targets, functions, args, and description hash. This allows anyone to
/// compute the ID without storing the full proposal data.
///
/// The `description_hash` is computed as `keccak256(description.to_bytes())`,
/// i.e., a keccak256 hash of the raw UTF-8 bytes of the description string.
/// Off-chain clients can reproduce this by hashing the raw string bytes
/// directly — no XDR encoding is required.
///
/// # Arguments
///
/// * `e` - Access to the Soroban environment.
/// * `targets` - The addresses of contracts to call.
/// * `functions` - The function names to invoke on each target.
/// * `args` - The arguments for each function call.
/// * `description_hash` - The keccak256 hash of the description's raw bytes.
pub fn hash_proposal(
    e: &Env,
    targets: &Vec<Address>,
    functions: &Vec<Symbol>,
    args: &Vec<Vec<Val>>,
    description_hash: &BytesN<32>,
) -> BytesN<32> {
    // Concatenate all inputs for hashing
    let mut data = Bytes::new(e);
    data.append(&targets.to_xdr(e));
    data.append(&functions.to_xdr(e));
    data.append(&args.to_xdr(e));
    data.append(&Bytes::from_slice(e, description_hash.to_array().as_slice()));

    e.crypto().keccak256(&data).to_bytes()
}

/// Prepares a vote by verifying the proposal is active,
/// and returning the proposal snapshot ledger for voting power lookup.
///
/// # Arguments
///
/// * `e` - Access to the Soroban environment.
/// * `proposal_id` - The unique identifier of the proposal.
/// * `quorum` - The quorum threshold, evaluated at the proposal's
///   `vote_snapshot` ledger via [`Governor::quorum`].
///
/// # Errors
///
/// * [`GovernorError::ProposalNotActive`] - Occurs if the proposal is not in
///   the active state.
/// * refer to [`get_proposal_core()`] errors.
pub fn check_proposal_state(e: &Env, proposal_id: &BytesN<32>, quorum: u128) -> u32 {
    let core = get_proposal_core(e, proposal_id);
    let state = derive_proposal_state(e, proposal_id, &core, quorum);
    if state != ProposalState::Active {
        panic_with_error!(e, GovernorError::ProposalNotActive);
    }

    core.vote_snapshot
}

/// Derives the current state of a proposal.
///
/// Proposal states fall into two categories:
///
/// ## Stored states
///
/// Written to `core.state` by lifecycle functions and returned immediately
/// when present. These represent irreversible transitions that have already
/// occurred:
///
/// * [`ProposalState::Canceled`] — set by [`cancel`].
/// * [`ProposalState::Executed`] — set by [`execute`].
/// * [`ProposalState::Queued`]   — set by [`queue`].
/// * [`ProposalState::Expired`]  — set by extensions (e.g. `TimelockControl`).
///
/// ## Derived states
///
/// Computed on the fly from the current ledger and vote tallies. These are
/// never persisted; `core.state` remains [`ProposalState::Pending`] (the
/// initial value from [`propose`]) throughout the voting lifecycle. This
/// avoids a storage write after every vote while still providing accurate
/// state queries at any point:
///
/// * [`ProposalState::Pending`]   — current ledger is at or before
///   `vote_start`.
/// * [`ProposalState::Active`]    — current ledger is between `vote_start` and
///   `vote_end`. Even if quorum and majority are already met, the proposal
///   remains `Active` until voting closes so that all voters have the
///   opportunity to participate.
/// * [`ProposalState::Succeeded`] — voting ended and quorum + majority were
///   met.
/// * [`ProposalState::Defeated`]  — voting ended without meeting quorum or
///   majority.
///
/// # Arguments
///
/// * `e` - Access to the Soroban environment.
/// * `proposal_id` - The unique identifier of the proposal.
/// * `core` - The proposal's stored core data.
/// * `quorum` - The quorum threshold, evaluated at the proposal's
///   `vote_snapshot` ledger via [`Governor::quorum`].
///
/// # Errors
///
/// * [`GovernorError::MathOverflow`] - Occurs if the participation tally
///   overflows when summing `for` and `abstain` votes.
fn derive_proposal_state(
    e: &Env,
    proposal_id: &BytesN<32>,
    core: &ProposalCore,
    quorum: u128,
) -> ProposalState {
    // Stored states: return immediately — the transition already happened.
    match core.state {
        ProposalState::Canceled | ProposalState::Executed | ProposalState::Queued => {
            return core.state;
        }
        ProposalState::Expired => {
            return core.state;
        }
        _ => {}
    }

    // Derived states: `core.state` is still `Pending` (its initial value
    // from `propose`), so we determine the actual state from timing and
    // vote tallies.
    let current_ledger = e.ledger().sequence();

    // `vote_snapshot` is the snapshot ledger; voting opens on the next ledger.
    if current_ledger <= core.vote_snapshot {
        return ProposalState::Pending;
    }

    // The proposal stays `Active` until `vote_end` passes, regardless of
    // whether quorum and majority are already met. This ensures all voters
    // have the full voting period to participate.
    if current_ledger <= core.vote_end {
        return ProposalState::Active;
    }

    // Voting has ended — check whether quorum and majority were met.
    let counts = get_proposal_vote_counts(e, proposal_id);
    let Some(participation) = counts.for_votes.checked_add(counts.abstain_votes) else {
        panic_with_error!(e, GovernorError::MathOverflow);
    };
    if participation >= quorum && counts.for_votes > counts.against_votes {
        return ProposalState::Succeeded;
    }

    ProposalState::Defeated
}

// ################## COUNTING: QUERY STATE ##################

/// Returns the counting mode identifier.
///
/// For simple counting, this returns `"simple"`.
///
/// # Arguments
///
/// * `e` - Access to the Soroban environment.
pub fn counting_mode(e: &Env) -> Symbol {
    Symbol::new(e, "simple")
}

/// Returns whether an account has voted on a proposal.
///
/// # Arguments
///
/// * `e` - Access to the Soroban environment.
/// * `proposal_id` - The unique identifier of the proposal.
/// * `account` - The address to check.
pub fn has_voted(e: &Env, proposal_id: &BytesN<32>, account: &Address) -> bool {
    let key = GovernorStorageKey::HasVoted(proposal_id.clone(), account.clone());
    if e.storage().persistent().has(&key) {
        e.storage().persistent().extend_ttl(&key, GOVERNOR_TTL_THRESHOLD, GOVERNOR_EXTEND_AMOUNT);
        true
    } else {
        false
    }
}

/// Returns the quorum value effective at the given ledger.
///
/// The quorum is the minimum total voting power (for + abstain) that must
/// participate for a proposal to be valid. Quorum values are stored as
/// checkpoints, so historical lookups return the value that was in effect
/// at the requested ledger.
///
/// # Arguments
///
/// * `e` - Access to the Soroban environment.
/// * `ledger` - The ledger at which to query the quorum.
///
/// # Errors
///
/// * [`GovernorError::QuorumNotSet`] - Occurs if no quorum checkpoint exists at
///   or before the requested ledger.
pub fn get_quorum(e: &Env, ledger: u32) -> u128 {
    let num: u32 =
        e.storage().instance().get(&GovernorStorageKey::NumQuorumCheckpoints).unwrap_or(0);

    if num == 0 {
        panic_with_error!(e, GovernorError::QuorumNotSet);
    }

    // Check if ledger is at or after the latest checkpoint.
    let latest = get_quorum_checkpoint(e, num - 1);
    if latest.ledger <= ledger {
        return latest.quorum;
    }

    // Check if ledger is before the first checkpoint.
    let first = get_quorum_checkpoint(e, 0);
    if first.ledger > ledger {
        panic_with_error!(e, GovernorError::QuorumNotSet);
    }

    // Binary search for the most recent checkpoint at or before `ledger`.
    let mut low: u32 = 0;
    let mut high: u32 = num - 1;

    while low < high {
        let mid = low + (high - low).div_ceil(2);
        let cp = get_quorum_checkpoint(e, mid);
        if cp.ledger <= ledger {
            low = mid;
        } else {
            high = mid - 1;
        }
    }

    get_quorum_checkpoint(e, low).quorum
}

/// Returns the quorum checkpoint at the given index.
fn get_quorum_checkpoint(e: &Env, index: u32) -> QuorumCheckpoint {
    let key = GovernorStorageKey::QuorumCheckpoint(index);
    let cp: QuorumCheckpoint = e
        .storage()
        .persistent()
        .get(&key)
        .unwrap_or_else(|| panic_with_error!(e, GovernorError::QuorumNotSet));
    e.storage().persistent().extend_ttl(&key, GOVERNOR_TTL_THRESHOLD, GOVERNOR_EXTEND_AMOUNT);
    cp
}

/// Returns whether the quorum has been reached for a proposal.
///
/// Quorum is reached when the sum of `for` and `abstain` votes meets or
/// exceeds the configured quorum value.
///
/// # Arguments
///
/// * `e` - Access to the Soroban environment.
/// * `proposal_id` - The unique identifier of the proposal.
/// * `quorum` - The quorum threshold, evaluated at the proposal's
///   `vote_snapshot` ledger via [`Governor::quorum`].
///
/// # Errors
///
/// * [`GovernorError::MathOverflow`] - Occurs if participation tally overflows.
pub fn quorum_reached(e: &Env, proposal_id: &BytesN<32>, quorum: u128) -> bool {
    let counts = get_proposal_vote_counts(e, proposal_id);

    let Some(participation) = counts.for_votes.checked_add(counts.abstain_votes) else {
        panic_with_error!(e, GovernorError::MathOverflow);
    };

    participation >= quorum
}

/// Returns whether the tally has succeeded for a proposal.
///
/// The tally succeeds when the `for` votes strictly exceed the `against` votes.
///
/// # Arguments
///
/// * `e` - Access to the Soroban environment.
/// * `proposal_id` - The unique identifier of the proposal.
pub fn tally_succeeded(e: &Env, proposal_id: &BytesN<32>) -> bool {
    let counts = get_proposal_vote_counts(e, proposal_id);
    counts.for_votes > counts.against_votes
}

/// Returns the vote tallies for a proposal.
///
/// If no tally exists yet, this returns a zero-initialized
/// [`ProposalVoteCounts`].
///
/// Vote tally entries are created lazily on the first recorded vote, not at
/// proposal creation time. This keeps the counting logic loosely coupled to
/// the proposal lifecycle.
///
/// Because of that design, a missing storage entry is interpreted as
/// "no votes cast yet" rather than an error (`panic`) or `Option::None`.
///
/// # Arguments
///
/// * `e` - Access to the Soroban environment.
/// * `proposal_id` - The unique identifier of the proposal.
pub fn get_proposal_vote_counts(e: &Env, proposal_id: &BytesN<32>) -> ProposalVoteCounts {
    let key = GovernorStorageKey::ProposalVote(proposal_id.clone());
    e.storage()
        .persistent()
        .get::<_, ProposalVoteCounts>(&key)
        .inspect(|_| {
            e.storage().persistent().extend_ttl(
                &key,
                GOVERNOR_TTL_THRESHOLD,
                GOVERNOR_EXTEND_AMOUNT,
            );
        })
        .unwrap_or(ProposalVoteCounts { against_votes: 0, for_votes: 0, abstain_votes: 0 })
}

// ################## COUNTING: CHANGE STATE ##################

/// Sets the quorum value.
///
/// # Arguments
///
/// * `e` - Access to the Soroban environment.
/// * `quorum` - The new quorum value.
///
/// # Events
///
/// * topics - `["quorum_changed"]`
/// * data - `[old_quorum: u128, new_quorum: u128]`
///
/// ⚠️ SECURITY RISK: This function has NO AUTHORIZATION CONTROLS ⚠️
///
/// It is the responsibility of the implementer to establish appropriate
/// access controls to ensure that only authorized accounts can call this
/// function.
pub fn set_quorum(e: &Env, quorum: u128) {
    let num: u32 =
        e.storage().instance().get(&GovernorStorageKey::NumQuorumCheckpoints).unwrap_or(0);
    let ledger = e.ledger().sequence();

    let old_quorum = if num > 0 {
        let last = get_quorum_checkpoint(e, num - 1);
        // If the last checkpoint is at the same ledger, update it in place.
        if last.ledger == ledger {
            e.storage().persistent().set(
                &GovernorStorageKey::QuorumCheckpoint(num - 1),
                &QuorumCheckpoint { ledger, quorum },
            );
            emit_quorum_changed(e, last.quorum, quorum);
            return;
        }
        last.quorum
    } else {
        0u128
    };

    // Append a new checkpoint.
    e.storage()
        .persistent()
        .set(&GovernorStorageKey::QuorumCheckpoint(num), &QuorumCheckpoint { ledger, quorum });
    e.storage().instance().set(&GovernorStorageKey::NumQuorumCheckpoints, &(num + 1));

    emit_quorum_changed(e, old_quorum, quorum);
}

/// Records a vote on a proposal.
///
/// # Arguments
///
/// * `e` - Access to the Soroban environment.
/// * `proposal_id` - The unique identifier of the proposal.
/// * `account` - The address casting the vote.
/// * `vote_type` - The type of vote (0 = Against, 1 = For, 2 = Abstain).
/// * `weight` - The voting power of the voter.
///
/// # Errors
///
/// * [`GovernorError::AlreadyVoted`] - Occurs if the account has already voted
///   on this proposal.
/// * [`GovernorError::InvalidVoteType`] - Occurs if the vote type is not 0, 1,
///   or 2.
/// * [`GovernorError::MathOverflow`] - Occurs if vote tallying overflows.
///
/// ⚠️ SECURITY RISK: This function has NO AUTHORIZATION CONTROLS ⚠️
///
/// It is the responsibility of the implementer to establish appropriate
/// access controls to ensure that only authorized accounts can call this
/// function.
pub fn count_vote(
    e: &Env,
    proposal_id: &BytesN<32>,
    account: &Address,
    vote_type: u32,
    weight: u128,
) {
    // Check if the account has already voted
    let voted_key = GovernorStorageKey::HasVoted(proposal_id.clone(), account.clone());
    if e.storage().persistent().has(&voted_key) {
        panic_with_error!(e, GovernorError::AlreadyVoted);
    }

    // Get current vote counts
    let mut counts = get_proposal_vote_counts(e, proposal_id);

    // Update vote counts based on vote type
    match vote_type {
        VOTE_AGAINST => {
            let Some(new_against) = counts.against_votes.checked_add(weight) else {
                panic_with_error!(e, GovernorError::MathOverflow);
            };
            counts.against_votes = new_against;
        }
        VOTE_FOR => {
            let Some(new_for) = counts.for_votes.checked_add(weight) else {
                panic_with_error!(e, GovernorError::MathOverflow);
            };
            counts.for_votes = new_for;
        }
        VOTE_ABSTAIN => {
            let Some(new_abstain) = counts.abstain_votes.checked_add(weight) else {
                panic_with_error!(e, GovernorError::MathOverflow);
            };
            counts.abstain_votes = new_abstain;
        }
        _ => panic_with_error!(e, GovernorError::InvalidVoteType),
    }

    // Store updated vote counts
    let vote_key = GovernorStorageKey::ProposalVote(proposal_id.clone());
    e.storage().persistent().set(&vote_key, &counts);

    // Mark account as having voted
    e.storage().persistent().set(&voted_key, &true);
}

/// Casts a vote on a proposal and returns the voter's voting power.
///
/// This is the high-level vote flow: it verifies the proposal is active,
/// fetches the voter's voting power from the token contract at the proposal
/// snapshot, records the vote, and emits a
/// [`VoteCast`](crate::governor::VoteCast) event.
///
/// # Arguments
///
/// * `e` - Access to the Soroban environment.
/// * `proposal_id` - The unique identifier of the proposal.
/// * `vote_type` - The type of vote (0 = Against, 1 = For, 2 = Abstain).
/// * `reason` - An optional explanation for the vote.
/// * `voter` - The address casting the vote.
/// * `quorum` - The quorum threshold, evaluated at the proposal's
///   `vote_snapshot` ledger via [`Governor::quorum`].
///
/// # Errors
///
/// * [`GovernorError::ProposalNotActive`] - If the proposal is not active.
/// * [`GovernorError::AlreadyVoted`] - If the voter has already voted.
/// * [`GovernorError::InvalidVoteType`] - If the vote type is invalid.
/// * [`GovernorError::MathOverflow`] - If vote tallying overflows.
/// * refer to [`get_proposal_core()`] errors.
/// * refer to [`get_token_contract()`] errors.
///
/// ⚠️ SECURITY RISK: This function has NO AUTHORIZATION CONTROLS ⚠️
///
/// It is the responsibility of the implementer to establish appropriate
/// access controls to ensure that only authorized accounts can call this
/// function.
pub fn cast_vote(
    e: &Env,
    proposal_id: &BytesN<32>,
    vote_type: u32,
    reason: &String,
    voter: &Address,
    quorum: u128,
) -> u128 {
    let snapshot = check_proposal_state(e, proposal_id, quorum);
    let voter_weight = get_voting_power(e, voter, snapshot);
    count_vote(e, proposal_id, voter, vote_type, voter_weight);
    emit_vote_cast(e, voter, proposal_id, vote_type, voter_weight, reason);
    voter_weight
}

// ################## INTERNAL HELPERS ##################

/// Fetches the voting power of an account at a specific ledger sequence
/// number from the token contract via a cross-contract call to
/// `get_votes_at_checkpoint`.
///
/// # Arguments
///
/// * `e` - Access to the Soroban environment.
/// * `account` - The address to query voting power for.
/// * `ledger` - The ledger sequence number to query.
///
/// # Errors
///
/// * refer to [`get_token_contract()`] errors.
fn get_voting_power(e: &Env, account: &Address, ledger: u32) -> u128 {
    let token = get_token_contract(e);
    VotesClient::new(e, &token).get_votes_at_checkpoint(&account.clone(), &ledger)
}