forked from StellarSplit/StellarSplit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
629 lines (542 loc) · 20.7 KB
/
Copy pathlib.rs
File metadata and controls
629 lines (542 loc) · 20.7 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
#![no_std]
use soroban_sdk::{contract, contractimpl, token, Address, Env, Map, String, Vec};
mod errors;
mod events;
mod fees;
mod storage;
mod test;
mod types;
pub use crate::errors::Error;
pub use crate::types::{ParticipantBalance, Split, SplitStatus};
const DEFAULT_MAX_PARTICIPANTS: u32 = 50;
/// Mandatory delay between `schedule_unpause` and a successful `unpause` (48 hours).
const UNPAUSE_TIMELOCK_SECONDS: u64 = 172_800;
const MAX_NOTE_LEN: u32 = 128;
const MAX_METADATA_ENTRIES: u32 = 32;
const MAX_METADATA_STRING_LEN: u32 = 128;
fn validate_note_len(note: &String) -> Result<(), Error> {
if note.len() > MAX_NOTE_LEN {
return Err(Error::InvalidInput);
}
Ok(())
}
fn participant_known(participants: &Vec<Address>, addr: &Address) -> bool {
let mut i = 0u32;
while i < participants.len() {
if participants.get(i).unwrap() == *addr {
return true;
}
i += 1;
}
false
}
fn validate_metadata(metadata: &Map<String, String>) -> Result<(), Error> {
if metadata.len() > MAX_METADATA_ENTRIES {
return Err(Error::InvalidMetadata);
}
let keys = metadata.keys();
let mut i = 0u32;
while i < keys.len() {
let key = keys.get(i).unwrap();
let value = metadata.get(key.clone()).unwrap();
if key.len() > MAX_METADATA_STRING_LEN || value.len() > MAX_METADATA_STRING_LEN {
return Err(Error::InvalidMetadata);
}
i += 1;
}
Ok(())
}
fn is_active(status: &SplitStatus) -> bool {
*status != SplitStatus::Released && *status != SplitStatus::Cancelled
}
/// Authenticate `admin` against the stored admin address.
fn require_admin(env: &Env, admin: &Address) -> Result<(), Error> {
admin.require_auth();
if !storage::has_admin(env) {
return Err(Error::NotInitialized);
}
if *admin != storage::get_admin(env) {
return Err(Error::Unauthorized);
}
Ok(())
}
/// Reject state-changing operations while the emergency freeze is active.
fn require_not_paused(env: &Env) -> Result<(), Error> {
if storage::is_paused(env) {
return Err(Error::ContractPaused);
}
Ok(())
}
#[contract]
pub struct SplitEscrowContract;
#[contractimpl]
impl SplitEscrowContract {
pub fn initialize(
env: Env,
admin: Address,
token_address: Address,
version: String,
) -> Result<(), Error> {
if storage::has_admin(&env) {
return Err(Error::AlreadyInitialized);
}
admin.require_auth();
validate_version(&version)?;
storage::set_admin(&env, &admin);
storage::set_token(&env, &token_address);
storage::set_fee_bps(&env, 0u32);
storage::set_version(&env, &version);
events::emit_initialized(&env, &admin);
Ok(())
}
pub fn get_version(env: Env) -> String {
storage::get_version(&env)
}
pub fn upgrade_version(env: Env, new_version: String) -> Result<(), Error> {
let admin = storage::get_admin(&env);
admin.require_auth();
validate_version(&new_version)?;
let old_version = storage::get_version(&env);
storage::set_version(&env, &new_version);
events::emit_contract_upgraded(&env, old_version, new_version);
Ok(())
}
/// Admin-only emergency freeze: halts `deposit`, `release_funds` and `cancel_split`
/// while leaving all escrow state and read-only functions untouched.
///
/// Pausing also discards any pending unpause schedule, so a re-pause always
/// restarts the full 48-hour timelock rather than inheriting an elapsed one.
pub fn pause(env: Env, admin: Address) -> Result<(), Error> {
require_admin(&env, &admin)?;
if storage::is_paused(&env) {
return Err(Error::ContractPaused);
}
storage::set_paused(&env, true);
storage::clear_unpause_scheduled_at(&env);
events::emit_paused(&env, &admin);
Ok(())
}
/// Admin-only: start the mandatory 48-hour timelock before the contract can be
/// unfrozen. Calling it again restarts the timelock from the current ledger time.
pub fn schedule_unpause(env: Env, admin: Address) -> Result<(), Error> {
require_admin(&env, &admin)?;
if !storage::is_paused(&env) {
return Err(Error::NotPaused);
}
let unpause_at = env
.ledger()
.timestamp()
.checked_add(UNPAUSE_TIMELOCK_SECONDS)
.ok_or(Error::InvalidInput)?;
storage::set_unpause_scheduled_at(&env, unpause_at);
events::emit_unpause_scheduled(&env, &admin, unpause_at);
Ok(())
}
/// Admin-only: lift the emergency freeze. Fails unless `schedule_unpause` was
/// called at least 48 hours earlier.
pub fn unpause(env: Env, admin: Address) -> Result<(), Error> {
require_admin(&env, &admin)?;
if !storage::is_paused(&env) {
return Err(Error::NotPaused);
}
let unpause_at =
storage::get_unpause_scheduled_at(&env).ok_or(Error::UnpauseNotScheduled)?;
if env.ledger().timestamp() < unpause_at {
return Err(Error::TimelockNotElapsed);
}
storage::set_paused(&env, false);
storage::clear_unpause_scheduled_at(&env);
events::emit_unpaused(&env, &admin);
Ok(())
}
/// Public read of the emergency freeze state.
pub fn is_paused(env: Env) -> bool {
storage::is_paused(&env)
}
/// Public read of the earliest timestamp at which `unpause` may succeed,
/// or `None` when no unpause is scheduled.
pub fn get_unpause_scheduled_at(env: Env) -> Option<u64> {
storage::get_unpause_scheduled_at(&env)
}
/// Create an escrow split. If `max_participants` is `None`, the cap defaults to 50.
/// `metadata` must satisfy map size and string length limits. If `note` is `None`, note is empty.
/// `payee` selects single-payee mode: when `None`, every participant's released share goes
/// to `creator` (original behavior); when `Some(addr)`, it goes to `addr` instead.
pub fn create_escrow(
env: Env,
creator: Address,
description: String,
total_amount: i128,
metadata: Map<String, String>,
obligations: Map<Address, i128>,
max_participants: Option<u32>,
whitelist_enabled: bool,
note: Option<String>,
payee: Option<Address>,
) -> Result<u64, Error> {
if !storage::has_admin(&env) {
return Err(Error::NotInitialized);
}
creator.require_auth();
if total_amount <= 0 {
return Err(Error::InvalidAmount);
}
// Validate that total_amount matches sum of obligations.
let mut sum_obligations = 0i128;
let keys = obligations.keys();
for i in 0..keys.len() {
let key = keys.get(i).unwrap();
let val = obligations.get(key).unwrap();
if val <= 0 {
return Err(Error::InvalidAmount);
}
sum_obligations += val;
}
if sum_obligations != total_amount {
return Err(Error::TotalAmountMismatch);
}
let cap = max_participants.unwrap_or(DEFAULT_MAX_PARTICIPANTS);
validate_metadata(&metadata)?;
let note_stored = match note {
Some(n) => {
validate_note_len(&n)?;
n
}
None => String::from_str(&env, ""),
};
let split_id = storage::get_next_split_id(&env);
storage::bump_next_split_id(&env);
let participants = Vec::new(&env);
let split = Split {
split_id,
creator,
description,
metadata,
total_amount,
deposited_amount: 0,
status: SplitStatus::Pending,
max_participants: cap,
participants,
balances: Map::new(&env),
deposits: Map::new(&env),
obligations,
note: note_stored,
payee,
};
storage::set_split(&env, &split);
storage::set_whitelist_enabled(&env, split_id, whitelist_enabled);
events::emit_split_created(&env, &split);
Ok(split_id)
}
/// Creator-only: update the on-chain note while the escrow is active (Pending or Ready).
pub fn set_note(env: Env, split_id: u64, note: String) -> Result<(), Error> {
validate_note_len(¬e)?;
let mut split = storage::get_split(&env, split_id).ok_or(Error::SplitNotFound)?;
split.creator.require_auth();
if !is_active(&split.status) {
return Err(Error::SplitNotActive);
}
if split.note == note {
return Ok(());
}
split.note = note.clone();
storage::set_split(&env, &split);
events::emit_note_updated(&env, split_id, ¬e);
Ok(())
}
/// Cancel a split and refund all deposited participant balances.
/// Used when a dispute is upheld (raiser wins).
pub fn cancel_split(env: Env, split_id: u64) -> Result<(), Error> {
require_not_paused(&env)?;
let mut split = storage::get_split(&env, split_id).ok_or(Error::SplitNotFound)?;
// Only the split creator can cancel/refund.
split.creator.require_auth();
if split.status == SplitStatus::Released || split.status == SplitStatus::Cancelled {
return Err(Error::SplitNotActive);
}
let token_address = storage::get_token(&env);
let token_client = token::Client::new(&env, &token_address);
// Refund all distinct participants.
let participants_len = split.participants.len();
let mut i = 0u32;
while i < participants_len {
let participant = split.participants.get(i).unwrap();
let amount = split.balances.get(participant.clone()).unwrap_or(0i128);
if amount > 0 {
token_client.transfer(&env.current_contract_address(), &participant, &amount);
split.balances.set(participant.clone(), 0i128);
split.deposits.set(participant, 0i128);
}
i += 1;
}
// Clear participants list; split is now cancelled and cannot be released.
split.participants = Vec::new(&env);
split.deposited_amount = 0;
split.status = SplitStatus::Cancelled;
storage::set_split(&env, &split);
events::emit_cancelled(&env, split_id);
Ok(())
}
/// Public read of the escrow note (empty string if none was set).
pub fn get_note(env: Env, split_id: u64) -> Result<String, Error> {
let split = storage::get_split(&env, split_id).ok_or(Error::SplitNotFound)?;
Ok(split.note.clone())
}
pub fn deposit(
env: Env,
split_id: u64,
participant: Address,
amount: i128,
) -> Result<(), Error> {
require_not_paused(&env)?;
participant.require_auth();
if amount <= 0 {
return Err(Error::InvalidAmount);
}
let mut split = storage::get_split(&env, split_id).ok_or(Error::SplitNotFound)?;
if split.status != SplitStatus::Pending {
return Err(Error::SplitNotPending);
}
if storage::is_whitelist_enabled(&env, split_id)
&& !storage::is_whitelisted(&env, split_id, &participant)
{
return Err(Error::Unauthorized);
}
let obligation = split
.obligations
.get(participant.clone())
.ok_or(Error::ParticipantNotOwed)?;
if obligation <= 0 {
return Err(Error::InvalidAmount);
}
let updated_total_deposit = split
.deposited_amount
.checked_add(amount)
.ok_or(Error::InvalidAmount)?;
if updated_total_deposit > split.total_amount {
return Err(Error::InvalidAmount);
}
let previous_deposit = split.deposits.get(participant.clone()).unwrap_or(0i128);
let updated_deposit = previous_deposit
.checked_add(amount)
.ok_or(Error::InvalidAmount)?;
if updated_deposit > obligation {
return Err(Error::InvalidAmount);
}
if !participant_known(&split.participants, &participant) {
if split.participants.len() >= split.max_participants {
return Err(Error::ParticipantCapExceeded);
}
split.participants.push_back(participant.clone());
}
split.deposits.set(participant.clone(), updated_deposit);
split.balances.set(participant.clone(), updated_deposit);
let token_address = storage::get_token(&env);
let token_client = token::Client::new(&env, &token_address);
token_client.transfer(&participant, &env.current_contract_address(), &amount);
split.deposited_amount = updated_total_deposit;
if split.deposited_amount >= split.total_amount {
split.status = SplitStatus::Ready;
}
storage::set_split(&env, &split);
events::emit_deposit(&env, split_id, &participant, amount);
emit_deposit_thresholds(
&env,
split_id,
&participant,
previous_deposit,
updated_deposit,
obligation,
);
Ok(())
}
pub fn get_participant_balance(
env: Env,
split_id: u64,
participant: Address,
) -> Result<ParticipantBalance, Error> {
let split = storage::get_split(&env, split_id).ok_or(Error::SplitNotFound)?;
let owed = split
.obligations
.get(participant.clone())
.ok_or(Error::ParticipantNotOwed)?;
let deposited = split.deposits.get(participant).unwrap_or(0i128);
let remaining = if deposited >= owed {
0i128
} else {
owed - deposited
};
Ok(ParticipantBalance {
deposited,
owed,
remaining,
})
}
pub fn add_to_whitelist(env: Env, split_id: u64, address: Address) -> Result<(), Error> {
let split = storage::get_split(&env, split_id).ok_or(Error::SplitNotFound)?;
split.creator.require_auth();
storage::add_to_whitelist(&env, split_id, &address);
Ok(())
}
pub fn remove_from_whitelist(env: Env, split_id: u64, address: Address) -> Result<(), Error> {
let split = storage::get_split(&env, split_id).ok_or(Error::SplitNotFound)?;
split.creator.require_auth();
storage::remove_from_whitelist(&env, split_id, &address);
Ok(())
}
pub fn toggle_whitelist(env: Env, split_id: u64, enabled: bool) -> Result<(), Error> {
let split = storage::get_split(&env, split_id).ok_or(Error::SplitNotFound)?;
split.creator.require_auth();
storage::set_whitelist_enabled(&env, split_id, enabled);
Ok(())
}
/// Finalize a `Ready` split: collects the protocol fee (if any), then pays out each
/// participant's share of the remaining balance to the split's payee (or `creator` in
/// single-payee mode). Emits one `FundsReleasedToParticipant` event per participant plus
/// one summary `FundsReleased` event for the total net amount distributed.
pub fn release_funds(env: Env, split_id: u64) -> Result<(), Error> {
require_not_paused(&env)?;
let mut split = storage::get_split(&env, split_id).ok_or(Error::SplitNotFound)?;
// Only the split creator can finalize settlement.
split.creator.require_auth();
if split.status != SplitStatus::Ready {
return Err(Error::SplitNotReady);
}
let total = split.deposited_amount;
let fee_amount = fees::collect_fee(&env, total)?;
let net_total = total - fee_amount;
let token_address = storage::get_token(&env);
let token_client = token::Client::new(&env, &token_address);
// Single-payee mode: every participant's share lands on `payee` if the
// creator configured one, otherwise on `creator` itself (this matches
// the contract's original, pre-fix behavior when `payee` is `None`).
let payee = split.payee.clone().unwrap_or_else(|| split.creator.clone());
// At this point split.status == Ready, which only happens once
// deposited_amount == total_amount. Since every participant's balance
// is capped at their obligation and balances sum to deposited_amount,
// every participant's balance is exactly equal to their obligation —
// so iterating obligations here is equivalent to iterating balances.
let keys = split.obligations.keys();
let num_keys = keys.len();
let mut distributed = 0i128;
for i in 0..num_keys {
let participant = keys.get(i).unwrap();
let obligation = split.obligations.get(participant.clone()).unwrap();
// Split net_total proportionally to each participant's obligation.
// The last participant absorbs the rounding remainder so the full
// net_total is always paid out, even when fees introduce integer
// division dust.
let share = if i + 1 == num_keys {
net_total - distributed
} else {
(obligation * net_total) / total
};
distributed += share;
if share > 0 {
token_client.transfer(&env.current_contract_address(), &payee, &share);
events::emit_funds_released_to_participant(&env, split_id, &participant, share);
}
}
split.status = SplitStatus::Released;
storage::set_split(&env, &split);
events::emit_released(&env, split_id, net_total);
Ok(())
}
/// Alias for cancellation that matches the dispute contract's "reverse_split" concept.
pub fn reverse_split(env: Env, split_id: u64) -> Result<(), Error> {
Self::cancel_split(env, split_id)
}
pub fn set_fee(env: Env, fee_bps: u32) -> Result<(), Error> {
fees::set_fee(&env, fee_bps)
}
pub fn set_treasury(env: Env, address: Address) -> Result<(), Error> {
fees::set_treasury(&env, &address)
}
/// Returns escrow state including `max_participants` and `participants` (count =
/// `participants.len()`).
pub fn get_escrow(env: Env, split_id: u64) -> Result<Split, Error> {
storage::get_split(&env, split_id).ok_or(Error::SplitNotFound)
}
/// View helper for dispute-resolution auth checks.
pub fn get_creator(env: Env, split_id: u64) -> Result<Address, Error> {
let split = storage::get_split(&env, split_id).ok_or(Error::SplitNotFound)?;
Ok(split.creator)
}
pub fn get_metadata(env: Env, split_id: u64) -> Result<Map<String, String>, Error> {
let split = storage::get_split(&env, split_id).ok_or(Error::SplitNotFound)?;
Ok(split.metadata)
}
pub fn update_metadata(
env: Env,
split_id: u64,
metadata: Map<String, String>,
) -> Result<(), Error> {
validate_metadata(&metadata)?;
let mut split = storage::get_split(&env, split_id).ok_or(Error::SplitNotFound)?;
split.creator.require_auth();
if !is_active(&split.status) {
return Err(Error::SplitNotActive);
}
split.metadata = metadata;
storage::set_split(&env, &split);
Ok(())
}
}
fn emit_deposit_thresholds(
env: &Env,
split_id: u64,
participant: &Address,
previous_deposit: i128,
updated_deposit: i128,
obligation: i128,
) {
let half_obligation = obligation / 2;
if previous_deposit < half_obligation && updated_deposit >= half_obligation {
events::emit_partial_threshold_reached(
env,
split_id,
participant,
updated_deposit,
obligation,
50u32,
);
}
if previous_deposit < obligation && updated_deposit >= obligation {
events::emit_partial_threshold_reached(
env,
split_id,
participant,
updated_deposit,
obligation,
100u32,
);
}
}
fn validate_version(version: &String) -> Result<(), Error> {
let len = version.len() as usize;
if len == 0 || len > 32 {
return Err(Error::InvalidVersion);
}
let mut buf = [0u8; 32];
version.copy_into_slice(&mut buf[..len]);
let mut dot_count = 0;
let mut part_len = 0;
for i in 0..len {
let b = buf[i];
if b == b'.' {
if part_len == 0 {
return Err(Error::InvalidVersion);
}
dot_count += 1;
part_len = 0;
} else if b >= b'0' && b <= b'9' {
part_len += 1;
} else {
return Err(Error::InvalidVersion);
}
}
if dot_count != 2 || part_len == 0 {
return Err(Error::InvalidVersion);
}
Ok(())
}