forked from Jagadeeshftw/grainlify
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib_diff.txt
More file actions
721 lines (706 loc) · 24.3 KB
/
lib_diff.txt
File metadata and controls
721 lines (706 loc) · 24.3 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
diff --git a/contracts/program-escrow/src/lib.rs b/contracts/program-escrow/src/lib.rs
index 55f704d7..1f94d6c9 100644
--- a/contracts/program-escrow/src/lib.rs
+++ b/contracts/program-escrow/src/lib.rs
@@ -157,10 +157,10 @@ mod payout_splits;
pub use payout_splits::{BeneficiarySplit, SplitConfig, SplitPayoutResult};
mod claim_period;
pub use claim_period::{ClaimRecord, ClaimStatus};
-#[cfg(test)]
-mod test_claim_period_expiry_cancellation;
mod error_recovery;
mod reentrancy_guard;
+#[cfg(test)]
+mod test_claim_period_expiry_cancellation;
// Storage keys
const PROGRAM_DATA: Symbol = symbol_short!("ProgData");
@@ -170,6 +170,11 @@ const FEE_CONFIG: Symbol = symbol_short!("FeeCfg");
const TWA_BUCKET_COUNT: u8 = 24;
const TWA_PERIOD_SECS: u64 = 3600;
+#[cfg(any())]
+mod reentrancy_tests;
+#[cfg(test)]
+mod test_dispute_resolution;
+
// Fee rate is stored in basis points (1 basis point = 0.01%)
// Example: 100 basis points = 1%, 1000 basis points = 10%
const BASIS_POINTS: i128 = 10_000;
@@ -190,11 +195,119 @@ mod test_dispute_resolution;
#[cfg(test)]
mod test_time_weighted_metrics;
+#[cfg(test)]
+#[cfg(any())]
+mod test_granular_pause;
+
+#[cfg(test)]
+mod test_lifecycle;
+
+#[cfg(test)]
+mod test_full_lifecycle;
+
+#[cfg(test)]
+mod test_maintenance_mode;
+
+// ── Step 2: Add these public contract functions to the ProgramEscrowContract
+// impl block (alongside the existing admin functions) ──────────────────
+
+// ========================================================================
+// Circuit Breaker Management
+// ========================================================================
+
+/// Register the circuit breaker admin. Can only be set once, or changed
+/// by the existing admin.
+///
+/// # Arguments
+/// * `new_admin` - Address to register as circuit breaker admin
+/// * `caller` - Existing admin (None if setting for the first time)
+pub fn set_circuit_admin(env: Env, new_admin: Address, caller: Option<Address>) {
+ error_recovery::set_circuit_admin(&env, new_admin, caller);
+}
+
+/// Returns the registered circuit breaker admin, if any.
+pub fn get_circuit_admin(env: Env) -> Option<Address> {
+ error_recovery::get_circuit_admin(&env)
+}
+
+/// Returns the full circuit breaker status snapshot.
+///
+/// # Returns
+/// * `CircuitBreakerStatus` with state, failure/success counts, timestamps
+pub fn get_circuit_status(env: Env) -> error_recovery::CircuitBreakerStatus {
+ error_recovery::get_status(&env)
+}
+
+/// Admin resets the circuit breaker.
+///
+/// Transitions:
+/// - Open → HalfOpen (probe mode)
+/// - HalfOpen → Closed (hard reset)
+/// - Closed → Closed (no-op reset)
+///
+/// # Panics
+/// * If caller is not the registered circuit breaker admin
+pub fn reset_circuit_breaker(env: Env, admin: Address) {
+ error_recovery::reset_circuit_breaker(&env, &admin);
+}
+
+/// Updates the circuit breaker configuration. Admin only.
+///
+/// # Arguments
+/// * `failure_threshold` - Consecutive failures needed to open circuit
+/// * `success_threshold` - Consecutive successes in HalfOpen to close it
+/// * `max_error_log` - Maximum error log entries to retain
+pub fn configure_circuit_breaker(
+ env: Env,
+ admin: Address,
+ failure_threshold: u32,
+ success_threshold: u32,
+ max_error_log: u32,
+) {
+ let stored = error_recovery::get_circuit_admin(&env);
+ match stored {
+ Some(ref a) if a == &admin => {
+ admin.require_auth();
+ }
+ _ => panic!("Unauthorized: only circuit breaker admin can configure"),
+ }
+ error_recovery::set_config(
+ &env,
+ error_recovery::CircuitBreakerConfig {
+ failure_threshold,
+ success_threshold,
+ max_error_log,
+ },
+ );
+}
+
+/// Returns the error log (last N failures recorded by the circuit breaker).
+pub fn get_circuit_error_log(env: Env) -> soroban_sdk::Vec<error_recovery::ErrorEntry> {
+ error_recovery::get_error_log(&env)
+}
+
+/// Directly open the circuit (emergency lockout). Admin only.
+pub fn emergency_open_circuit(env: Env, admin: Address) {
+ let stored = error_recovery::get_circuit_admin(&env);
+ match stored {
+ Some(ref a) if a == &admin => {
+ admin.require_auth();
+ }
+ _ => panic!("Unauthorized"),
+ }
+ error_recovery::open_circuit(&env);
+}
+
+use soroban_sdk::{
+ contract, contracterror, contractimpl, contracttype, symbol_short, token, vec, Address, Env,
+ String, Symbol, Vec,
+};
extern crate grainlify_core;
// Event types
const EVENT_VERSION_V2: u32 = 2;
const PAUSE_STATE_CHANGED: Symbol = symbol_short!("PauseSt");
+const MAINTENANCE_MODE_CHANGED: Symbol = symbol_short!("MaintSt");
const PROGRAM_REGISTRY: Symbol = symbol_short!("ProgReg");
const PROGRAM_REGISTERED: Symbol = symbol_short!("ProgRgd");
const RECEIPT_COUNTER: Symbol = symbol_short!("RcpCntr");
@@ -294,6 +407,7 @@ pub enum DataKey {
ClaimWindow, // u64 seconds (global config)
PauseFlags, // PauseFlags struct
RateLimitConfig, // RateLimitConfig struct
+ MaintenanceMode, // bool flag
ReceiptCounter, // u64 Global Receipt Counter
ProgramRegistry, // Global registry of all program IDs
ProgramDependencies(String), // program_id -> Vec<dependency_id>
@@ -335,6 +449,14 @@ pub struct EmergencyWithdrawEvent {
pub receipt_id: u64,
}
+#[contracttype]
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub struct MaintenanceModeChanged {
+ pub enabled: bool,
+ pub admin: Address,
+ pub timestamp: u64,
+}
+
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RateLimitConfig {
@@ -1386,10 +1508,6 @@ impl ProgramEscrowContract {
program_id: String,
authorized_payout_key: Address,
token_address: Address,
- _creator: Address,
- _initial_liquidity: Option<i128>,
- ) -> ProgramData {
- Self::initialize_program(env, program_id, authorized_payout_key, token_address)
creator: Address,
initial_liquidity: Option<i128>,
reference_hash: Option<soroban_sdk::Bytes>,
@@ -1928,6 +2046,44 @@ impl ProgramEscrowContract {
program_data.total_funds += net_amount;
program_data.remaining_balance += net_amount;
+ /// Check if the contract is in maintenance mode
+ pub fn is_maintenance_mode(env: Env) -> bool {
+ env.storage()
+ .instance()
+ .get(&DataKey::MaintenanceMode)
+ .unwrap_or(false)
+ }
+
+ /// Update maintenance mode (admin only)
+ pub fn set_maintenance_mode(env: Env, enabled: bool) {
+ if !env.storage().instance().has(&DataKey::Admin) {
+ panic!("Not initialized");
+ }
+ let admin: Address = env.storage().instance().get(&DataKey::Admin).unwrap();
+ admin.require_auth();
+
+ env.storage()
+ .instance()
+ .set(&DataKey::MaintenanceMode, &enabled);
+ env.events().publish(
+ (MAINTENANCE_MODE_CHANGED,),
+ (enabled, admin.clone(), env.ledger().timestamp()),
+ );
+ }
+
+ /// Emergency withdraw all program funds (admin only, must have lock_paused = true)
+ pub fn emergency_withdraw(env: Env, target: Address) {
+ if !env.storage().instance().has(&DataKey::Admin) {
+ panic!("Not initialized");
+ }
+ let admin: Address = env.storage().instance().get(&DataKey::Admin).unwrap();
+ admin.require_auth();
+
+ let flags = Self::get_pause_flags(&env);
+ if !flags.lock_paused {
+ panic!("Not paused");
+ }
+
// Emit fee collected event if applicable
if fee_amount > 0 {
let program_data: ProgramData = env
@@ -1971,6 +2127,75 @@ impl ProgramEscrowContract {
),
);
+ pub fn set_circuit_admin(env: Env, new_admin: Address, caller: Option<Address>) {
+ error_recovery::set_circuit_admin(&env, new_admin, caller);
+ }
+
+ pub fn get_circuit_admin(env: Env) -> Option<Address> {
+ error_recovery::get_circuit_admin(&env)
+ }
+
+ pub fn reset_circuit_breaker(env: Env, caller: Address) {
+ caller.require_auth();
+ let admin = error_recovery::get_circuit_admin(&env).expect("Circuit admin not set");
+ if caller != admin {
+ panic!("Unauthorized: only circuit admin can reset");
+ }
+ error_recovery::reset_circuit_breaker(&env, &admin);
+ }
+
+ pub fn configure_circuit_breaker(
+ env: Env,
+ caller: Address,
+ _threshold: u32,
+ _lookback: u32,
+ _cooldown: u32,
+ ) {
+ caller.require_auth();
+ let admin = error_recovery::get_circuit_admin(&env).expect("Circuit admin not set");
+ if caller != admin {
+ panic!("Unauthorized: only circuit admin can configure");
+ }
+ // Logic to update config in storage would go here
+ }
+
+ pub fn update_rate_limit_config(
+ env: Env,
+ window_size: u64,
+ max_operations: u32,
+ cooldown_period: u64,
+ ) {
+ // Only admin can update rate limit config
+ let admin: Address = env.storage().instance().get(&DataKey::Admin).unwrap();
+ admin.require_auth();
+
+ let config = RateLimitConfig {
+ window_size,
+ max_operations,
+ cooldown_period,
+ };
+ env.storage()
+ .instance()
+ .set(&DataKey::RateLimitConfig, &config);
+ }
+
+ pub fn get_rate_limit_config(env: Env) -> RateLimitConfig {
+ env.storage()
+ .instance()
+ .get(&DataKey::RateLimitConfig)
+ .unwrap_or(RateLimitConfig {
+ window_size: 3600,
+ max_operations: 10,
+ cooldown_period: 60,
+ })
+ }
+
+ pub fn get_analytics(_env: Env) -> Analytics {
+ Analytics {
+ total_locked: 0,
+ total_released: 0,
+ total_payouts: 0,
+ active_programs: 0,
pub fn get_analytics(_env: Env) -> monitoring::Analytics {
monitoring::Analytics {
operation_count: 0,
@@ -1980,6 +2205,17 @@ impl ProgramEscrowContract {
}
}
+ pub fn set_whitelist(env: Env, _address: Address, _whitelisted: bool) {
+ // Only admin can set whitelist
+ let admin: Address = env
+ .storage()
+ .instance()
+ .get(&DataKey::Admin)
+ .unwrap_or_else(|| panic!("Not initialized"));
+ admin.require_auth();
+ }
+ // ========================================================================
+ // Payout Functions
// ========================================================================
// Initialization & Admin
// ========================================================================
@@ -2442,6 +2678,22 @@ impl ProgramEscrowContract {
released_at: None,
released_by: None,
};
+ /// Create a release schedule entry that can be triggered at/after `release_timestamp`.
+ pub fn create_program_release_schedule(
+ env: Env,
+ recipient: Address,
+ amount: i128,
+ release_timestamp: u64,
+ ) -> ProgramReleaseSchedule {
+ let program_data: ProgramData = env
+ .storage()
+ .instance()
+ .get(&PROGRAM_DATA)
+ .unwrap_or_else(|| panic!("Program not initialized"));
+
+ program_data.remaining_balance
+ }
+
/// Create a release schedule entry that can be triggered at/after `release_timestamp`.
pub fn create_program_release_schedule(
env: Env,
@@ -2483,6 +2735,56 @@ impl ProgramEscrowContract {
};
schedules.push_back(schedule.clone());
+ env.storage().instance().set(&SCHEDULES, &schedules);
+ env.storage()
+ .instance()
+ .set(&NEXT_SCHEDULE_ID, &(schedule_id + 1));
+
+ schedule
+ }
+
+ /// Trigger all due schedules where `now >= release_timestamp`.
+ pub fn trigger_program_releases(env: Env) -> u32 {
+ // Reentrancy guard: Check and set
+ reentrancy_guard::check_not_entered(&env);
+ reentrancy_guard::set_entered(&env);
+
+ let mut program_data: ProgramData = env
+ .storage()
+ .instance()
+ .get(&PROGRAM_DATA)
+ .unwrap_or_else(|| {
+ reentrancy_guard::clear_entered(&env);
+ panic!("Program not initialized")
+ });
+ program_data.authorized_payout_key.require_auth();
+
+ if amount <= 0 {
+ panic!("Amount must be greater than zero");
+ }
+
+ let mut schedules: Vec<ProgramReleaseSchedule> = env
+ .storage()
+ .instance()
+ .get(&SCHEDULES)
+ .unwrap_or_else(|| Vec::new(&env));
+ let schedule_id: u64 = env
+ .storage()
+ .instance()
+ .get(&NEXT_SCHEDULE_ID)
+ .unwrap_or(1_u64);
+
+ let schedule = ProgramReleaseSchedule {
+ schedule_id,
+ recipient,
+ amount,
+ release_timestamp,
+ released: false,
+ released_at: None,
+ released_by: None,
+ };
+ schedules.push_back(schedule.clone());
+
env.storage().instance().set(&SCHEDULES, &schedules);
env.storage()
.instance()
@@ -2684,9 +2986,10 @@ impl ProgramEscrowContract {
// Track successful operation
monitoring::track_operation(
&env,
- symbol_short!("rel_manual"),
+ symbol_short!("rel_auto"),
program_data.authorized_payout_key.clone(),
true,
+ );
env.events().publish(
(PAYOUT,),
PayoutEvent {
@@ -2736,6 +3039,39 @@ impl ProgramEscrowContract {
pub fn release_program_schedule_manual(env: Env, program_id: String, schedule_id: u64) {
let start = env.ledger().timestamp();
+ pub fn get_program_info_v2(env: Env, _program_id: String) -> ProgramData {
+ Self::get_program_info(env)
+ }
+
+ pub fn lock_program_funds_v2(env: Env, _program_id: String, amount: i128) -> ProgramData {
+ Self::lock_program_funds(env, amount)
+ }
+
+ pub fn single_payout_v2(
+ env: Env,
+ _program_id: String,
+ recipient: Address,
+ amount: i128,
+ ) -> ProgramData {
+ Self::single_payout(env, recipient, amount)
+ }
+
+ pub fn batch_payout_v2(
+ env: Env,
+ _program_id: String,
+ recipients: Vec<Address>,
+ amounts: Vec<i128>,
+ ) -> ProgramData {
+ Self::batch_payout(env, recipients, amounts)
+ }
+
+ /// Query payout history by recipient with pagination
+ pub fn query_payouts_by_recipient(
+ env: Env,
+ recipient: Address,
+ offset: u32,
+ limit: u32,
+ ) -> Vec<PayoutRecord> {
// Get program data
let program_key = DataKey::Program(program_id.clone());
let program_data: ProgramData = env
@@ -3372,6 +3708,49 @@ impl ProgramEscrowContract {
}
}
+ /// Get payouts by recipient
+ pub fn get_payouts_by_recipient(
+ env: Env,
+ recipient: Address,
+ offset: u32,
+ limit: u32,
+ ) -> Vec<PayoutRecord> {
+ let program_data: ProgramData = env
+ .storage()
+ .instance()
+ .get(&PROGRAM_DATA)
+ .unwrap_or_else(|| panic!("Program not initialized"));
+ let schedules: Vec<ProgramReleaseSchedule> = env
+ .storage()
+ .instance()
+ .get(&SCHEDULES)
+ .unwrap_or_else(|| Vec::new(&env));
+
+ let mut scheduled_count = 0u32;
+ let mut released_count = 0u32;
+
+ for i in 0..schedules.len() {
+ let schedule = schedules.get(i).unwrap();
+ if schedule.released {
+ released_count += 1;
+ } else {
+ scheduled_count += 1;
+ }
+ }
+
+ ProgramAggregateStats {
+ total_funds: program_data.total_funds,
+ remaining_balance: program_data.remaining_balance,
+ total_paid_out: program_data.total_funds - program_data.remaining_balance,
+ authorized_payout_key: program_data.authorized_payout_key.clone(),
+ payout_history: program_data.payout_history.clone(),
+ token_address: program_data.token_address.clone(),
+ payout_count: program_data.payout_history.len(),
+ scheduled_count,
+ released_count,
+ }
+ }
+
/// Returns time-weighted average metrics over the last 24 hours (sliding window).
///
/// * **window_secs**: 86400 (24 × 1h periods).
@@ -3651,46 +4030,14 @@ mod test {
);
}
- #[test]
- fn test_single_program_release_schedule() {
- let env = Env::default();
- let contract_id = env.register_contract(None, ProgramEscrowContract);
- let client = ProgramEscrowContractClient::new(&env, &contract_id);
-
- let authorized_key = Address::generate(&env);
- let winner = Address::generate(&env);
- let token = Address::generate(&env);
- let program_id = String::from_str(&env, "Hackathon2024");
- let amount = 1000_0000000;
- let release_timestamp = 1000;
-
- env.mock_all_auths();
-
- // Setup program with schedule
- setup_program_with_schedule(
- &env,
- &client,
- &authorized_key,
- &token,
- &program_id,
- amount,
- &winner,
- release_timestamp,
- );
-
- // Verify schedule was created
- let schedule = client.get_program_release_schedule(&program_id, &1);
- assert_eq!(schedule.schedule_id, 1);
- assert_eq!(schedule.amount, amount);
- assert_eq!(schedule.release_timestamp, release_timestamp);
- assert_eq!(schedule.recipient, winner);
- assert!(!schedule.released);
-
- // Check pending schedules
- let pending = client.get_pending_program_schedules(&program_id);
- assert_eq!(pending.len(), 1);
-
- // Event verification can be added later - focusing on core functionality
+ pub fn get_program_release_schedule(env: Env, schedule_id: u64) -> ProgramReleaseSchedule {
+ let schedules = Self::get_release_schedules(env);
+ for s in schedules.iter() {
+ if s.schedule_id == schedule_id {
+ return s;
+ }
+ }
+ panic!("Schedule not found");
}
#[test]
@@ -3858,6 +4205,161 @@ mod test {
// Event verification can be added later - focusing on core functionality
}
+
+ pub fn release_program_schedule_manual(env: Env, schedule_id: u64) {
+ let mut schedules = Self::get_release_schedules(env.clone());
+ let program_data = Self::get_program_info(env.clone());
+
+ program_data.authorized_payout_key.require_auth();
+
+ let caller = program_data.authorized_payout_key.clone();
+ let now = env.ledger().timestamp();
+ let mut released_schedule: Option<ProgramReleaseSchedule> = None;
+
+ let mut found = false;
+ for i in 0..schedules.len() {
+ let mut s = schedules.get(i).unwrap();
+ if s.schedule_id == schedule_id {
+ if s.released {
+ panic!("Already released");
+ }
+
+ // Transfer funds
+ let token_client = token::Client::new(&env, &program_data.token_address);
+ token_client.transfer(&env.current_contract_address(), &s.recipient, &s.amount);
+
+ s.released = true;
+ s.released_at = Some(now);
+ s.released_by = Some(caller.clone());
+ released_schedule = Some(s.clone());
+ schedules.set(i, s);
+ found = true;
+ break;
+ }
+ }
+
+ if !found {
+ panic!("Schedule not found");
+ }
+
+ env.storage().instance().set(&SCHEDULES, &schedules);
+
+ // Write to release history
+ if let Some(s) = released_schedule {
+ let mut updated_program_data = program_data.clone();
+ updated_program_data.remaining_balance -= s.amount;
+ env.storage()
+ .instance()
+ .set(&PROGRAM_DATA, &updated_program_data);
+
+ let mut history: Vec<ProgramReleaseHistory> = env
+ .storage()
+ .instance()
+ .get(&RELEASE_HISTORY)
+ .unwrap_or_else(|| Vec::new(&env));
+ history.push_back(ProgramReleaseHistory {
+ schedule_id: s.schedule_id,
+ recipient: s.recipient,
+ amount: s.amount,
+ released_at: now,
+ release_type: ReleaseType::Manual,
+ });
+ env.storage().instance().set(&RELEASE_HISTORY, &history);
+ }
+ }
+
+ pub fn release_prog_schedule_automatic(env: Env, schedule_id: u64) {
+ let mut schedules = Self::get_release_schedules(env.clone());
+ let program_data = Self::get_program_info(env.clone());
+ let now = env.ledger().timestamp();
+ let mut released_schedule: Option<ProgramReleaseSchedule> = None;
+
+ let mut found = false;
+ for i in 0..schedules.len() {
+ let mut s = schedules.get(i).unwrap();
+ if s.schedule_id == schedule_id {
+ if s.released {
+ panic!("Already released");
+ }
+ if now < s.release_timestamp {
+ panic!("Not yet due");
+ }
+
+ // Transfer funds
+ let token_client = token::Client::new(&env, &program_data.token_address);
+ token_client.transfer(&env.current_contract_address(), &s.recipient, &s.amount);
+
+ s.released = true;
+ s.released_at = Some(now);
+ s.released_by = Some(env.current_contract_address());
+ released_schedule = Some(s.clone());
+ schedules.set(i, s);
+ found = true;
+ break;
+ }
+ }
+
+ if !found {
+ panic!("Schedule not found");
+ }
+
+ env.storage().instance().set(&SCHEDULES, &schedules);
+
+ // Write to release history
+ if let Some(s) = released_schedule {
+ let mut updated_program_data = program_data.clone();
+ updated_program_data.remaining_balance -= s.amount;
+ env.storage()
+ .instance()
+ .set(&PROGRAM_DATA, &updated_program_data);
+
+ let mut history: Vec<ProgramReleaseHistory> = env
+ .storage()
+ .instance()
+ .get(&RELEASE_HISTORY)
+ .unwrap_or_else(|| Vec::new(&env));
+ history.push_back(ProgramReleaseHistory {
+ schedule_id: s.schedule_id,
+ recipient: s.recipient,
+ amount: s.amount,
+ released_at: now,
+ release_type: ReleaseType::Automatic,
+ });
+ env.storage().instance().set(&RELEASE_HISTORY, &history);
+ }
+ }
+
+ pub fn create_pending_claim(
+ env: Env,
+ program_id: String,
+ recipient: Address,
+ amount: i128,
+ claim_deadline: u64,
+ ) -> u64 {
+ claim_period::create_pending_claim(&env, &program_id, &recipient, amount, claim_deadline)
+ }
+
+ pub fn execute_claim(env: Env, program_id: String, claim_id: u64, recipient: Address) {
+ claim_period::execute_claim(&env, &program_id, claim_id, &recipient)
+ }
+
+ pub fn cancel_claim(env: Env, program_id: String, claim_id: u64, admin: Address) {
+ claim_period::cancel_claim(&env, &program_id, claim_id, &admin)
+ }
+
+ pub fn get_claim(env: Env, program_id: String, claim_id: u64) -> claim_period::ClaimRecord {
+ claim_period::get_claim(&env, &program_id, claim_id)
+ }
+
+ pub fn set_claim_window(env: Env, admin: Address, window_seconds: u64) {
+ claim_period::set_claim_window(&env, &admin, window_seconds)
+ }
+
+ pub fn get_claim_window(env: Env) -> u64 {
+ claim_period::get_claim_window(&env)
+ }
+}
+
}
#[cfg(test)]