forked from ussyalfaks/Grainlify-Stellar-Contracts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
4426 lines (3834 loc) · 159 KB
/
Copy pathlib.rs
File metadata and controls
4426 lines (3834 loc) · 159 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
#![no_std]
//! # Program Escrow Smart Contract
//!
//! A secure escrow system for managing hackathon and program prize pools on Stellar.
//! This contract enables organizers to lock funds and distribute prizes to multiple
//! winners through secure, auditable batch payouts.
//!
//! ## Overview
//!
//! The Program Escrow contract manages the complete lifecycle of hackathon/program prizes:
//! 1. **Initialization**: Set up program with authorized payout controller
//! 2. **Fund Locking**: Lock prize pool funds in escrow
//! 3. **Batch Payouts**: Distribute prizes to multiple winners simultaneously
//! 4. **Single Payouts**: Distribute individual prizes
//! 5. **Tracking**: Maintain complete payout history and balance tracking
//!
//! ## Architecture
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────────┐
//! │ Program Escrow Architecture │
//! ├─────────────────────────────────────────────────────────────────┤
//! │ │
//! │ ┌──────────────┐ │
//! │ │ Organizer │ │
//! │ └──────┬───────┘ │
//! │ │ │
//! │ │ 1. init_program() │
//! │ ▼ │
//! │ ┌──────────────────┐ │
//! │ │ Program Created │ │
//! │ └────────┬─────────┘ │
//! │ │ │
//! │ │ 2. lock_program_funds() │
//! │ ▼ │
//! │ ┌──────────────────┐ │
//! │ │ Funds Locked │ │
//! │ │ (Prize Pool) │ │
//! │ └────────┬─────────┘ │
//! │ │ │
//! │ │ 3. Hackathon happens... │
//! │ │ │
//! │ ┌────────▼─────────┐ │
//! │ │ Authorized │ │
//! │ │ Payout Key │ │
//! │ └────────┬─────────┘ │
//! │ │ │
//! │ ┌──────┴───────┐ │
//! │ │ │ │
//! │ ▼ ▼ │
//! │ batch_payout() single_payout() │
//! │ │ │ │
//! │ ▼ ▼ │
//! │ ┌─────────────────────────┐ │
//! │ │ Winner 1, 2, 3, ... │ │
//! │ └─────────────────────────┘ │
//! │ │
//! │ Storage: │
//! │ ┌──────────────────────────────────────────┐ │
//! │ │ ProgramData: │ │
//! │ │ - program_id │ │
//! │ │ - total_funds │ │
//! │ │ - remaining_balance │ │
//! │ │ - authorized_payout_key │ │
//! │ │ - payout_history: [PayoutRecord] │ │
//! │ │ - token_address │ │
//! │ └──────────────────────────────────────────┘ │
//! └─────────────────────────────────────────────────────────────────┘
//! ```
//!
//! ## Security Model
//!
//! ### Trust Assumptions
//! - **Authorized Payout Key**: Trusted backend service that triggers payouts
//! - **Organizer**: Trusted to lock appropriate prize amounts
//! - **Token Contract**: Standard Stellar Asset Contract (SAC)
//! - **Contract**: Trustless; operates according to programmed rules
//!
//! ### Key Security Features
//! 1. **Single Initialization**: Prevents program re-configuration
//! 2. **Authorization Checks**: Only authorized key can trigger payouts
//! 3. **Balance Validation**: Prevents overdrafts
//! 4. **Atomic Transfers**: All-or-nothing batch operations
//! 5. **Complete Audit Trail**: Full payout history tracking
//! 6. **Overflow Protection**: Safe arithmetic for all calculations
//!
//! ## Usage Example
//!
//! ```rust
//! use soroban_sdk::{Address, Env, String, vec};
//!
//! // 1. Initialize program (one-time setup)
//! let program_id = String::from_str(&env, "Hackathon2024");
//! let backend = Address::from_string("GBACKEND...");
//! let usdc_token = Address::from_string("CUSDC...");
//!
//! let program = escrow_client.init_program(
//! &program_id,
//! &backend,
//! &usdc_token
//! );
//!
//! // 2. Lock prize pool (10,000 USDC)
//! let prize_pool = 10_000_0000000; // 10,000 USDC (7 decimals)
//! escrow_client.lock_program_funds(&authorized_key, &prize_pool);
//!
//! // 3. After hackathon, distribute prizes
//! let winners = vec![
//! &env,
//! Address::from_string("GWINNER1..."),
//! Address::from_string("GWINNER2..."),
//! Address::from_string("GWINNER3..."),
//! ];
//!
//! let prizes = vec![
//! &env,
//! 5_000_0000000, // 1st place: 5,000 USDC
//! 3_000_0000000, // 2nd place: 3,000 USDC
//! 2_000_0000000, // 3rd place: 2,000 USDC
//! ];
//!
//! escrow_client.batch_payout(&winners, &prizes);
//! ```
//!
//! ## Event System
//!
//! The contract emits events for all major operations:
//! - `ProgramInit`: Program initialization
//! - `FundsLocked`: Prize funds locked
//! - `BatchPayout`: Multiple prizes distributed
//! - `Payout`: Single prize distributed
//!
//! ## Best Practices
//!
//! 1. **Verify Winners**: Confirm winner addresses off-chain before payout
//! 2. **Test Payouts**: Use testnet for testing prize distributions
//! 3. **Secure Backend**: Protect authorized payout key with HSM/multi-sig
//! 4. **Audit History**: Review payout history before each distribution
//! 5. **Balance Checks**: Verify remaining balance matches expectations
//! 6. **Token Approval**: Ensure contract has token allowance before locking funds
// ── Step 1: Add module declarations near the top of lib.rs ──────────────
// (after `mod anti_abuse;` and before the contract struct)
mod error_recovery;
mod governance_integration;
pub mod monitoring;
mod reentrancy_guard;
// ==================== ANTI-ABUSE MODULE ====================
mod anti_abuse {
use soroban_sdk::{contracttype, symbol_short, Address, Env};
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RateLimitState {
pub last_operation_timestamp: u64,
pub window_start_timestamp: u64,
pub operation_count: u32,
}
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum RateLimitKey {
State(Address),
Whitelist(Address),
}
pub fn is_whitelisted(env: &Env, address: &Address) -> bool {
env.storage()
.instance()
.has(&RateLimitKey::Whitelist(address.clone()))
}
pub fn set_whitelist(env: &Env, address: &Address, whitelisted: bool) {
if whitelisted {
env.storage()
.instance()
.set(&RateLimitKey::Whitelist(address.clone()), &true);
} else {
env.storage()
.instance()
.remove(&RateLimitKey::Whitelist(address.clone()));
}
}
pub fn check_rate_limit(
env: &Env,
address: &Address,
window_size: u64,
max_operations: u32,
cooldown_period: u64,
) {
if is_whitelisted(env, address) {
return;
}
let now = env.ledger().timestamp();
let key = RateLimitKey::State(address.clone());
let mut state: RateLimitState =
env.storage()
.persistent()
.get(&key)
.unwrap_or(RateLimitState {
last_operation_timestamp: 0,
window_start_timestamp: now,
operation_count: 0,
});
// 1. Cooldown check
if state.last_operation_timestamp > 0
&& now
< state
.last_operation_timestamp
.saturating_add(cooldown_period)
{
env.events().publish(
(symbol_short!("abuse"), symbol_short!("cooldown")),
(address.clone(), now),
);
panic!("Operation in cooldown period");
}
// 2. Window check
if now >= state.window_start_timestamp.saturating_add(window_size) {
// New window
state.window_start_timestamp = now;
state.operation_count = 1;
} else {
// Same window
if state.operation_count >= max_operations {
env.events().publish(
(symbol_short!("abuse"), symbol_short!("limit")),
(address.clone(), now),
);
panic!("Rate limit exceeded");
}
state.operation_count += 1;
}
state.last_operation_timestamp = now;
env.storage().persistent().set(&key, &state);
// Extend TTL for state (approx 1 day)
env.storage().persistent().extend_ttl(&key, 17280, 17280);
}
}
// ==================== END ANTI-ABUSE MODULE ====================
#[cfg(test)]
mod error_recovery_tests;
#[cfg(test)]
mod reentrancy_tests;
#[cfg(test)]
mod test_admin_bootstrap;
#[cfg(test)]
mod test_monitoring;
#[cfg(test)]
mod test_dispute_resolution;
#[cfg(test)]
mod reentrancy_guard_standalone_test;
#[cfg(test)]
mod malicious_reentrant;
#[cfg(test)]
mod test_granular_pause;
#[cfg(test)]
mod test_lifecycle;
#[cfg(test)]
mod test_schedule_pagination;
#[cfg(test)]
mod budget_profiling_tests;
#[cfg(test)]
mod test_analytics_events;
#[cfg(test)]
mod test_governance_integration;
use soroban_sdk::{
contract, contracterror, contractimpl, contracttype, symbol_short, token, vec, Address, BytesN,
Env, String, Symbol, Vec,
};
// Event types
const PROGRAM_INITIALIZED: Symbol = symbol_short!("PrgInit");
const FUNDS_LOCKED: Symbol = symbol_short!("FndsLock");
const BATCH_PAYOUT: Symbol = symbol_short!("BatchPay");
const PAYOUT: Symbol = symbol_short!("Payout");
const DISPUTE_OPENED: Symbol = symbol_short!("DispOpen");
const DISPUTE_RESOLVED: Symbol = symbol_short!("DispRes");
const DISPUTE_CANCELLED: Symbol = symbol_short!("DispCanc");
const EVENT_VERSION_V2: u32 = 2;
const PAUSE_STATE_CHANGED: Symbol = symbol_short!("PauseSt");
const UPGRADE_EXECUTED: Symbol = symbol_short!("UpgExec");
const AGGREGATE_STATS: Symbol = symbol_short!("AggStats");
const LARGE_PAYOUT: Symbol = symbol_short!("LrgPay");
const SCHEDULE_TRIGGERED: Symbol = symbol_short!("SchedTrg");
const WHITELIST_CHANGED: Symbol = symbol_short!("WlChange");
const WHITELIST_ENFORCEMENT_CHANGED: Symbol = symbol_short!("WlEnfChg");
// Storage keys
const PROGRAM_DATA: Symbol = symbol_short!("ProgData");
const SCHEDULES: Symbol = symbol_short!("Scheds");
const RELEASE_HISTORY: Symbol = symbol_short!("RelHist");
const NEXT_SCHEDULE_ID: Symbol = symbol_short!("NxtSched");
const FEE_CONFIG: Symbol = symbol_short!("FeeConf");
const FUND_CAP_CONFIG: Symbol = symbol_short!("FnCapCfg");
const BASIS_POINTS: i128 = 10_000;
/// Threshold for bumping persistent storage TTL (approx. 1 day on 5s ledgers).
const PERSISTENT_TTL_THRESHOLD: u32 = 17_280;
/// Extension horizon for persistent storage TTL (approx. 30 days on 5s ledgers).
/// This ensures long-lived release schedules and history remain accessible.
const PERSISTENT_TTL_EXTEND_TO: u32 = 518_400;
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PayoutRecord {
pub recipient: Address,
pub amount: i128,
pub timestamp: u64,
}
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ProgramInitializedEvent {
pub version: u32,
pub program_id: String,
pub authorized_payout_key: Address,
pub token_address: Address,
pub total_funds: i128,
}
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FundsLockedEvent {
pub version: u32,
pub program_id: String,
pub amount: i128,
pub remaining_balance: i128,
}
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BatchPayoutEvent {
pub version: u32,
pub program_id: String,
pub recipient_count: u32,
pub total_amount: i128,
pub remaining_balance: i128,
pub gas_proxy_transfer_ops: u32,
pub gas_proxy_history_appends: u32,
pub gas_proxy_storage_reads: u32,
pub gas_proxy_storage_writes: u32,
pub gas_proxy_events_emitted: u32,
}
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PayoutEvent {
pub version: u32,
pub program_id: String,
pub recipient: Address,
pub amount: i128,
pub remaining_balance: i128,
}
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AggregateStatsEvent {
pub version: u32,
pub program_id: String,
pub total_funds: i128,
pub remaining_balance: i128,
pub total_paid_out: i128,
pub payout_count: u32,
pub scheduled_count: u32,
}
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LargePayoutEvent {
pub version: u32,
pub program_id: String,
pub recipient: Address,
pub amount: i128,
pub threshold: i128,
}
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct WhitelistChangedEvent {
pub address: Address,
pub whitelisted: bool,
}
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct WhitelistEnforcementChangedEvent {
pub enabled: bool,
}
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ScheduleTriggeredEvent {
pub version: u32,
pub program_id: String,
pub schedule_id: u64,
pub recipient: Address,
pub amount: i128,
pub trigger_type: ReleaseType,
}
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ProgramData {
pub program_id: String,
pub total_funds: i128,
pub remaining_balance: i128,
pub authorized_payout_key: Address,
pub payout_history: Vec<PayoutRecord>,
pub token_address: Address, // Token contract address for transfers
}
/// Storage key type for individual programs
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum DataKey {
Admin, // Contract Admin
ReleaseSchedule(String, u64), // program_id, schedule_id -> ProgramReleaseSchedule
ReleaseHistory(String), // program_id -> Vec<ProgramReleaseHistory>
NextScheduleId(String), // program_id -> next schedule_id
PayoutApproval(String, Address), // program_id, recipient -> PayoutApproval
PendingClaim(String, u64), // (program_id, schedule_id) -> ClaimRecord
ClaimWindow, // u64 seconds (global config)
PauseFlags, // PauseFlags struct
RateLimitConfig, // RateLimitConfig struct
FeeConfig, // FeeConfig struct
Dispute, // DisputeRecord (global program-level dispute)
RecipientDispute(Address), // recipient -> DisputeRecord
ScheduleDispute(u64), // schedule_id -> DisputeRecord
Whitelist(Address), // Address -> bool (whitelisted flag)
WhitelistEnforced, // bool (enforcement flag)
PendingAdmin, // Address proposed via propose_admin, awaiting accept_admin
}
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PauseFlags {
pub lock_paused: bool,
pub release_paused: bool,
pub refund_paused: bool,
}
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PauseStateChanged {
pub operation: Symbol,
pub paused: bool,
pub admin: Address,
}
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct UpgradeExecutedEvent {
pub version: u32,
pub wasm_hash: BytesN<32>,
pub admin: Address,
}
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RateLimitConfig {
pub window_size: u64,
pub max_operations: u32,
pub cooldown_period: u64,
}
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FeeConfig {
pub lock_fee_rate: i128,
pub payout_fee_rate: i128,
pub fee_recipient: Address,
pub fee_enabled: bool,
}
/// Admin-configurable caps for fund locking.
/// When set, `lock_program_funds` rejects amounts that would exceed either cap.
/// Default: no cap (backward-compatible).
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FundCapConfig {
/// Maximum total funds allowed across all lock operations (None = no cap).
pub max_total_funds: Option<i128>,
/// Maximum amount allowed for a single lock operation (None = no cap).
pub max_single_lock: Option<i128>,
}
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Analytics {
pub total_locked: i128,
pub total_released: i128,
pub total_payouts: u32,
pub active_programs: u32,
pub operation_count: u32,
}
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ProgramReleaseSchedule {
pub schedule_id: u64,
pub recipient: Address,
pub amount: i128,
pub release_timestamp: u64,
pub released: bool,
pub released_at: Option<u64>,
pub released_by: Option<Address>,
}
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ReleaseType {
Manual,
Automatic,
Oracle,
}
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ProgramReleaseHistory {
pub schedule_id: u64,
pub recipient: Address,
pub amount: i128,
pub released_at: u64,
pub release_type: ReleaseType,
}
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ProgramAggregateStats {
pub total_funds: i128,
pub remaining_balance: i128,
pub total_paid_out: i128,
pub payout_count: u32,
pub scheduled_count: u32,
pub released_count: u32,
pub authorized_payout_key: Address,
pub payout_history: Vec<PayoutRecord>,
pub token_address: Address,
}
/// Maximum number of items per batch (used by `batch_payout` and
/// `trigger_program_releases` to bound per-invocation work).
pub const MAX_BATCH_SIZE: u32 = 100;
/// Maximum number of schedules returned by one public query invocation.
pub const MAX_QUERY_LIMIT: u32 = 100;
// ── Dispute Resolution Types ──────────────────────────────────────────────
/// Status of a program-level dispute.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum DisputeStatus {
None,
Open,
Resolved,
Cancelled,
}
/// Scope for a dispute halt.
///
/// `Global` preserves the original program-wide dispute behavior. `Recipient`
/// blocks direct payouts and releases for one recipient, while `Schedule`
/// blocks only one release schedule.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum DisputeScope {
Global,
Recipient(Address),
Schedule(u64),
}
/// Record stored on-chain for an active or historical dispute.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DisputeRecord {
pub opened_by: Address,
pub opened_at: u64,
pub reason: String,
pub status: DisputeStatus,
pub resolved_by: Option<Address>,
pub resolved_at: Option<u64>,
}
// ── Dispute Event Types ───────────────────────────────────────────────────
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DisputeOpenedEvent {
pub version: u32,
pub program_id: String,
pub scope: DisputeScope,
pub opened_by: Address,
pub reason: String,
pub timestamp: u64,
}
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DisputeResolvedEvent {
pub version: u32,
pub program_id: String,
pub scope: DisputeScope,
pub resolved_by: Address,
pub timestamp: u64,
}
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DisputeCancelledEvent {
pub version: u32,
pub program_id: String,
pub scope: DisputeScope,
pub cancelled_by: Address,
pub timestamp: u64,
}
#[contracterror]
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
#[repr(u32)]
pub enum Error {
/// Governance contract version is below the minimum required for admin operations.
GovernanceVersionTooLow = 4,
/// large-payout threshold_bps exceeds 10_000 (100%).
InvalidThresholdBps = 5,
/// Governance proposal is not in an executable state: pending, rejected,
/// missing, delayed, vetoed/cancelled, or already executed.
GovernanceProposalNotExecutable = 6,
/// The requested WASM hash has no executed, post-delay governance
/// proposal approving it (or no governance contract is configured at
/// all — upgrades fail closed, they are never permitted by default).
UpgradeNotApproved = 7,
/// The requested migration-wrapper program ID does not match this instance.
ProgramIdMismatch = 8,
}
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PayoutApproval {
pub program_id: String,
pub recipient: Address,
pub amount: i128,
pub approvals: Vec<Address>,
pub total_paid_out: i128,
pub payout_count: u32,
pub scheduled_count: u32,
pub released_count: u32,
}
#[contract]
pub struct ProgramEscrowContract;
#[contractimpl]
impl ProgramEscrowContract {
/// Initialize a new program escrow
///
/// # Arguments
/// * `program_id` - Unique identifier for the program/hackathon
/// * `authorized_payout_key` - Address authorized to trigger payouts (backend)
/// * `token_address` - Address of the token contract to use for transfers
///
/// # Returns
/// The initialized ProgramData
pub fn init_program(
env: Env,
program_id: String,
authorized_payout_key: Address,
token_address: Address,
) -> ProgramData {
let start = env.ledger().timestamp();
let res = Self::initialize_program(
env.clone(),
program_id,
authorized_payout_key.clone(),
token_address,
);
monitoring::track_operation(&env, symbol_short!("init"), authorized_payout_key, true);
monitoring::emit_performance(
&env,
symbol_short!("init"),
env.ledger().timestamp().saturating_sub(start),
);
res
}
pub fn initialize_program(
env: Env,
program_id: String,
authorized_payout_key: Address,
token_address: Address,
) -> ProgramData {
// Check if program already exists
if env.storage().persistent().has(&PROGRAM_DATA) {
Self::bump_persistent_symbol_ttl(&env, &PROGRAM_DATA);
panic!("Program already initialized");
}
let program_data = ProgramData {
program_id: program_id.clone(),
total_funds: 0,
remaining_balance: 0,
authorized_payout_key: authorized_payout_key.clone(),
payout_history: vec![&env],
token_address: token_address.clone(),
};
// Store program data
env.storage().persistent().set(&PROGRAM_DATA, &program_data);
Self::bump_persistent_symbol_ttl(&env, &PROGRAM_DATA);
env.storage()
.persistent()
.set(&SCHEDULES, &Vec::<ProgramReleaseSchedule>::new(&env));
Self::bump_persistent_symbol_ttl(&env, &SCHEDULES);
env.storage()
.persistent()
.set(&RELEASE_HISTORY, &Vec::<ProgramReleaseHistory>::new(&env));
Self::bump_persistent_symbol_ttl(&env, &RELEASE_HISTORY);
env.storage().instance().set(&NEXT_SCHEDULE_ID, &1_u64);
Self::bump_instance_ttl(&env);
// Emit ProgramInitialized event
env.events().publish(
(PROGRAM_INITIALIZED,),
ProgramInitializedEvent {
version: EVENT_VERSION_V2,
program_id,
authorized_payout_key,
token_address,
total_funds: 0i128,
},
);
program_data
}
/// Calculate fee amount based on rate (in basis points)
fn calculate_fee(amount: i128, fee_rate: i128) -> i128 {
if fee_rate == 0 {
return 0;
}
// Fee = (amount * fee_rate) / BASIS_POINTS
amount
.checked_mul(fee_rate)
.and_then(|x| x.checked_div(BASIS_POINTS))
.unwrap_or(0)
}
/// Bump the TTL for single-program persistent storage keys
fn bump_persistent_symbol_ttl(env: &Env, key: &Symbol) {
env.storage()
.persistent()
.extend_ttl(key, PERSISTENT_TTL_THRESHOLD, PERSISTENT_TTL_EXTEND_TO);
}
/// Bump the TTL for the contract instance storage
fn bump_instance_ttl(env: &Env) {
env.storage()
.instance()
.extend_ttl(PERSISTENT_TTL_THRESHOLD, PERSISTENT_TTL_EXTEND_TO);
}
/// Load the complete schedule vector for internal mutation and lookup paths.
///
/// Public query functions must paginate this vector, but internal release
/// operations need access to schedules beyond the public page-size cap.
fn load_program_release_schedules(env: &Env) -> Vec<ProgramReleaseSchedule> {
let schedules = env
.storage()
.persistent()
.get(&SCHEDULES)
.unwrap_or_else(|| Vec::new(env));
Self::bump_persistent_symbol_ttl(env, &SCHEDULES);
schedules
}
/// Return a capped raw-index page from the supplied schedule vector.
fn paginate_program_release_schedules(
env: &Env,
schedules: &Vec<ProgramReleaseSchedule>,
offset: u32,
limit: u32,
) -> Vec<ProgramReleaseSchedule> {
let limit = limit.min(MAX_QUERY_LIMIT);
let mut results = Vec::new(env);
if limit == 0 || offset >= schedules.len() {
return results;
}
let end = offset.saturating_add(limit).min(schedules.len());
for index in offset..end {
results.push_back(schedules.get(index).unwrap());
}
results
}
/// Get fee configuration (internal helper)
fn get_fee_config_internal(env: &Env) -> FeeConfig {
env.storage()
.instance()
.get(&FEE_CONFIG)
.unwrap_or_else(|| FeeConfig {
lock_fee_rate: 0,
payout_fee_rate: 0,
fee_recipient: env.current_contract_address(),
fee_enabled: false,
})
}
/// Emit aggregate statistics event
fn emit_aggregate_stats(env: &Env, program_data: &ProgramData) {
let schedules: Vec<ProgramReleaseSchedule> = env
.storage()
.persistent()
.get(&SCHEDULES)
.unwrap_or_else(|| Vec::new(env));
Self::bump_persistent_symbol_ttl(env, &SCHEDULES);
let mut scheduled_count = 0u32;
for i in 0..schedules.len() {
if !schedules.get(i).unwrap().released {
scheduled_count += 1;
}
}
env.events().publish(
(AGGREGATE_STATS,),
AggregateStatsEvent {
version: EVENT_VERSION_V2,
program_id: program_data.program_id.clone(),
total_funds: program_data.total_funds,
remaining_balance: program_data.remaining_balance,
total_paid_out: program_data.total_funds - program_data.remaining_balance,
payout_count: program_data.payout_history.len(),
scheduled_count,
},
);
}
/// Check if payout is large and emit event if threshold exceeded
fn check_and_emit_large_payout(
env: &Env,
program_data: &ProgramData,
recipient: &Address,
amount: i128,
) {
let threshold = monitoring::get_large_payout_threshold_amount(env, program_data.total_funds);
if amount >= threshold {
env.events().publish(
(LARGE_PAYOUT,),
LargePayoutEvent {
version: EVENT_VERSION_V2,
program_id: program_data.program_id.clone(),
recipient: recipient.clone(),
amount,
threshold,
},
);
}
}
/// Check if a program exists
///
/// # Returns
/// * `bool` - True if program exists, false otherwise
pub fn program_exists(env: Env) -> bool {
let exists = env.storage().persistent().has(&PROGRAM_DATA);
if exists {
Self::bump_persistent_symbol_ttl(&env, &PROGRAM_DATA);
}
exists
}
// ========================================================================
// Fund Management
// ========================================================================
/// Lock funds into the program escrow
///
/// # Arguments
/// * `from` - The address funding the contract, must authorize this call
/// * `amount` - Amount of funds to lock (in native token units)
///
/// # Returns
/// Updated ProgramData with locked funds
pub fn lock_program_funds(env: Env, from: Address, amount: i128) -> ProgramData {
let start = env.ledger().timestamp();
let caller_addr = from.clone();
from.require_auth();
if Self::check_paused(&env, symbol_short!("lock")) {
monitoring::track_operation(&env, symbol_short!("lock"), caller_addr.clone(), false);
panic!("Funds Paused");
}
// Enforce per-caller rate limit
let rl_config = Self::get_rate_limit_config(env.clone());
anti_abuse::check_rate_limit(
&env,
&caller_addr,
rl_config.window_size,
rl_config.max_operations,
rl_config.cooldown_period,
);
if amount <= 0 {
monitoring::track_operation(&env, symbol_short!("lock"), caller_addr.clone(), false);
panic!("Amount must be greater than zero");
}
let mut program_data: ProgramData = env
.storage()
.persistent()
.get(&PROGRAM_DATA)
.unwrap_or_else(|| panic!("Program not initialized"));
Self::bump_persistent_symbol_ttl(&env, &PROGRAM_DATA);
// Check fund caps if configured
let cap_config: FundCapConfig = env
.storage()
.instance()
.get(&FUND_CAP_CONFIG)
.unwrap_or(FundCapConfig {
max_total_funds: None,
max_single_lock: None,
});
// Per-lock cap check
if let Some(max_single) = cap_config.max_single_lock {
if amount > max_single {
monitoring::track_operation(&env, symbol_short!("lock"), caller_addr.clone(), false);
panic!("Amount exceeds per-lock maximum");
}
}
// Total-funds cap check
if let Some(max_total) = cap_config.max_total_funds {
let new_total = program_data.total_funds.checked_add(amount)
.unwrap_or_else(|| {
monitoring::track_operation(&env, symbol_short!("lock"), caller_addr.clone(), false);
panic!("Total funds overflow");
});
if new_total > max_total {
monitoring::track_operation(&env, symbol_short!("lock"), caller_addr.clone(), false);
panic!("Total funds cap exceeded");
}
}
// Transfer funds
let token_client = token::Client::new(&env, &program_data.token_address);
token_client.transfer(&from, &env.current_contract_address(), &amount);
// Update balances
program_data.total_funds = program_data.total_funds.checked_add(amount).expect("Total funds overflow");
program_data.remaining_balance = program_data.remaining_balance.checked_add(amount).expect("Remaining balance overflow");
// Ensure invariant
let contract_balance = token_client.balance(&env.current_contract_address());
if contract_balance < program_data.remaining_balance {
panic!("Invariant violation: token balance < remaining balance");
}
// Store updated data
env.storage().persistent().set(&PROGRAM_DATA, &program_data);
Self::bump_persistent_symbol_ttl(&env, &PROGRAM_DATA);
// Emit FundsLocked event
env.events().publish(
(FUNDS_LOCKED,),
FundsLockedEvent {
version: EVENT_VERSION_V2,
program_id: program_data.program_id.clone(),
amount,
remaining_balance: program_data.remaining_balance,
},
);