forked from Netwalls/BOXMEOUT_STELLA
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
467 lines (413 loc) · 15 KB
/
Copy pathlib.rs
File metadata and controls
467 lines (413 loc) · 15 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
#![no_std]
use shared::types::ProtocolConfig;
use soroban_sdk::{
contract, contractimpl, contracttype, symbol_short, token, Address, Bytes, Env, Symbol, Vec,
};
// ─── STORAGE KEYS ─────────────────────────────────────────────────────────────
// "ADMIN" -> Address
// "FACTORY" -> Address
// "TOKEN" -> Address (XLM token contract)
// "FEE_BPS" -> u32 (fee in basis points)
// "FEE_RECIPIENT" -> Address
// "BALANCE" -> i128
// "TOTAL_FEES" -> i128
// "WITHDRAWAL_LOG" -> Vec<(Address, i128, u64)>
fn key_admin(env: &Env) -> Symbol {
Symbol::new(env, "ADMIN")
}
fn key_factory(env: &Env) -> Symbol {
Symbol::new(env, "FACTORY")
}
fn key_token(env: &Env) -> Symbol {
Symbol::new(env, "TOKEN")
}
fn key_fee_bps(env: &Env) -> Symbol {
Symbol::new(env, "FEE_BPS")
}
fn key_fee_recipient(env: &Env) -> Symbol {
Symbol::new(env, "FEE_RECIPIENT")
}
fn key_balance(env: &Env) -> Symbol {
Symbol::new(env, "BALANCE")
}
fn key_total_fees(env: &Env) -> Symbol {
Symbol::new(env, "TOTAL_FEES")
}
fn key_wlog(env: &Env) -> Symbol {
Symbol::new(env, "WITHDRAWAL_LOG")
}
#[contract]
pub struct Treasury;
#[contractimpl]
impl Treasury {
/// Initializes the Treasury with admin, fee configuration, and token address.
///
/// Must be called once immediately after deployment. Stores admin address,
/// fee basis points, fee recipient, token address, and initializes balance
/// tracking and withdrawal log.
///
/// # Arguments
///
/// * `env` - The Soroban execution environment.
/// * `admin` - Address of the treasury administrator, authorized to withdraw funds.
/// * `fee_bps` - Protocol fee in basis points (e.g., 200 = 2%). Must not exceed 1000 (10%).
/// * `fee_recipient` - Address that receives protocol fees.
/// * `factory` - Address of the `MarketFactory` contract.
/// * `token` - Address of the XLM token contract.
///
/// # Panics
///
/// Panics if:
/// - The treasury has already been initialized.
/// - `fee_bps` exceeds 1000 (10%).
pub fn initialize(
env: Env,
admin: Address,
fee_bps: u32,
fee_recipient: Address,
factory: Address,
token: Address,
) {
if env.storage().persistent().has(&key_admin(&env)) {
panic!("already initialized");
}
// Validate fee_bps does not exceed 10% (1000 basis points)
if fee_bps > 1000 {
panic!("fee_bps exceeds maximum of 1000 (10%)");
}
env.storage().persistent().set(&key_admin(&env), &admin);
env.storage().persistent().set(&key_fee_bps(&env), &fee_bps);
env.storage()
.persistent()
.set(&key_fee_recipient(&env), &fee_recipient);
env.storage().persistent().set(&key_factory(&env), &factory);
env.storage().persistent().set(&key_token(&env), &token);
env.storage().persistent().set(&key_balance(&env), &0i128);
env.storage()
.persistent()
.set(&key_total_fees(&env), &0i128);
env.storage()
.persistent()
.set(&key_wlog(&env), &Vec::<(Address, i128, u64)>::new(&env));
}
/// Receives protocol fees from a registered `Market` contract.
///
/// Only callable by a Market contract address registered with the factory.
/// Increments the per-market escrow balance and emits a `BetDeposited` event.
///
/// # Arguments
///
/// * `env` - The Soroban execution environment.
/// * `from_market` - Address of the Market contract depositing bets (must be authorized).
/// * `market_id` - Identifier of the market, used for per-market escrow tracking.
/// * `amount` - Amount of XLM to deposit into escrow, in stroops.
///
/// # Panics
///
/// Panics if:
/// - The invoking contract address does not match the address registered for `market_id` in the factory.
pub fn deposit_fees(env: Env, market_id: Bytes, amount: i128) {
let factory: Address = env
.storage()
.persistent()
.get(&key_factory(&env))
.expect("not initialized");
let caller = env.current_contract_address();
let caller = env.current_contract_address();
let registered: Address = env.invoke_contract(
&factory,
&Symbol::new(&env, "get_market_address"),
soroban_sdk::vec![&env, market_id.to_val()],
);
if registered != caller {
panic!("unauthorized: caller is not a registered market");
}
let balance: i128 = env
.storage()
.persistent()
.get(&key_balance(&env))
.unwrap_or(0);
let total: i128 = env
.storage()
.persistent()
.get(&key_total_fees(&env))
.unwrap_or(0);
env.storage()
.persistent()
.set(&key_balance(&env), &(balance + amount));
env.storage()
.persistent()
.set(&key_total_fees(&env), &(total + amount));
env.events().publish(
(Symbol::new(&env, "FeesDeposited"),),
(caller, amount, env.ledger().timestamp()),
);
}
/// Transfers collected fees from the treasury to a recipient address.
///
/// Validates that `amount ≤ BALANCE` and deducts it before transferring XLM.
/// Appends an entry to `WITHDRAWAL_LOG`. Emits a `FeesWithdrawn` event.
///
/// # Arguments
///
/// * `env` - The Soroban execution environment.
/// * `admin` - Admin address. Must authorize this call.
/// * `recipient` - Address that will receive the withdrawn XLM.
/// * `amount` - Amount to withdraw in stroops. Must not exceed current `BALANCE`.
///
/// # Panics
///
/// Panics if:
/// - `admin` has not authorized the call.
/// - `amount` exceeds the current `BALANCE`.
pub fn withdraw_fees(env: Env, admin: Address, recipient: Address, amount: i128) {
admin.require_auth();
let stored_admin: Address = env
.storage()
.persistent()
.get(&key_admin(&env))
.expect("not initialized");
if stored_admin != admin {
panic!("not admin");
}
let balance: i128 = env
.storage()
.persistent()
.get(&key_balance(&env))
.unwrap_or(0);
if amount > balance {
panic!("amount exceeds balance");
}
env.storage()
.persistent()
.set(&key_balance(&env), &(balance - amount));
let token_addr: Address = env
.storage()
.persistent()
.get(&key_token(&env))
.expect("token not set");
token::Client::new(&env, &token_addr).transfer(
&env.current_contract_address(),
&recipient,
&amount,
);
let ts = env.ledger().timestamp();
let mut log: Vec<(Address, i128, u64)> = env
.storage()
.persistent()
.get(&key_wlog(&env))
.unwrap_or(Vec::new(&env));
log.push_back((recipient.clone(), amount, ts));
env.storage().persistent().set(&key_wlog(&env), &log);
env.events().publish(
(Symbol::new(&env, "FeesWithdrawn"),),
(recipient, amount, ts),
);
amount
}
/// Drains all treasury funds to `recipient` in an emergency.
///
/// Only callable while the protocol is paused (verified via cross-contract call
/// to the factory's `get_config`). Resets `BALANCE` to zero, logs the drain,
/// and emits an `EmergencyDrain` event.
///
/// # Arguments
///
/// * `env` - The Soroban execution environment.
/// * `admin` - Admin address. Must authorize this call.
/// * `recipient` - Address that receives all drained XLM.
///
/// # Returns
///
/// Returns the total amount drained in stroops.
///
/// # Panics
///
/// Panics if:
/// - `admin` has not authorized the call.
/// - The protocol is not currently paused.
pub fn emergency_drain(env: Env, admin: Address, recipient: Address) -> i128 {
admin.require_auth();
let stored_admin: Address = env
.storage()
.persistent()
.get(&key_admin(&env))
.expect("not initialized");
if stored_admin != admin {
panic!("not admin");
}
let factory: Address = env
.storage()
.persistent()
.get(&key_factory(&env))
.expect("factory not set");
let config: ProtocolConfig = env.invoke_contract(
&factory,
&Symbol::new(&env, "get_config"),
soroban_sdk::vec![&env],
);
if !config.paused {
panic!("protocol is not paused");
}
let amount: i128 = env
.storage()
.persistent()
.get(&key_balance(&env))
.unwrap_or(0);
let token_addr: Address = env
.storage()
.persistent()
.get(&key_token(&env))
.expect("token not set");
token::Client::new(&env, &token_addr).transfer(
&env.current_contract_address(),
&recipient,
&amount,
);
env.storage()
.persistent()
.set(&key_balance(&env), &0i128);
let ts = env.ledger().timestamp();
let mut log: Vec<(Address, i128, u64)> = env
.storage()
.persistent()
.get(&key_wlog(&env))
.unwrap_or(Vec::new(&env));
log.push_back((recipient.clone(), amount, ts));
env.storage().persistent().set(&key_wlog(&env), &log);
env.events().publish(
(symbol_short!("EmrgDrain"),),
(recipient, amount, ts),
);
amount
}
/// Returns the current treasury XLM balance.
///
/// Read-only — does not modify state. Matches the sum of all deposits
/// minus all withdrawals.
///
/// # Returns
///
/// Returns the current `BALANCE` in stroops. Returns `0` if never set.
pub fn get_balance(env: Env) -> i128 {
env.storage()
.persistent()
.get(&key_balance(&env))
.unwrap_or(0)
}
/// Returns lifetime cumulative fees collected.
///
/// Read-only — does not modify state.
///
/// # Returns
///
/// Returns the cumulative `TOTAL_FEES_EARNED` in stroops. Returns `0` if never set.
pub fn get_total_fees_earned(env: Env) -> i128 {
env.storage()
.persistent()
.get(&key_total_fees(&env))
.unwrap_or(0)
}
/// Returns the complete log of all past withdrawals from the treasury.
///
/// Each entry is a tuple of `(recipient, amount, timestamp)`. Read-only —
/// does not modify state.
///
/// # Returns
///
/// Returns a [`Vec`] of `(Address, i128, u64)` tuples, one per withdrawal,
/// in the order they occurred. Returns an empty `Vec` if no withdrawals have occurred.
pub fn get_withdrawal_log(env: Env) -> Vec<(Address, i128, u64)> {
env.storage()
.persistent()
.get(&key_wlog(&env))
.unwrap_or(Vec::new(&env))
}
/// Returns the stored fee basis points.
///
/// Read-only — does not modify state.
///
/// # Returns
///
/// Returns the `FEE_BPS` value set during initialization.
pub fn get_fee_bps(env: Env) -> u32 {
env.storage()
.persistent()
.get(&key_fee_bps(&env))
.unwrap_or(0)
}
/// Returns the stored fee recipient address.
///
/// Read-only — does not modify state.
///
/// # Returns
///
/// Returns the `FEE_RECIPIENT` address set during initialization.
pub fn get_fee_recipient(env: Env) -> Address {
env.storage()
.persistent()
.get(&key_fee_recipient(&env))
.expect("not initialized")
}
}
// ─── TESTS ────────────────────────────────────────────────────────────────────
#[cfg(test)]
mod tests {
use super::*;
use shared::test_utils::{create_test_address, create_test_env};
use soroban_sdk::IntoVal;
#[test]
fn test_initialize_success() {
let env = create_test_env();
let admin = create_test_address(&env);
let factory = create_test_address(&env);
let fee_recipient = create_test_address(&env);
let token = create_test_address(&env);
let contract_id = env.register_contract(None, Treasury);
let client = TreasuryClient::new(&env, &contract_id);
client.initialize(&admin, &200u32, &fee_recipient, &factory, &token);
assert_eq!(client.get_balance(), 0);
assert_eq!(client.get_total_fees_earned(), 0);
assert_eq!(client.get_fee_bps(), 0);
assert_eq!(client.get_withdrawal_log().len(), 0);
assert_eq!(client.get_fee_bps(), 200);
assert_eq!(client.get_fee_recipient(), fee_recipient);
}
#[test]
#[should_panic(expected = "already initialized")]
fn test_double_initialize_panics() {
let env = create_test_env();
let admin = create_test_address(&env);
let factory = create_test_address(&env);
let fee_recipient = create_test_address(&env);
let token = create_test_address(&env);
let contract_id = env.register_contract(None, Treasury);
let client = TreasuryClient::new(&env, &contract_id);
client.initialize(&admin, &200u32, &fee_recipient, &factory, &token);
client.initialize(&admin, &200u32, &fee_recipient, &factory, &token); // must panic
}
#[test]
#[should_panic(expected = "fee_bps exceeds maximum of 1000 (10%)")]
fn test_initialize_fee_bps_exceeds_maximum() {
let env = create_test_env();
let admin = create_test_address(&env);
let factory = create_test_address(&env);
let fee_recipient = create_test_address(&env);
let token = create_test_address(&env);
let contract_id = env.register_contract(None, Treasury);
let client = TreasuryClient::new(&env, &contract_id);
client.initialize(&admin, &1001u32, &fee_recipient, &factory, &token);
}
#[test]
fn test_initialize_fee_bps_at_maximum() {
let env = create_test_env();
let admin = create_test_address(&env);
let factory = create_test_address(&env);
let fee_recipient = create_test_address(&env);
let token = create_test_address(&env);
let contract_id = env.register_contract(None, Treasury);
let client = TreasuryClient::new(&env, &contract_id);
client.initialize(&admin, &1000u32, &fee_recipient, &factory, &token);
assert_eq!(client.get_fee_bps(), 1000);
}
}