-
Notifications
You must be signed in to change notification settings - Fork 126
Expand file tree
/
Copy pathlib.rs
More file actions
1390 lines (1236 loc) · 50.7 KB
/
Copy pathlib.rs
File metadata and controls
1390 lines (1236 loc) · 50.7 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
//! ILN Governance Contract
//!
//! Issue #59 — GovernanceProposal struct with full spec fields.
//! Issue #61 — cast_vote() with anti-double-vote protection and VoteCast event.
//! Issue #64 — delegate_votes() / undelegate_votes() with transitive delegation
//! and cycle detection.
//! Issue #68 — veto_proposal() admin emergency block with governance-controlled
//! disable mechanism.
#![no_std]
#[cfg(test)]
extern crate std;
use soroban_sdk::{
contract, contracterror, contractimpl, contracttype, token::Client as TokenClient, vec,
Address, BytesN, Env, IntoVal, Symbol, Vec,
};
/// Vote receipts only need to outlive the active voting window.
const VOTE_RECEIPT_TTL_THRESHOLD_LEDGERS: u32 = 50_000;
const VOTE_RECEIPT_TTL_LEDGERS: u32 = 69_120;
/// Default minimum quorum = 10% (1000 bps).
const DEFAULT_MIN_QUORUM_BPS: u32 = 1_000;
/// Default voting window: 3 days at ~5 s/ledger ≈ 51_840 ledgers.
/// Expressed in seconds to match `env.ledger().timestamp()`.
const VOTING_PERIOD_SECS: u64 = 259_200;
/// Default minimum token balance required to submit a proposal (1 000 stroops).
const DEFAULT_MIN_PROPOSAL_BALANCE: i128 = 1_000;
/// Maximum transitive delegation chain depth we will traverse.
const MAX_DELEGATION_DEPTH: u32 = 10;
// ================================================================
// Governance error enum
// ================================================================
#[contracterror]
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum GovernanceError {
AlreadyInitialized = 1,
ProposalNotFound = 2,
VotingEnded = 3,
ProposalNotActive = 4,
NoVotingPower = 5,
AlreadyVoted = 6,
VotingOngoing = 7,
QuorumNotReached = 8,
ProposalRejected = 9,
AlreadyResolved = 10,
/// Issue #64: Delegating to self is not allowed.
CannotDelegateToSelf = 11,
/// Issue #64: Delegation would create a cycle.
DelegationCyclePrevented = 12,
TimelockNotExpired = 13,
Unauthorized = 14,
/// Invalid quorum basis points (must be 1..=10_000).
InvalidQuorumBps = 15,
/// Issue #68: caller is not the admin.
NotAdmin = 16,
/// Issue #68: proposal cannot be vetoed in its current status.
NotVetoable = 17,
/// Issue #68: admin veto power has been disabled by governance.
VetoPowerDisabled = 18,
/// Proposer does not hold the minimum required token balance.
InsufficientProposerBalance = 19,
/// Issue #531: the cross-contract execution call failed. The proposal
/// remains in `Passed` status so `execute_proposal` can be retried.
ExecutionFailed = 20,
}
// ================================================================
// ProposalAction
// ================================================================
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub enum ProposalAction {
UpdateFeeRate(u32),
/// Add a token to the allowlist. The tuple carries the token address and
/// its decimal precision (e.g. 6 for USDC, 7 for XLM) — required since
/// Issue #23 introduced the token decimals registry.
AddToken(Address, u32),
RemoveToken(Address),
UpdateMaxDiscountRate(u32),
/// Issue #545: Update reputation decay parameters on the ILN contract.
/// Tuple: (rate_bps, period_ledgers)
UpdateDecayParams(u32, u64),
/// Issue #544: Update distribution reward parameters.
/// Tuple: (half_token, hundred_usdc_stroops, lp_multiplier)
UpdateDistributionRewardParams(i128, i128, i128),
/// Issue #533: Update fee tier configuration on the ILN contract.
UpdateFeeTiers(Vec<FeeTierConfig>),
/// Issue #539: Upgrade the ILN contract WASM via governance vote.
Upgrade(BytesN<32>),
/// Update LP reward rate (in stroops per 100 USDC volume).
UpdateLpRewardRate(i128),
/// Update freelancer reward rate (in stroops per settlement).
UpdateFreelancerRewardRate(i128),
/// Update payer reward rate (in stroops per on-time settlement).
UpdatePayerRewardRate(i128),
/// Update insurance pool coverage cap (in stroops).
UpdateInsuranceCoverageCap(i128),
/// Update insurance pool premium rates (in bps).
UpdateInsurancePremiumRate(u32),
/// Issue #532: register (or update) the default oracle for a feed type
/// on the ILN contract's oracle registry.
RegisterOracle(OracleFeedType, Address),
/// Issue #532: remove the default oracle for a feed type from the ILN
/// contract's oracle registry.
RemoveOracle(OracleFeedType),
}
/// Issue #532: mirrors `invoice_liquidity::oracle_registry::OracleFeedType`.
/// Soroban contracts share no Rust types across crates — cross-contract
/// calls decode structurally (same unit-variant names, same order), the
/// same way `FeeTierConfig` below mirrors the ILN contract's fee tier
/// struct. Keep variant names/order in sync with the ILN contract's enum.
#[contracttype]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OracleFeedType {
Price,
Identity,
Credit,
}
/// Issue #533: Fee tier configuration.
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct FeeTierConfig {
/// Minimum invoice amount for this tier (inclusive, in stroops).
pub min_amount: i128,
/// Fee rate in basis points for this tier.
pub fee_rate_bps: u32,
}
// ================================================================
// ProposalStatus
// ================================================================
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub enum ProposalStatus {
Active,
Passed,
Rejected,
Executed,
/// Issue #68: proposal was blocked by the admin via veto_proposal().
Vetoed,
}
// ================================================================
// GovernanceProposal struct
// ================================================================
#[contracttype]
#[derive(Clone, Debug)]
pub struct GovernanceProposal {
pub id: u64,
pub proposer: Address,
pub description_hash: BytesN<32>,
pub action_type: ProposalAction,
pub proposed_value: i128,
pub status: ProposalStatus,
pub votes_for: i128,
pub votes_against: i128,
pub created_at: u64,
pub voting_end: u64,
pub eta_ledger: u32,
}
// ================================================================
// Events
// ================================================================
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct VoteCast {
pub proposal_id: u64,
pub voter: Address,
pub support: bool,
pub weight: i128,
}
/// Issue #64
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct VotesDelegated {
pub delegator: Address,
pub delegate: Address,
}
/// Issue #64
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct VotesUndelegated {
pub delegator: Address,
}
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct ProposalExecuted {
pub proposal_id: u64,
pub action_type: ProposalAction,
pub proposed_value: i128,
pub votes_for: i128,
pub votes_against: i128,
}
/// Issue #531: emitted when a proposal's cross-contract execution call
/// fails. The proposal remains `Passed` (not `Executed`) so a subsequent
/// `execute_proposal` call can retry it.
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct ProposalExecutionFailed {
pub proposal_id: u64,
pub action_type: ProposalAction,
}
/// Issue #68: emitted when the admin vetoes a proposal.
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct ProposalVetoed {
pub proposal_id: u64,
pub admin: Address,
pub reason_hash: BytesN<32>,
}
/// Emitted when a new governance proposal is created.
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct ProposalCreated {
pub proposal_id: u64,
pub proposer: Address,
pub action_type: ProposalAction,
pub proposed_value: i128,
pub voting_end: u64,
}
/// Emitted once, when the contract is initialised (Issue #538).
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct GovernanceInitialized {
pub iln_contract: Address,
pub gov_token: Address,
pub admin: Address,
}
/// Emitted whenever a governance-controlled numeric parameter changes
/// (Issue #538: event emission completeness audit).
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct GovernanceParameterUpdated {
pub param_name: Symbol,
pub old_value: i128,
pub new_value: i128,
}
/// Emitted when admin veto power is permanently disabled (Issue #68 / #538).
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct VetoPowerDisabled {
pub disabled_by: Address,
}
// ================================================================
// Storage keys
// ================================================================
#[contracttype]
pub enum StorageKey {
IlnContract,
GovToken,
/// Configurable minimum participation required for proposal passing.
/// Expressed in basis points (bps) of total supply, e.g. 1000 = 10%.
MinQuorumBps,
/// Issue #622: governance token total supply used as the quorum
/// denominator. Seeded at `initialize` time and only updatable via the
/// ILN-contract-gated `set_gov_token_total_supply` — no longer a
/// caller-supplied `execute_proposal` argument.
GovTokenTotalSupply,
Proposal(u64),
ProposalCount,
VoteWeightSnapshot(u64, Address),
HasVoted(u64, Address),
/// Issue #530: `true` when vote weight is `sqrt(balance + delegated)`
/// instead of linear. Defaults to `false` for backwards compatibility.
QuadraticVotingEnabled,
/// Issue #530: the actual weight applied to the tally for this voter on
/// this proposal (post square-root transform when quadratic voting is
/// enabled, otherwise equal to the linear balance). Recorded alongside
/// `HasVoted` as the vote receipt.
AppliedVoteWeight(u64, Address),
/// Issue #64: forward delegation pointer — Delegation(X) = Y means X delegates to Y.
Delegation(Address),
/// Issue #64: running tally of total delegated weight pointing (transitively) at Address.
DelegatedToMe(Address),
ExecutionDelay,
/// Issue #68: the admin address (set at initialise time).
Admin,
/// Issue #68: when `true`, admin veto power is active; when `false`, it has been disabled.
VetoPowerEnabled,
/// Configurable minimum token balance a proposer must hold.
MinProposalBalance,
/// Issue #544: distribution contract address for reward param updates.
DistributionContract,
}
// ================================================================
// Contract
// ================================================================
#[contract]
pub struct GovContract;
#[contractimpl]
impl GovContract {
// ── Initialise ────────────────────────────────────────────────
pub fn initialize(
env: Env,
iln_contract: Address,
distribution_contract: Address,
gov_token: Address,
admin: Address,
gov_token_total_supply: i128,
) -> Result<(), GovernanceError> {
if env.storage().instance().has(&StorageKey::IlnContract) {
return Err(GovernanceError::AlreadyInitialized);
}
env.storage()
.instance()
.set(&StorageKey::IlnContract, &iln_contract);
env.storage()
.instance()
.set(&StorageKey::DistributionContract, &distribution_contract);
env.storage()
.instance()
.set(&StorageKey::GovToken, &gov_token);
env.storage().instance().set(&StorageKey::Admin, &admin);
env.storage()
.instance()
.set(&StorageKey::VetoPowerEnabled, &true);
env.storage()
.instance()
.set(&StorageKey::MinQuorumBps, &DEFAULT_MIN_QUORUM_BPS);
env.storage()
.instance()
.set(&StorageKey::ProposalCount, &0_u64);
// Issue #622: total_supply used to be a caller-supplied argument to
// execute_proposal, letting any caller inflate or deflate it to
// manipulate quorum. soroban-sdk 21.x's token::Client has no
// total_supply() query (SEP-41's TokenInterface/StellarAssetInterface
// don't expose one), so a live on-chain read isn't available here —
// instead this value is seeded at initialize time and can only be
// updated afterwards via set_gov_token_total_supply, which requires
// the same iln_contract authorization as set_min_quorum_bps /
// set_min_proposal_balance. It is no longer settable by whoever
// happens to call execute_proposal.
env.storage()
.instance()
.set(&StorageKey::GovTokenTotalSupply, &gov_token_total_supply);
env.events().publish(
(Symbol::new(&env, "initialized"), admin.clone()),
GovernanceInitialized {
iln_contract,
gov_token,
admin,
},
);
Ok(())
}
/// Returns the configured minimum quorum in bps (e.g. 1000 = 10%).
pub fn get_min_quorum_bps(env: Env) -> u32 {
env.storage()
.instance()
.get(&StorageKey::MinQuorumBps)
.unwrap_or(DEFAULT_MIN_QUORUM_BPS)
}
/// Returns the configured governance token total supply used for quorum
/// calculations (see Issue #622).
pub fn get_gov_token_total_supply(env: Env) -> i128 {
env.storage()
.instance()
.get(&StorageKey::GovTokenTotalSupply)
.unwrap_or(0)
}
/// Updates the governance token total supply used for quorum
/// calculations.
///
/// Authorization: the configured ILN contract address must authorize —
/// the same trust boundary as `set_min_quorum_bps` /
/// `set_min_proposal_balance`. This replaces the old caller-supplied
/// `total_supply` argument on `execute_proposal` (Issue #622): quorum's
/// denominator can no longer be chosen by whoever happens to call
/// execute_proposal, only by the same authority that already controls
/// the quorum bps and proposal-balance thresholds.
pub fn set_gov_token_total_supply(env: Env, total_supply: i128) -> Result<(), GovernanceError> {
let iln_contract: Address = env
.storage()
.instance()
.get(&StorageKey::IlnContract)
.unwrap();
iln_contract.require_auth();
let old_value: i128 = env
.storage()
.instance()
.get(&StorageKey::GovTokenTotalSupply)
.unwrap_or(0);
env.storage()
.instance()
.set(&StorageKey::GovTokenTotalSupply, &total_supply);
let pn = Symbol::new(&env, "gov_token_total_supply");
env.events().publish(
(Symbol::new(&env, "parameter_updated"), pn.clone()),
GovernanceParameterUpdated {
param_name: pn,
old_value,
new_value: total_supply,
},
);
Ok(())
}
/// Updates the minimum quorum configuration.
///
/// Authorization: the configured ILN contract address must authorize.
pub fn set_min_quorum_bps(env: Env, min_quorum_bps: u32) -> Result<(), GovernanceError> {
if min_quorum_bps == 0 || min_quorum_bps > 10_000 {
return Err(GovernanceError::InvalidQuorumBps);
}
let iln_contract: Address = env
.storage()
.instance()
.get(&StorageKey::IlnContract)
.unwrap();
iln_contract.require_auth();
let old_value: u32 = env
.storage()
.instance()
.get(&StorageKey::MinQuorumBps)
.unwrap_or(DEFAULT_MIN_QUORUM_BPS);
env.storage()
.instance()
.set(&StorageKey::MinQuorumBps, &min_quorum_bps);
let pn = Symbol::new(&env, "min_quorum_bps");
env.events().publish(
(Symbol::new(&env, "parameter_updated"), pn.clone()),
GovernanceParameterUpdated {
param_name: pn,
old_value: old_value as i128,
new_value: min_quorum_bps as i128,
},
);
Ok(())
}
// ── Issue #59 / feat/create-proposal ─────────────────────────
pub fn create_proposal(
env: Env,
proposer: Address,
action_type: ProposalAction,
description_hash: BytesN<32>,
proposed_value: i128,
) -> Result<u64, GovernanceError> {
proposer.require_auth();
// ── Balance check ─────────────────────────────────────────
let token_addr: Address = env.storage().instance().get(&StorageKey::GovToken).unwrap();
let token = TokenClient::new(&env, &token_addr);
let proposer_balance = token.balance(&proposer);
let min_balance: i128 = env
.storage()
.instance()
.get(&StorageKey::MinProposalBalance)
.unwrap_or(DEFAULT_MIN_PROPOSAL_BALANCE);
if proposer_balance < min_balance {
return Err(GovernanceError::InsufficientProposerBalance);
}
let count: u64 = env
.storage()
.instance()
.get(&StorageKey::ProposalCount)
.unwrap_or(0);
let id = count.saturating_add(1);
let now = env.ledger().timestamp();
let voting_end = now.saturating_add(VOTING_PERIOD_SECS);
let proposal = GovernanceProposal {
id,
proposer: proposer.clone(),
description_hash,
action_type: action_type.clone(),
proposed_value,
status: ProposalStatus::Active,
votes_for: 0,
votes_against: 0,
created_at: now,
voting_end,
eta_ledger: 0,
};
// Snapshot the proposer's balance at proposal creation time.
env.storage().persistent().set(
&StorageKey::VoteWeightSnapshot(id, proposer.clone()),
&proposer_balance,
);
env.storage()
.persistent()
.set(&StorageKey::Proposal(id), &proposal);
env.storage()
.instance()
.set(&StorageKey::ProposalCount, &id);
env.events().publish(
(Symbol::new(&env, "proposal_created"), id, proposer.clone()),
ProposalCreated {
proposal_id: id,
proposer,
action_type,
proposed_value,
voting_end,
},
);
Ok(id)
}
// ── Issue #530: quadratic voting toggle ───────────────────────
/// Returns whether quadratic voting (`sqrt(balance + delegated)` weight)
/// is enabled. Defaults to `false` (linear weighting) for backwards
/// compatibility with proposals created before this feature existed.
pub fn is_quadratic_voting_enabled(env: Env) -> bool {
env.storage()
.instance()
.get(&StorageKey::QuadraticVotingEnabled)
.unwrap_or(false)
}
/// Enables or disables quadratic voting.
///
/// Authorization: the configured ILN contract address must authorize
/// (same governance-controlled-toggle pattern as `set_min_quorum_bps`).
pub fn set_quadratic_voting_enabled(env: Env, enabled: bool) -> Result<(), GovernanceError> {
let iln_contract: Address = env
.storage()
.instance()
.get(&StorageKey::IlnContract)
.unwrap();
iln_contract.require_auth();
let old_value: bool = env
.storage()
.instance()
.get(&StorageKey::QuadraticVotingEnabled)
.unwrap_or(false);
env.storage()
.instance()
.set(&StorageKey::QuadraticVotingEnabled, &enabled);
let pn = Symbol::new(&env, "quadratic_voting_enabled");
env.events().publish(
(Symbol::new(&env, "parameter_updated"), pn.clone()),
GovernanceParameterUpdated {
param_name: pn,
old_value: old_value as i128,
new_value: enabled as i128,
},
);
Ok(())
}
/// Returns the actual weight applied to `voter`'s vote on `proposal_id`,
/// i.e. the vote receipt recorded by Issue #530. `None` if the address
/// has not voted on this proposal (or its temporary-storage TTL expired).
pub fn get_applied_vote_weight(env: Env, proposal_id: u64, voter: Address) -> Option<i128> {
env.storage()
.temporary()
.get(&StorageKey::AppliedVoteWeight(proposal_id, voter))
}
/// Integer square root (floor) via binary search. `n` is assumed `>= 0`
/// (token balances and delegated weight tallies are non-negative).
fn isqrt(n: i128) -> i128 {
if n <= 1 {
return n.max(0);
}
let mut lo: i128 = 0;
let mut hi: i128 = n;
while lo < hi {
let mid = lo + (hi - lo + 1) / 2;
match mid.checked_mul(mid) {
Some(sq) if sq <= n => lo = mid,
_ => hi = mid - 1,
}
}
lo
}
/// Returns the configured minimum proposer balance.
pub fn get_min_proposal_balance(env: Env) -> i128 {
env.storage()
.instance()
.get(&StorageKey::MinProposalBalance)
.unwrap_or(DEFAULT_MIN_PROPOSAL_BALANCE)
}
/// Updates the minimum proposer balance.
///
/// Authorization: the configured ILN contract address must authorize.
pub fn set_min_proposal_balance(env: Env, min_balance: i128) -> Result<(), GovernanceError> {
let iln_contract: Address = env
.storage()
.instance()
.get(&StorageKey::IlnContract)
.unwrap();
iln_contract.require_auth();
let old_value: i128 = env
.storage()
.instance()
.get(&StorageKey::MinProposalBalance)
.unwrap_or(DEFAULT_MIN_PROPOSAL_BALANCE);
env.storage()
.instance()
.set(&StorageKey::MinProposalBalance, &min_balance);
let pn = Symbol::new(&env, "min_proposal_balance");
env.events().publish(
(Symbol::new(&env, "parameter_updated"), pn.clone()),
GovernanceParameterUpdated {
param_name: pn,
old_value,
new_value: min_balance,
},
);
Ok(())
}
// ── Issue #64: delegate_votes ─────────────────────────────────
/// Delegate the caller's voting weight to `delegate`.
///
/// * Cannot delegate to self.
/// * Rejects delegation if it would create a cycle in the chain.
/// * Re-delegation overwrites the previous delegation and adjusts the
/// `DelegatedToMe` tally on both old and new terminal nodes.
///
/// Emits `VotesDelegated`.
pub fn delegate_votes(
env: Env,
delegator: Address,
delegate: Address,
) -> Result<(), GovernanceError> {
delegator.require_auth();
if delegator == delegate {
return Err(GovernanceError::CannotDelegateToSelf);
}
// ── Cycle detection ───────────────────────────────────────
// Walk the forward chain from `delegate`.
// If we reach `delegator` at any point, the new edge would close a cycle.
let mut cursor: Option<Address> = Self::get_delegate_raw(&env, &delegate);
let mut depth = 0u32;
while let Some(ref next) = cursor.clone() {
if depth >= MAX_DELEGATION_DEPTH {
break;
}
if *next == delegator {
return Err(GovernanceError::DelegationCyclePrevented);
}
cursor = Self::get_delegate_raw(&env, next);
depth += 1;
}
// ── Find the terminal node for `delegate` ─────────────────
let terminal = Self::resolve_terminal(&env, &delegate);
// ── Remove weight from old terminal if re-delegating ──────
if let Some(old_delegate) = Self::get_delegate_raw(&env, &delegator) {
let old_terminal = Self::resolve_terminal(&env, &old_delegate);
let delegator_balance = Self::get_own_balance_for_delegation(&env, &delegator);
Self::adjust_delegated_to_me(&env, &old_terminal, -delegator_balance);
}
// ── Store forward pointer ─────────────────────────────────
env.storage()
.persistent()
.set(&StorageKey::Delegation(delegator.clone()), &delegate);
// ── Add weight to new terminal ────────────────────────────
let delegator_balance = Self::get_own_balance_for_delegation(&env, &delegator);
Self::adjust_delegated_to_me(&env, &terminal, delegator_balance);
env.events().publish(
(
Symbol::new(&env, "votes_delegated"),
delegator.clone(),
delegate.clone(),
),
VotesDelegated {
delegator,
delegate,
},
);
Ok(())
}
// ── Issue #64: undelegate_votes ───────────────────────────────
/// Remove the caller's delegation.
///
/// Emits `VotesUndelegated`.
pub fn undelegate_votes(env: Env, delegator: Address) -> Result<(), GovernanceError> {
delegator.require_auth();
if let Some(old_delegate) = Self::get_delegate_raw(&env, &delegator) {
let old_terminal = Self::resolve_terminal(&env, &old_delegate);
let delegator_balance = Self::get_own_balance_for_delegation(&env, &delegator);
Self::adjust_delegated_to_me(&env, &old_terminal, -delegator_balance);
env.storage()
.persistent()
.remove(&StorageKey::Delegation(delegator.clone()));
}
env.events().publish(
(Symbol::new(&env, "votes_undelegated"), delegator.clone()),
VotesUndelegated { delegator },
);
Ok(())
}
// ── Issue #64: get_delegate ───────────────────────────────────
/// Return the direct delegate for `addr`, if any.
pub fn get_delegate(env: Env, addr: Address) -> Option<Address> {
Self::get_delegate_raw(&env, &addr)
}
// ── cast_vote ─────────────────────────────────────────────────
/// Cast a vote on an active proposal.
///
/// Issue #64: weight = own snapshot balance + DelegatedToMe tally.
pub fn cast_vote(
env: Env,
voter: Address,
proposal_id: u64,
support: bool,
) -> Result<(), GovernanceError> {
voter.require_auth();
let mut proposal: GovernanceProposal = env
.storage()
.persistent()
.get(&StorageKey::Proposal(proposal_id))
.ok_or(GovernanceError::ProposalNotFound)?;
let now = env.ledger().timestamp();
if now >= proposal.voting_end {
return Err(GovernanceError::VotingEnded);
}
if proposal.status != ProposalStatus::Active {
return Err(GovernanceError::ProposalNotActive);
}
let voted_key = StorageKey::HasVoted(proposal_id, voter.clone());
if env.storage().temporary().has(&voted_key) {
return Err(GovernanceError::AlreadyVoted);
}
let token_addr: Address = env.storage().instance().get(&StorageKey::GovToken).unwrap();
let token = TokenClient::new(&env, &token_addr);
// Own snapshotted (or current) balance.
let snapshot_key = StorageKey::VoteWeightSnapshot(proposal_id, voter.clone());
let own_balance: i128 = match env.storage().persistent().get(&snapshot_key) {
Some(w) => w,
None => {
let current = token.balance(&voter);
env.storage().persistent().set(&snapshot_key, ¤t);
current
}
};
// Issue #64: add delegated weight.
let delegated: i128 = env
.storage()
.persistent()
.get(&StorageKey::DelegatedToMe(voter.clone()))
.unwrap_or(0_i128);
let raw_weight = own_balance.saturating_add(delegated);
// Issue #530: quadratic voting reduces whale influence by weighting
// votes by sqrt(balance + delegated) instead of the raw balance.
// Off by default so proposals created before this feature shipped
// keep their original linear semantics.
let weight = if Self::is_quadratic_voting_enabled(env.clone()) {
Self::isqrt(raw_weight)
} else {
raw_weight
};
if weight == 0 {
return Err(GovernanceError::NoVotingPower);
}
if support {
proposal.votes_for = proposal.votes_for.saturating_add(weight);
} else {
proposal.votes_against = proposal.votes_against.saturating_add(weight);
}
env.storage().temporary().set(&voted_key, &true);
env.storage().temporary().extend_ttl(
&voted_key,
VOTE_RECEIPT_TTL_THRESHOLD_LEDGERS,
VOTE_RECEIPT_TTL_LEDGERS,
);
// Issue #530: record the actual weight applied (vote receipt).
let applied_weight_key = StorageKey::AppliedVoteWeight(proposal_id, voter.clone());
env.storage().temporary().set(&applied_weight_key, &weight);
env.storage().temporary().extend_ttl(
&applied_weight_key,
VOTE_RECEIPT_TTL_THRESHOLD_LEDGERS,
VOTE_RECEIPT_TTL_LEDGERS,
);
env.storage()
.persistent()
.set(&StorageKey::Proposal(proposal_id), &proposal);
env.events().publish(
(Symbol::new(&env, "vote_cast"), proposal_id, voter.clone()),
VoteCast {
proposal_id,
voter,
support,
weight,
},
);
Ok(())
}
// ── Issue #62: set_execution_delay / get_execution_delay ──
pub fn set_execution_delay(
env: Env,
admin: Address,
delay: u32,
) -> Result<(), GovernanceError> {
admin.require_auth();
if let Some(stored_admin) = env
.storage()
.instance()
.get::<StorageKey, Address>(&StorageKey::Admin)
{
if admin != stored_admin {
return Err(GovernanceError::Unauthorized);
}
} else {
env.storage().instance().set(&StorageKey::Admin, &admin);
}
let old_value: u32 = env
.storage()
.instance()
.get(&StorageKey::ExecutionDelay)
.unwrap_or(0_u32);
env.storage()
.instance()
.set(&StorageKey::ExecutionDelay, &delay);
let pn = Symbol::new(&env, "execution_delay");
env.events().publish(
(Symbol::new(&env, "parameter_updated"), pn.clone()),
GovernanceParameterUpdated {
param_name: pn,
old_value: old_value as i128,
new_value: delay as i128,
},
);
Ok(())
}
pub fn get_execution_delay(env: Env) -> u32 {
env.storage()
.instance()
.get(&StorageKey::ExecutionDelay)
.unwrap_or(0)
}
// ── execute_proposal ─────────────────────────────────────────
pub fn execute_proposal(env: Env, proposal_id: u64) -> Result<(), GovernanceError> {
let mut proposal: GovernanceProposal = env
.storage()
.persistent()
.get(&StorageKey::Proposal(proposal_id))
.ok_or(GovernanceError::ProposalNotFound)?;
let now = env.ledger().timestamp();
if now < proposal.voting_end {
return Err(GovernanceError::VotingOngoing);
}
if proposal.status == ProposalStatus::Active {
let total_votes = proposal.votes_for.saturating_add(proposal.votes_against);
let min_quorum_bps: u32 = env
.storage()
.instance()
.get(&StorageKey::MinQuorumBps)
.unwrap_or(DEFAULT_MIN_QUORUM_BPS);
// Issue #622: total_supply used to be a caller-supplied argument,
// letting a caller inflate it (lowering the effective quorum) or
// deflate it (blocking quorum entirely). Read the contract-stored
// value instead (seeded at initialize, only updatable via the
// ILN-contract-gated set_gov_token_total_supply) — it can no
// longer be chosen by whoever happens to call execute_proposal.
let total_supply: i128 = env
.storage()
.instance()
.get(&StorageKey::GovTokenTotalSupply)
.unwrap_or(0);
let quorum = if total_supply <= 0 {
0_i128
} else {
total_supply.saturating_mul(min_quorum_bps as i128) / 10_000_i128
};
if total_votes < quorum {
proposal.status = ProposalStatus::Rejected;
env.storage()
.persistent()
.set(&StorageKey::Proposal(proposal_id), &proposal);
return Err(GovernanceError::QuorumNotReached);
}
if proposal.votes_for <= proposal.votes_against {
proposal.status = ProposalStatus::Rejected;
env.storage()
.persistent()
.set(&StorageKey::Proposal(proposal_id), &proposal);
return Err(GovernanceError::ProposalRejected);
}
proposal.status = ProposalStatus::Passed;
let delay = env
.storage()
.instance()
.get(&StorageKey::ExecutionDelay)
.unwrap_or(0_u32);
proposal.eta_ledger = env.ledger().sequence().saturating_add(delay);
env.storage()
.persistent()
.set(&StorageKey::Proposal(proposal_id), &proposal);
return Ok(());
}
if proposal.status == ProposalStatus::Passed {
let current_ledger = env.ledger().sequence();
if current_ledger < proposal.eta_ledger {
return Err(GovernanceError::TimelockNotExpired);
}
let iln_contract: Address = env
.storage()
.instance()
.get(&StorageKey::IlnContract)
.unwrap();
// Issue #531: capture the outcome of the cross-contract call instead
// of firing-and-forgetting it. A failed call (callee panics / returns