forked from Vero-protocol/vero-core-contracts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy_entry.rs
More file actions
917 lines (808 loc) · 35.1 KB
/
Copy pathproxy_entry.rs
File metadata and controls
917 lines (808 loc) · 35.1 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
#![allow(missing_docs)]
use crate::contracts::logic;
use crate::contracts::validate_address;
use crate::types::{
BatchCall, ContractError, DataKey, GuardianEntry, RewardStream, Snapshot, SnapshotMeta, Task,
};
use crate::DEFAULT_WEIGHT_THRESHOLD;
use crate::{circuit_breaker, drips, events, guardian, reputation, storage, task};
use soroban_sdk::{contract, contractimpl, panic_with_error, Address, BytesN, Env, Vec};
/// The main entrypoint for the Vero Core contract.
///
/// Implements all contract features including voting, task registration,
/// reputation management, token locking, and upgrades.
#[contract]
pub struct VeroContract;
fn is_strictly_sorted_addresses(addrs: &Vec<Address>) -> bool {
if addrs.len() < 2 {
return true;
}
let mut prev = addrs.get(0).unwrap();
let mut i = 1;
while i < addrs.len() {
let current = addrs.get(i).unwrap();
if prev >= current {
return false;
}
prev = current;
i += 1;
}
true
}
#[contractimpl]
impl VeroContract {
pub fn initialize(
env: Env,
admin: Address,
token: Address,
lock_threshold: i128,
) -> Result<(), ContractError> {
validate_address(&env, &admin)?;
validate_address(&env, &token)?;
if env
.storage()
.instance()
.get::<_, bool>(&DataKey::Initialized)
.unwrap_or(false)
{
return Err(ContractError::AlreadyInitialized);
}
env.storage().instance().set(&DataKey::Initialized, &true);
env.storage().instance().set(&DataKey::Admin, &admin);
env.storage().instance().set(&DataKey::TokenAddress, &token);
env.storage()
.instance()
.set(&DataKey::LockThreshold, &lock_threshold);
env.storage().instance().set(&DataKey::Paused, &false);
// Grant Admin role to the deployer/initial admin
let admin_role_key = DataKey::RoleAssignment(admin.clone(), crate::types::Role::Admin);
env.storage().instance().set(&admin_role_key, &true);
crate::migrate::set_version(&env, crate::migrate::CURRENT_VERSION);
env.storage().instance().extend_ttl(100_000, 100_000);
events::emit_contract_initialized(&env, &admin);
Ok(())
}
pub fn get_admin(env: Env) -> Option<Address> {
env.storage().instance().get(&DataKey::Admin)
}
pub fn toggle_pause(env: Env, admin: Address) -> Result<(), ContractError> {
validate_address(&env, &admin)?;
crate::contracts::rbac::require_role(&env, &admin, crate::types::Role::EmergencyManager)?;
let current = env
.storage()
.instance()
.get(&DataKey::Paused)
.unwrap_or(false);
let new_paused = !current;
env.storage().instance().set(&DataKey::Paused, &new_paused);
events::emit_pause_toggled(&env, new_paused);
Ok(())
}
pub fn pause(env: Env, admin: Address) -> Result<(), ContractError> {
validate_address(&env, &admin)?;
crate::contracts::rbac::require_role(&env, &admin, crate::types::Role::EmergencyManager)?;
env.storage().instance().set(&DataKey::Paused, &true);
events::emit_pause_toggled(&env, true);
Ok(())
}
pub fn unpause(env: Env, admin: Address) -> Result<(), ContractError> {
validate_address(&env, &admin)?;
crate::contracts::rbac::require_role(&env, &admin, crate::types::Role::EmergencyManager)?;
env.storage().instance().set(&DataKey::Paused, &false);
events::emit_pause_toggled(&env, false);
Ok(())
}
pub fn is_paused(env: Env) -> bool {
env.storage()
.instance()
.get(&DataKey::Paused)
.unwrap_or(false)
}
pub fn add_guardian(env: Env, admin: Address, guardian: Address) -> Result<(), ContractError> {
validate_address(&env, &admin)?;
validate_address(&env, &guardian)?;
circuit_breaker::require_not_paused(&env)?;
crate::contracts::rbac::require_role(&env, &admin, crate::types::Role::GuardianManager)?;
guardian::add_guardian(&env, admin.clone(), guardian.clone())?;
events::emit_guardian_added(&env, &admin, &guardian);
Ok(())
}
pub fn remove_guardian(
env: Env,
admin: Address,
guardian: Address,
) -> Result<(), ContractError> {
validate_address(&env, &admin)?;
validate_address(&env, &guardian)?;
circuit_breaker::require_not_paused(&env)?;
crate::contracts::rbac::require_role(&env, &admin, crate::types::Role::GuardianManager)?;
guardian::remove_guardian(&env, admin.clone(), guardian.clone())?;
events::emit_guardian_removed(&env, &admin, &guardian);
Ok(())
}
pub fn is_guardian(env: Env, guardian: Address) -> bool {
guardian::is_guardian(&env, &guardian)
}
pub fn set_reputation(
env: Env,
admin: Address,
guardian: Address,
score: u64,
) -> Result<(), ContractError> {
validate_address(&env, &admin)?;
validate_address(&env, &guardian)?;
circuit_breaker::require_not_paused(&env)?;
reputation::set_reputation(&env, admin.clone(), guardian.clone(), score)?;
events::emit_reputation_set(&env, &admin, &guardian, score);
Ok(())
}
pub fn get_reputation(env: Env, guardian: Address) -> Option<u64> {
reputation::get_reputation(&env, &guardian)
}
pub fn calculate_voting_power(env: Env, guardian: Address) -> Option<u64> {
reputation::calculate_voting_power(&env, &guardian)
}
pub fn lock_tokens(env: Env, guardian: Address, amount: i128) -> Result<(), ContractError> {
validate_address(&env, &guardian)?;
logic::lock_tokens(&env, guardian, amount)
}
pub fn request_unlock(env: Env, guardian: Address) -> Result<(), ContractError> {
validate_address(&env, &guardian)?;
logic::request_unlock(&env, guardian)
}
pub fn unlock_tokens(env: Env, guardian: Address) -> Result<(), ContractError> {
validate_address(&env, &guardian)?;
logic::unlock_tokens(&env, guardian)
}
/// Recovers tokens from the contract in emergency situations.
///
/// Note: This function deliberately bypasses the circuit breaker pause gate
/// (`require_not_paused`), as it serves as the recovery mechanism of last resort
/// when normal contract operations are halted or paused. Requires the caller
/// to hold the `EmergencyManager` role.
pub fn emergency_recover(
env: Env,
admin: Address,
recipient: Address,
amount: i128,
) -> Result<(), ContractError> {
validate_address(&env, &admin)?;
validate_address(&env, &recipient)?;
crate::contracts::rbac::require_role(&env, &admin, crate::types::Role::EmergencyManager)?;
logic::emergency_recover(&env, admin, recipient, amount)
}
pub fn resign_guardian(env: Env, guardian: Address) -> Result<(), ContractError> {
validate_address(&env, &guardian)?;
logic::resign_guardian(&env, guardian)
}
pub fn set_weight_threshold(
env: Env,
admin: Address,
threshold: u64,
) -> Result<(), ContractError> {
validate_address(&env, &admin)?;
circuit_breaker::require_not_paused(&env)?;
crate::contracts::rbac::require_role(&env, &admin, crate::types::Role::ConfigManager)?;
env.storage()
.instance()
.set(&DataKey::WeightThreshold, &threshold);
events::emit_threshold_set(&env, &admin, threshold);
Ok(())
}
pub fn get_weight_threshold(env: Env) -> u64 {
env.storage()
.instance()
.get(&DataKey::WeightThreshold)
.unwrap_or(DEFAULT_WEIGHT_THRESHOLD)
}
pub fn set_vault_address(env: Env, admin: Address, vault: Address) {
if validate_address(&env, &admin).is_err() {
panic_with_error!(env, ContractError::InvalidAddress);
}
if validate_address(&env, &vault).is_err() {
panic_with_error!(env, ContractError::InvalidAddress);
}
circuit_breaker::require_not_paused(&env).unwrap();
// Use try-catch pattern via unwrap since this function has no Result return
crate::contracts::rbac::require_role(&env, &admin, crate::types::Role::ConfigManager)
.unwrap();
env.storage().instance().set(&DataKey::VaultAddress, &vault);
events::emit_vault_set(&env, &admin, &vault);
}
pub fn set_fee_bps(env: Env, admin: Address, bps: u32) -> Result<(), ContractError> {
validate_address(&env, &admin)?;
circuit_breaker::require_not_paused(&env)?;
crate::contracts::rbac::require_role(&env, &admin, crate::types::Role::ConfigManager)?;
if bps > 1000 {
return Err(ContractError::InvalidConfig);
}
env.storage().instance().set(&DataKey::FeeBps, &bps);
Ok(())
}
pub fn set_treasury_address(
env: Env,
admin: Address,
treasury: Address,
) -> Result<(), ContractError> {
validate_address(&env, &admin)?;
validate_address(&env, &treasury)?;
circuit_breaker::require_not_paused(&env)?;
crate::contracts::rbac::require_role(&env, &admin, crate::types::Role::ConfigManager)?;
env.storage()
.instance()
.set(&DataKey::TreasuryAddress, &treasury);
Ok(())
}
pub fn register_task(
env: Env,
admin: Address,
task_id: u64,
min_votes_required: u32,
) -> Result<(), ContractError> {
validate_address(&env, &admin)?;
circuit_breaker::require_not_paused(&env)?;
crate::contracts::rbac::require_role(&env, &admin, crate::types::Role::TaskManager)?;
let task_ids = soroban_sdk::vec![&env, task_id];
task::register_tasks(&env, admin, task_ids, min_votes_required)
}
pub fn cancel_task(env: Env, admin: Address, task_id: u64) -> Result<(), ContractError> {
validate_address(&env, &admin)?;
circuit_breaker::require_not_paused(&env)?;
crate::contracts::rbac::require_role(&env, &admin, crate::types::Role::TaskManager)?;
task::cancel_task(&env, admin, task_id)
}
/// Purge a terminal task (done or cancelled) from contract storage.
///
/// Removes the task struct, its voter list, each individual `Voted` record,
/// and the task id from the `AllTasks` index. Reduces on-chain state size
/// and the cost of future `get_snapshot` calls.
///
/// Reverts with `TaskNotFound` if no task exists, `TaskNotTerminal` if the
/// task is still active, and `NotAuthorized` if the caller is not the admin.
pub fn purge_task(env: Env, admin: Address, task_id: u64) -> Result<(), ContractError> {
validate_address(&env, &admin)?;
circuit_breaker::require_not_paused(&env)?;
crate::contracts::rbac::require_role(&env, &admin, crate::types::Role::TaskManager)?;
task::purge_task(&env, admin, task_id)
}
pub fn vote(env: Env, guardian: Address, task_id: u64) -> Result<(), ContractError> {
validate_address(&env, &guardian)?;
logic::process_vote(&env, guardian, task_id)
}
pub fn vote_batch(
env: Env,
guardian: Address,
task_ids: Vec<u64>,
) -> Result<(), ContractError> {
validate_address(&env, &guardian)?;
logic::process_vote_batch(&env, guardian, task_ids)
}
pub fn get_task(env: Env, task_id: u64) -> Option<crate::types::Task> {
task::get_task(&env, task_id)
}
/// Archives a resolved, stale task, moving it from active to archived storage.
///
/// Requires the `TaskManager` role. This was previously permissionless;
/// however, `start_drips_stream` only resolves tasks from active storage
/// (no archived-storage fallback), so an unauthorized early archive could
/// permanently block a task's reward stream from ever starting. Gating
/// this behind `TaskManager`, consistent with `cancel_task`/`purge_task`,
/// prevents that griefing vector.
pub fn archive_task(env: Env, admin: Address, task_id: u64) -> Result<(), ContractError> {
validate_address(&env, &admin)?;
circuit_breaker::require_not_paused(&env)?;
crate::contracts::rbac::require_role(&env, &admin, crate::types::Role::TaskManager)?;
storage::archive_task(&env, task_id)?;
events::emit_task_archived(&env, task_id);
Ok(())
}
pub fn get_archived_task(env: Env, task_id: u64) -> Option<crate::types::Task> {
storage::get_archived_task(&env, task_id)
}
pub fn start_reward_stream(
env: Env,
admin: Address,
drips_address: Address,
contributor: Address,
task_id: u64,
) -> Result<(), ContractError> {
validate_address(&env, &admin)?;
validate_address(&env, &drips_address)?;
validate_address(&env, &contributor)?;
circuit_breaker::require_not_paused(&env)?;
crate::contracts::rbac::require_role(&env, &admin, crate::types::Role::TreasuryManager)?;
let result = drips::start_drips_stream(&env, drips_address, contributor.clone(), task_id);
match &result {
Ok(()) => events::emit_reward_stream_started(&env, task_id, &contributor),
Err(_) => events::emit_reward_stream_failed(&env, task_id, &contributor),
}
result
}
pub fn get_reward_stream(env: Env, task_id: u64) -> Option<RewardStream> {
drips::get_reward_stream(&env, task_id)
}
/// Report an observed failure to the circuit breaker.
///
/// Reporting stays open to any observer, but every report is now
/// **authenticated, rate-limited and quota-capped per address**, and the
/// breaker only auto-pauses once several *independent* reporters agree.
/// This preserves the "any observer can report" design goal while making it
/// impossible for a single address to unilaterally pause the contract.
///
/// See [`crate::circuit_breaker`] for the full trust-model decision record.
///
/// # Errors
/// * `InvalidAddress` — reporter is the zero address or the contract itself.
/// * `UnauthorizedReporter` — trusted-reporters-only mode is enabled and the
/// caller is not a guardian / EmergencyManager / Admin.
/// * `ReportRateLimited` — the caller reported within the cooldown window.
/// * `ReporterQuotaExceeded` — the caller exhausted its per-window quota.
pub fn record_failure(env: Env, reporter: Address) -> Result<(), ContractError> {
validate_address(&env, &reporter)?;
circuit_breaker::record_failure(&env, reporter)
}
/// Current cumulative failure count for the active breaker window.
pub fn get_failure_count(env: Env) -> u32 {
circuit_breaker::failure_count(&env)
}
/// Number of reports the given address contributed to the active window.
pub fn get_reporter_failure_count(env: Env, reporter: Address) -> u32 {
circuit_breaker::reporter_count(&env, &reporter)
}
/// Distinct addresses that have reported failures in the active window.
pub fn get_failure_reporters(env: Env) -> Vec<Address> {
circuit_breaker::failure_reporters(&env)
}
/// Whether failure reporting is currently restricted to trusted monitors.
pub fn is_trusted_reporters_only(env: Env) -> bool {
circuit_breaker::trusted_reporters_only(&env)
}
/// Restrict (or re-open) failure reporting to trusted monitors — registered
/// guardians and `EmergencyManager` / `Admin` role holders.
///
/// Intended as an escape hatch if a Sybil flood of reports is ever observed.
///
/// # Errors
/// * `NotAuthorized` — caller does not hold the `EmergencyManager` role.
pub fn set_trusted_reporters_only(
env: Env,
admin: Address,
enabled: bool,
) -> Result<(), ContractError> {
validate_address(&env, &admin)?;
crate::contracts::rbac::require_role(&env, &admin, crate::types::Role::EmergencyManager)?;
circuit_breaker::set_trusted_reporters_only(&env, enabled);
events::emit_trusted_reporters_only_set(&env, &admin, enabled);
Ok(())
}
pub fn reset_circuit_breaker(env: Env, admin: Address) -> Result<(), ContractError> {
validate_address(&env, &admin)?;
crate::contracts::rbac::require_role(&env, &admin, crate::types::Role::EmergencyManager)?;
circuit_breaker::reset(&env, admin.clone())?;
events::emit_circuit_breaker_reset(&env, &admin);
Ok(())
}
pub fn get_estimated_cost(_env: Env, op: crate::types::Operation) -> u64 {
crate::gas::get_estimated_cost(op)
}
pub fn upgrade_contract(env: Env, admin: Address, new_wasm_hash: BytesN<32>) {
if validate_address(&env, &admin).is_err() {
panic_with_error!(env, ContractError::InvalidAddress);
}
crate::contracts::rbac::require_role(&env, &admin, crate::types::Role::Admin).unwrap();
env.deployer()
.update_current_contract_wasm(new_wasm_hash.clone());
events::emit_contract_upgraded(&env, &admin, &new_wasm_hash);
}
// ─── Multi-sig upgrade management ────────────────────────────────────────
/// Configure the list of authorized upgrade signers and the required quorum.
///
/// Only the contract admin may call this function. It overwrites any previous
/// multi-sig configuration and clears any pending upgrade proposal.
///
/// # Arguments
/// * `signers` — List of addresses authorized to propose/approve upgrades.
/// * `threshold` — Minimum number of approvals required to execute an upgrade.
///
/// # Errors
/// * `NotAuthorized` — Caller is not the contract admin.
/// * `InvalidUpgradeConfig` — Threshold is zero or exceeds the number of signers.
pub fn set_upgrade_signers(
env: Env,
admin: Address,
signers: Vec<Address>,
threshold: u32,
) -> Result<(), ContractError> {
validate_address(&env, &admin)?;
for signer in signers.iter() {
validate_address(&env, &signer)?;
}
crate::contracts::rbac::require_role(&env, &admin, crate::types::Role::Admin)?;
if threshold == 0 || threshold > signers.len() || !is_strictly_sorted_addresses(&signers) {
return Err(ContractError::InvalidUpgradeConfig);
}
// Clear any pending upgrade when reconfiguring
env.storage()
.instance()
.remove(&DataKey::PendingUpgradeWasm);
env.storage()
.instance()
.remove(&DataKey::PendingUpgradeApprovals);
env.storage()
.instance()
.set(&DataKey::UpgradeSigners, &signers);
env.storage()
.instance()
.set(&DataKey::UpgradeThreshold, &threshold);
events::emit_upgrade_signers_set(&env, signers.len(), threshold);
Ok(())
}
/// Returns the currently configured list of authorized upgrade signers.
pub fn get_upgrade_signers(env: Env) -> Vec<Address> {
env.storage()
.instance()
.get(&DataKey::UpgradeSigners)
.unwrap_or(Vec::new(&env))
}
/// Returns the minimum number of upgrade approvals required (quorum).
pub fn get_upgrade_threshold(env: Env) -> u32 {
env.storage()
.instance()
.get(&DataKey::UpgradeThreshold)
.unwrap_or(0u32)
}
/// Propose a new upgrade WASM hash as an upgrade signer.
///
/// If no pending upgrade exists, creates one and records the caller's
/// approval. The caller is added to the approvals list.
///
/// If a pending upgrade exists with a **different** WASM hash, the call
/// reverts. If the hash matches, the caller is added to the approval list
/// (same effect as calling `approve_upgrade`).
///
/// # Errors
/// * `NotUpgradeSigner` — Caller is not in the authorized signers list.
/// * `NoPendingUpgrade` — (not applicable; propose creates one).
/// * `AlreadyApproved` — Caller has already approved.
pub fn propose_upgrade(
env: Env,
signer: Address,
new_wasm_hash: BytesN<32>,
) -> Result<(), ContractError> {
validate_address(&env, &signer)?;
signer.require_auth();
// Verify signer is authorized
let signers: Vec<Address> = env
.storage()
.instance()
.get(&DataKey::UpgradeSigners)
.ok_or(ContractError::NotUpgradeSigner)?;
if !signers.contains(signer.clone()) {
return Err(ContractError::NotUpgradeSigner);
}
// Check if there's an existing pending upgrade
if let Some(existing_hash) = env
.storage()
.instance()
.get::<_, BytesN<32>>(&DataKey::PendingUpgradeWasm)
{
// If hashes differ, reject
if existing_hash != new_wasm_hash {
return Err(ContractError::InvalidUpgradeConfig);
}
// Hash matches — just add approval (same as approve_upgrade but without require_auth)
let mut approvals: Vec<Address> = env
.storage()
.instance()
.get(&DataKey::PendingUpgradeApprovals)
.unwrap_or(Vec::new(&env));
if approvals.contains(signer.clone()) {
return Err(ContractError::AlreadyApproved);
}
if let Some(previous) = approvals.last() {
if previous >= signer {
return Err(ContractError::InvalidUpgradeConfig);
}
}
approvals.push_back(signer.clone());
env.storage()
.instance()
.set(&DataKey::PendingUpgradeApprovals, &approvals);
let threshold: u32 = env
.storage()
.instance()
.get(&DataKey::UpgradeThreshold)
.unwrap_or(0u32);
events::emit_upgrade_approved(&env, &signer, approvals.len(), threshold);
return Ok(());
}
// No pending upgrade — create one
env.storage()
.instance()
.set(&DataKey::PendingUpgradeWasm, &new_wasm_hash);
// Record the first approval
let mut approvals: Vec<Address> = Vec::new(&env);
approvals.push_back(signer.clone());
env.storage()
.instance()
.set(&DataKey::PendingUpgradeApprovals, &approvals);
events::emit_upgrade_proposed(&env, &signer);
let threshold: u32 = env
.storage()
.instance()
.get(&DataKey::UpgradeThreshold)
.unwrap_or(0u32);
events::emit_upgrade_approved(&env, &signer, approvals.len(), threshold);
Ok(())
}
/// Approve a pending upgrade as an authorized signer.
///
/// A pending upgrade must exist. If the caller has already approved,
/// the call reverts with `AlreadyApproved`.
///
/// # Errors
/// * `NotUpgradeSigner` — Caller is not in the authorized signers list.
/// * `NoPendingUpgrade` — No upgrade has been proposed.
/// * `AlreadyApproved` — Caller has already approved this proposal.
pub fn approve_upgrade(env: Env, signer: Address) -> Result<(), ContractError> {
validate_address(&env, &signer)?;
signer.require_auth();
// Verify signer is authorized
let signers: Vec<Address> = env
.storage()
.instance()
.get(&DataKey::UpgradeSigners)
.ok_or(ContractError::NotUpgradeSigner)?;
if !signers.contains(signer.clone()) {
return Err(ContractError::NotUpgradeSigner);
}
// Verify there is a pending upgrade
if !env.storage().instance().has(&DataKey::PendingUpgradeWasm) {
return Err(ContractError::NoPendingUpgrade);
}
// Verify caller hasn't already approved
let mut approvals: Vec<Address> = env
.storage()
.instance()
.get(&DataKey::PendingUpgradeApprovals)
.unwrap_or(Vec::new(&env));
if approvals.contains(signer.clone()) {
return Err(ContractError::AlreadyApproved);
}
if let Some(previous) = approvals.last() {
if previous >= signer {
return Err(ContractError::InvalidUpgradeConfig);
}
}
approvals.push_back(signer.clone());
env.storage()
.instance()
.set(&DataKey::PendingUpgradeApprovals, &approvals);
let threshold: u32 = env
.storage()
.instance()
.get(&DataKey::UpgradeThreshold)
.unwrap_or(0u32);
events::emit_upgrade_approved(&env, &signer, approvals.len(), threshold);
Ok(())
}
/// Execute the pending upgrade once the approval quorum is met.
///
/// # Errors
/// * `NoPendingUpgrade` — No upgrade has been proposed.
/// * `UpgradeThresholdNotMet` — Not enough approvals yet.
pub fn execute_upgrade(env: Env) -> Result<(), ContractError> {
// Check pending proposal exists
let wasm_hash: BytesN<32> = env
.storage()
.instance()
.get(&DataKey::PendingUpgradeWasm)
.ok_or(ContractError::NoPendingUpgrade)?;
let approvals: Vec<Address> = env
.storage()
.instance()
.get(&DataKey::PendingUpgradeApprovals)
.ok_or(ContractError::NoPendingUpgrade)?;
let threshold: u32 = env
.storage()
.instance()
.get(&DataKey::UpgradeThreshold)
.ok_or(ContractError::InvalidUpgradeConfig)?;
if approvals.len() < threshold {
return Err(ContractError::UpgradeThresholdNotMet);
}
// Clean up pending state BEFORE upgrade (after upgrade the contract
// code is replaced and further cleanup may not run).
env.storage()
.instance()
.remove(&DataKey::PendingUpgradeWasm);
env.storage()
.instance()
.remove(&DataKey::PendingUpgradeApprovals);
events::emit_upgrade_executed(&env);
// Perform the actual WASM upgrade
env.deployer().update_current_contract_wasm(wasm_hash);
Ok(())
}
/// Cancel a pending upgrade. Only the contract admin may call this.
///
/// # Errors
/// * `NotAuthorized` — Caller is not the contract admin.
/// * `NoPendingUpgrade` — No upgrade has been proposed.
pub fn cancel_upgrade(env: Env, admin: Address) -> Result<(), ContractError> {
validate_address(&env, &admin)?;
crate::contracts::rbac::require_role(&env, &admin, crate::types::Role::Admin)?;
if !env.storage().instance().has(&DataKey::PendingUpgradeWasm) {
return Err(ContractError::NoPendingUpgrade);
}
env.storage()
.instance()
.remove(&DataKey::PendingUpgradeWasm);
env.storage()
.instance()
.remove(&DataKey::PendingUpgradeApprovals);
events::emit_upgrade_cancelled(&env);
Ok(())
}
/// Builds the full contract snapshot atomically. Reverts with
/// `SnapshotTooLarge` once any tracked collection (guardians, tasks,
/// reward streams) exceeds `MAX_SNAPSHOT_COLLECTION_SIZE` — at that point
/// use `get_snapshot_meta` plus the paginated `*_page` calls instead.
pub fn get_snapshot(env: Env) -> Result<Snapshot, ContractError> {
logic::get_snapshot(&env)
}
pub fn record_snapshot(env: Env) -> Result<(), ContractError> {
circuit_breaker::require_not_paused(&env)?;
logic::record_snapshot(&env)
}
/// O(1) snapshot header (paused/admin/thresholds/addresses) plus the
/// current guardian/task/reward-stream counts. Always safe to call.
pub fn get_snapshot_meta(env: Env) -> SnapshotMeta {
logic::get_snapshot_meta(&env)
}
/// Returns a bounded page of guardians (with status + reputation)
/// starting at `offset`. `limit` is capped server-side regardless of the
/// value passed in. Reads `O(limit)` entries, not `O(total guardian
/// count)` — stays cheaply invokable at guardian counts where
/// `get_snapshot` is capped out entirely.
pub fn get_guardians_page(env: Env, offset: u32, limit: u32) -> Vec<GuardianEntry> {
logic::get_guardians_page(&env, offset, limit)
}
/// Returns a bounded page of tasks starting at `offset`. Reads `O(limit)`
/// entries, not `O(total task count)`.
pub fn get_tasks_page(env: Env, offset: u32, limit: u32) -> Vec<Task> {
logic::get_tasks_page(&env, offset, limit)
}
/// Returns a bounded page of reward streams starting at `offset`.
pub fn get_reward_streams_page(env: Env, offset: u32, limit: u32) -> Vec<RewardStream> {
logic::get_reward_streams_page(&env, offset, limit)
}
pub fn get_snapshot_history(env: Env) -> soroban_sdk::Vec<u64> {
env.storage()
.instance()
.get(&DataKey::AllSnapshots)
.unwrap_or(soroban_sdk::Vec::new(&env))
}
pub fn get_snapshot_at(env: Env, timestamp: u64) -> Result<Snapshot, ContractError> {
env.storage()
.instance()
.get(&DataKey::Snapshot(timestamp))
.ok_or(ContractError::SnapshotNotFound)
}
pub fn get_withdrawal_timelock(env: Env, guardian: Address) -> Option<u64> {
env.storage()
.instance()
.get(&DataKey::WithdrawalTimelock(guardian))
}
pub fn batch_execute(
env: Env,
calls: soroban_sdk::Vec<BatchCall>,
) -> Result<(), ContractError> {
for call in calls.iter() {
match call {
BatchCall::RegisterTask(admin, task_id, min_votes_required) => {
Self::register_task(env.clone(), admin, task_id, min_votes_required)?
}
BatchCall::CancelTask(admin, task_id) => {
Self::cancel_task(env.clone(), admin, task_id)?
}
BatchCall::Vote(guardian, task_id) => Self::vote(env.clone(), guardian, task_id)?,
BatchCall::AddGuardian(admin, guardian) => {
Self::add_guardian(env.clone(), admin, guardian)?
}
BatchCall::RemoveGuardian(admin, guardian) => {
Self::remove_guardian(env.clone(), admin, guardian)?
}
BatchCall::SetReputation(admin, guardian, score) => {
Self::set_reputation(env.clone(), admin, guardian, score)?
}
BatchCall::LockTokens(guardian, amount) => {
Self::lock_tokens(env.clone(), guardian, amount)?
}
BatchCall::RequestUnlock(guardian) => Self::request_unlock(env.clone(), guardian)?,
BatchCall::UnlockTokens(guardian) => Self::unlock_tokens(env.clone(), guardian)?,
BatchCall::ResignGuardian(guardian) => {
Self::resign_guardian(env.clone(), guardian)?
}
BatchCall::SetWeightThreshold(admin, threshold) => {
Self::set_weight_threshold(env.clone(), admin, threshold)?
}
BatchCall::SetVaultAddress(admin, vault) => {
Self::set_vault_address(env.clone(), admin, vault)
}
BatchCall::SetUpgradeSigners(admin, signers, threshold) => {
Self::set_upgrade_signers(env.clone(), admin, signers, threshold)?
}
BatchCall::ProposeUpgrade(signer, hash) => {
Self::propose_upgrade(env.clone(), signer, hash)?
}
BatchCall::ApproveUpgrade(signer) => Self::approve_upgrade(env.clone(), signer)?,
BatchCall::ExecuteUpgrade(_signer) => Self::execute_upgrade(env.clone())?,
BatchCall::CancelUpgrade(admin) => Self::cancel_upgrade(env.clone(), admin)?,
BatchCall::StartRewardStream(admin, drips, contributor, task_id) => {
Self::start_reward_stream(env.clone(), admin, drips, contributor, task_id)?
}
BatchCall::TogglePause(admin) => Self::toggle_pause(env.clone(), admin)?,
BatchCall::Pause(admin) => Self::pause(env.clone(), admin)?,
BatchCall::Unpause(admin) => Self::unpause(env.clone(), admin)?,
BatchCall::RecordFailure(reporter) => Self::record_failure(env.clone(), reporter)?,
BatchCall::ResetCircuitBreaker(admin) => {
Self::reset_circuit_breaker(env.clone(), admin)?;
}
BatchCall::EmergencyRecover(admin, recipient, amount) => {
Self::emergency_recover(env.clone(), admin, recipient, amount)?
}
BatchCall::SetFeeBps(admin, bps) => Self::set_fee_bps(env.clone(), admin, bps)?,
BatchCall::SetTreasuryAddress(admin, treasury) => {
Self::set_treasury_address(env.clone(), admin, treasury)?
}
}
}
Ok(())
}
// ─── Role-based access control ──────────────────────────────────────
/// Grant a role to a target address. Only callable by Admin role holders.
///
/// # Errors
/// * `NotAuthorized` — Caller does not hold the Admin role.
pub fn grant_role(
env: Env,
caller: Address,
target: Address,
role: crate::types::Role,
) -> Result<(), ContractError> {
validate_address(&env, &caller)?;
validate_address(&env, &target)?;
crate::contracts::rbac::grant_role_internal(&env, &caller, &target, role)
}
/// Revoke a role from a target address. Only callable by Admin role holders.
///
/// # Errors
/// * `NotAuthorized` — Caller does not hold the Admin role.
/// * `LastAdminRemovalBlocked` — Cannot revoke the last remaining Admin role.
pub fn revoke_role(
env: Env,
caller: Address,
target: Address,
role: crate::types::Role,
) -> Result<(), ContractError> {
validate_address(&env, &caller)?;
validate_address(&env, &target)?;
crate::contracts::rbac::revoke_role_internal(&env, &caller, &target, role)
}
/// Check whether an address holds a specific role.
pub fn has_role(env: Env, address: Address, role: crate::types::Role) -> bool {
crate::contracts::rbac::has_role(&env, &address, role)
}
/// Returns the currently recorded storage version.
pub fn get_storage_version(env: Env) -> u32 {
crate::migrate::get_version(&env)
}
/// Run the storage migration to bring the storage schema to the latest version.
/// Only contract admin can trigger migration.
pub fn migrate_storage(env: Env, admin: Address) -> Result<(), ContractError> {
validate_address(&env, &admin)?;
crate::contracts::rbac::require_role(&env, &admin, crate::types::Role::Admin)?;
crate::migrate::migrate(&env)
}
}