-
Notifications
You must be signed in to change notification settings - Fork 123
Expand file tree
/
Copy pathrisk_management.rs
More file actions
420 lines (376 loc) · 13.1 KB
/
Copy pathrisk_management.rs
File metadata and controls
420 lines (376 loc) · 13.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
//! # Risk Management Module
//!
//! Provides configurable risk parameters and pause controls for the lending protocol.
//!
//! ## Risk Parameters (all in basis points)
//! - **Minimum collateral ratio** (default 110%): below this, new borrows are rejected
//! - **Liquidation threshold** (default 105%): below this, positions can be liquidated
//! - **Close factor** (default 50%): max percentage of debt liquidatable per transaction
//! - **Liquidation incentive** (default 10%): bonus awarded to liquidators
//!
//! ## Pause Controls
//! - Per-operation pause switches (deposit, withdraw, borrow, repay, liquidate, flash_loan, bridge_acceptance)
//! - Global emergency pause that halts all operations immediately
//!
//! ## Safety
//! - Parameter changes are limited to ±10% per update to prevent drastic shifts.
//! - Min collateral ratio must always be ≥ liquidation threshold.
//! - Only the admin address can modify risk parameters.
#![allow(unused)]
use crate::events::{
emit_admin_action, emit_pause_state_changed, emit_risk_params_updated, AdminActionEvent,
PauseStateChangedEvent, RiskParamsUpdatedEvent,
};
use soroban_sdk::{contracterror, contracttype, Address, Env, IntoVal, Map, Symbol, Val, Vec};
/// Errors that can occur during risk management operations
#[contracterror]
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
#[repr(u32)]
pub enum RiskManagementError {
/// Unauthorized access - caller is not admin
Unauthorized = 1,
/// Invalid parameter value
InvalidParameter = 2,
/// Parameter change exceeds maximum allowed change
ParameterChangeTooLarge = 3,
/// Minimum collateral ratio not met
InsufficientCollateralRatio = 4,
/// Operation is paused
OperationPaused = 5,
/// Emergency pause is active
EmergencyPaused = 6,
/// Invalid collateral ratio (must be >= liquidation threshold)
InvalidCollateralRatio = 7,
/// Invalid liquidation threshold (must be <= collateral ratio)
InvalidLiquidationThreshold = 8,
/// Close factor out of valid range (0-100%)
InvalidCloseFactor = 9,
/// Liquidation incentive out of valid range (0-50%)
InvalidLiquidationIncentive = 10,
/// Overflow occurred during calculation
Overflow = 11,
/// Action requires governance approval
GovernanceRequired = 12,
/// Contract has already been initialized
AlreadyInitialized = 13,
}
/// Storage keys for risk management data
#[contracttype]
#[derive(Clone)]
#[cfg_attr(test, derive(Debug, PartialEq))]
pub enum RiskDataKey {
/// Global risk configuration parameters (MCR, liquidation threshold, etc.)
/// Value type: RiskConfig
RiskConfig,
/// Protocol admin address authorized for risk management
/// Value type: Address
Admin,
/// Global emergency pause flag. If true, all protocol operations are halted.
/// Value type: bool
EmergencyPause,
/// Timelock for safety of sensitive parameter changes
/// Value type: u64 (timestamp)
ParameterChangeTimelock,
}
/// Risk configuration parameters for pause switches
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct RiskConfig {
/// Pause switches for different operations
pub pause_switches: Map<Symbol, bool>,
/// Minimum collateral ratio (in basis points)
pub min_collateral_ratio: i128,
/// Liquidation threshold (in basis points)
pub liquidation_threshold: i128,
/// Close factor (in basis points)
pub close_factor: i128,
/// Liquidation incentive (in basis points)
pub liquidation_incentive: i128,
/// Last update timestamp
pub last_update: u64,
}
/// Pause switch operation types
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub enum PauseOperation {
/// Pause deposit operations
Deposit,
/// Pause withdraw operations
Withdraw,
/// Pause borrow operations
Borrow,
/// Pause repay operations
Repay,
/// Pause liquidation operations
Liquidate,
/// Pause flash loan operations
FlashLoan,
/// Pause bridge acceptance (deposit) operations
BridgeAcceptance,
/// Pause all operations (emergency)
All,
}
/// Initialize risk management system
///
/// Sets up default risk parameters and admin address.
/// Should be called during contract initialization.
///
/// # Arguments
/// * `env` - The Soroban environment
/// * `admin` - The admin address
///
/// # Returns
/// Returns Ok(()) on success
///
/// # Errors
/// * `RiskManagementError::InvalidParameter` - If default parameters are invalid
pub fn initialize_risk_management(env: &Env, admin: Address) -> Result<(), RiskManagementError> {
// Check if initialized
let config_key = RiskDataKey::RiskConfig;
if env.storage().persistent().has(&config_key) {
return Ok(());
}
// Set admin
env.storage().persistent().set(&RiskDataKey::Admin, &admin);
let risk_params =
crate::risk_params::get_risk_params(env).unwrap_or(crate::risk_params::RiskParams {
min_collateral_ratio: 11_000,
liquidation_threshold: 10_500,
close_factor: 5_000,
liquidation_incentive: 1_000,
last_update: env.ledger().timestamp(),
});
// Initialize default risk config for pause switches
let default_config = RiskConfig {
pause_switches: create_default_pause_switches(env),
min_collateral_ratio: risk_params.min_collateral_ratio,
liquidation_threshold: risk_params.liquidation_threshold,
close_factor: risk_params.close_factor,
liquidation_incentive: risk_params.liquidation_incentive,
last_update: env.ledger().timestamp(),
};
let config_key = RiskDataKey::RiskConfig;
env.storage().persistent().set(&config_key, &default_config);
// Initialize emergency pause as false
let emergency_key = RiskDataKey::EmergencyPause;
env.storage().persistent().set(&emergency_key, &false);
emit_admin_action(
env,
AdminActionEvent {
actor: admin.clone(),
action: Symbol::new(env, "initialize"),
timestamp: env.ledger().timestamp(),
},
);
Ok(())
}
/// Create default pause switches map
fn create_default_pause_switches(env: &Env) -> Map<Symbol, bool> {
let mut switches = Map::new(env);
switches.set(Symbol::new(env, "pause_deposit"), false);
switches.set(Symbol::new(env, "pause_withdraw"), false);
switches.set(Symbol::new(env, "pause_borrow"), false);
switches.set(Symbol::new(env, "pause_repay"), false);
switches.set(Symbol::new(env, "pause_liquidate"), false);
switches.set(Symbol::new(env, "pause_flash_loan"), false);
switches.set(Symbol::new(env, "pause_bridge_acceptance"), false);
switches
}
/// Get the admin address (deprecated, delegates to new admin module)
#[deprecated(note = "Use crate::admin::get_admin instead")]
pub fn get_admin(env: &Env) -> Option<Address> {
crate::admin::get_admin(env)
}
/// Check if caller is admin (delegates to new admin module)
pub fn require_admin(env: &Env, caller: &Address) -> Result<(), RiskManagementError> {
crate::admin::require_admin(env, caller).map_err(|_| RiskManagementError::Unauthorized)
}
/// Get current risk configuration
pub fn get_risk_config(env: &Env) -> Option<RiskConfig> {
let config_key = RiskDataKey::RiskConfig;
let mut config = env
.storage()
.persistent()
.get::<RiskDataKey, RiskConfig>(&config_key)?;
if let Some(params) = crate::risk_params::get_risk_params(env) {
config.min_collateral_ratio = params.min_collateral_ratio;
config.liquidation_threshold = params.liquidation_threshold;
config.close_factor = params.close_factor;
config.liquidation_incentive = params.liquidation_incentive;
config.last_update = params.last_update;
}
Some(config)
}
/// Set pause switches (admin only)
///
/// Updates pause switches for different operations.
///
/// # Arguments
/// * `env` - The Soroban environment
/// * `caller` - The caller address (must be admin)
/// * `operation` - The operation to pause/unpause (as Symbol)
/// * `paused` - Whether to pause (true) or unpause (false)
///
/// # Returns
/// Returns Ok(()) on success
///
/// # Errors
/// * `RiskManagementError::Unauthorized` - If caller is not admin
pub fn set_pause_switch(
env: &Env,
caller: Address,
operation: Symbol,
paused: bool,
) -> Result<(), RiskManagementError> {
// Check admin
require_admin(env, &caller)?;
// Get current config
let mut config = get_risk_config(env).ok_or(RiskManagementError::InvalidParameter)?;
// Update pause switch
config.pause_switches.set(operation.clone(), paused);
// Update timestamp
config.last_update = env.ledger().timestamp();
// Save config
let config_key = RiskDataKey::RiskConfig;
env.storage().persistent().set(&config_key, &config);
// Emit event
emit_pause_switch_updated_event(env, &caller, &operation, paused);
Ok(())
}
/// Set multiple pause switches at once (admin only)
///
/// # Arguments
/// * `env` - The Soroban environment
/// * `caller` - The caller address (must be admin)
/// * `switches` - Map of operation symbols to pause states
///
/// # Returns
/// Returns Ok(()) on success
pub fn set_pause_switches(
env: &Env,
caller: Address,
switches: Map<Symbol, bool>,
) -> Result<(), RiskManagementError> {
// Check admin
require_admin(env, &caller)?;
// Get current config
let mut config = get_risk_config(env).ok_or(RiskManagementError::InvalidParameter)?;
// Update all pause switches
for (op, paused) in switches.iter() {
config.pause_switches.set(op, paused);
}
// Update timestamp
config.last_update = env.ledger().timestamp();
// Save config
let config_key = RiskDataKey::RiskConfig;
env.storage().persistent().set(&config_key, &config);
// Emit event
emit_pause_switches_updated_event(env, &caller, &switches);
Ok(())
}
/// Check if an operation is paused
pub fn is_operation_paused(env: &Env, operation: Symbol) -> bool {
if let Some(config) = get_risk_config(env) {
config.pause_switches.get(operation).unwrap_or(false)
} else {
false
}
}
/// Require that an operation is not paused
pub fn require_operation_not_paused(
env: &Env,
operation: Symbol,
) -> Result<(), RiskManagementError> {
if is_operation_paused(env, operation.clone()) {
return Err(RiskManagementError::OperationPaused);
}
Ok(())
}
/// Check if operation is paused (public helper for other modules)
/// This is a convenience function that can be called from other modules
pub fn check_operation_paused(env: &Env, operation: Symbol) -> bool {
// First check emergency pause
if is_emergency_paused(env) {
return true;
}
// Then check specific operation pause
is_operation_paused(env, operation)
}
/// Set emergency pause (admin only)
///
/// Emergency pause stops all operations immediately.
///
/// # Arguments
/// * `env` - The Soroban environment
/// * `caller` - The caller address (must be admin)
/// * `paused` - Whether to enable (true) or disable (false) emergency pause
///
/// # Returns
/// Returns Ok(()) on success
pub fn set_emergency_pause(
env: &Env,
caller: Address,
paused: bool,
) -> Result<(), RiskManagementError> {
// Check admin
require_admin(env, &caller)?;
// Set emergency pause
let emergency_key = RiskDataKey::EmergencyPause;
env.storage().persistent().set(&emergency_key, &paused);
// Emit event
emit_emergency_pause_event(env, &caller, paused);
Ok(())
}
/// Check if emergency pause is active
pub fn is_emergency_paused(env: &Env) -> bool {
let emergency_key = RiskDataKey::EmergencyPause;
env.storage()
.persistent()
.get::<RiskDataKey, bool>(&emergency_key)
.unwrap_or(false)
}
/// Require that emergency pause is not active
pub fn check_emergency_pause(env: &Env) -> Result<(), RiskManagementError> {
if is_emergency_paused(env) {
return Err(RiskManagementError::EmergencyPaused);
}
Ok(())
}
/// Emit pause switch updated event
fn emit_pause_switch_updated_event(env: &Env, caller: &Address, operation: &Symbol, paused: bool) {
emit_pause_state_changed(
env,
PauseStateChangedEvent {
actor: caller.clone(),
operation: operation.clone(),
paused,
timestamp: env.ledger().timestamp(),
},
);
}
/// Emit pause switches updated event
fn emit_pause_switches_updated_event(env: &Env, caller: &Address, switches: &Map<Symbol, bool>) {
for (operation, paused) in switches.iter() {
emit_pause_state_changed(
env,
PauseStateChangedEvent {
actor: caller.clone(),
operation,
paused,
timestamp: env.ledger().timestamp(),
},
);
}
}
/// Emit emergency pause event
fn emit_emergency_pause_event(env: &Env, caller: &Address, paused: bool) {
emit_pause_state_changed(
env,
PauseStateChangedEvent {
actor: caller.clone(),
operation: Symbol::new(env, "emergency"),
paused,
timestamp: env.ledger().timestamp(),
},
);
}