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
428 lines (362 loc) · 13.8 KB
/
Copy pathlib.rs
File metadata and controls
428 lines (362 loc) · 13.8 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
#![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::{Split, SplitStatus};
const DEFAULT_MAX_PARTICIPANTS: u32 = 50;
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 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
}
#[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(())
}
/// Create an escrow split. If `max_participants` is `None`, the cap defaults to 50.
/// `metadata` is fully optional but must be valid per constraints. If `note` is `None`, note is empty.
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>,
metadata: Option<Map<String, String>>,
) -> 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);
if obligations.len() > cap {
return Err(Error::ParticipantCapExceeded);
}
validate_metadata(&metadata)?;
let note_stored = match note {
Some(n) => {
validate_note_len(&n)?;
n
}
None => String::from_str(&env, ""),
};
let metadata_stored = match metadata {
Some(m) => {
validate_metadata(&m)?;
m
}
None => Map::new(&env),
};
// Whitelist functionality is supported via add/remove calls, but default is disabled.
// Toggling is now possible via `toggle_whitelist`.
let whitelist_enabled = false;
let split_id = storage::get_next_split_id(&env);
storage::bump_next_split_id(&env);
let mut participants = Vec::new(&env);
for i in 0..keys.len() {
participants.push_back(keys.get(i).unwrap());
}
let split = Split {
split_id,
creator,
description,
metadata: metadata_stored,
total_amount,
deposited_amount: 0,
status: SplitStatus::Pending,
max_participants: cap,
participants,
balances: Map::new(&env),
obligations,
note: note_stored,
};
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(())
}
pub fn cancel_split(env: Env, split_id: u64) -> Result<(), Error> {
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);
// Zero out balances to prevent accidental double-refund.
split.balances.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> {
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);
}
// Whitelist check if enabled.
if storage::is_whitelist_enabled(&env, split_id)
&& !storage::is_whitelisted(&env, split_id, &participant)
{
return Err(Error::Unauthorized);
}
// Track per-participant deposited balances so we can refund on dispute outcomes.
let previous_balance = split.balances.get(participant.clone()).unwrap_or(0i128);
if previous_balance == 0 {
if split.participants.len() >= split.max_participants {
return Err(Error::ParticipantCapExceeded);
}
split.participants.push_back(participant.clone());
}
// Track per-participant deposited balances so we can refund on dispute outcomes.
let previous_balance = split.balances.get(participant.clone()).unwrap_or(0i128);
split
.balances
.set(participant.clone(), previous_balance + amount);
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
.balances
.set(participant.clone(), current_balance + amount);
split.deposited_amount += amount;
// Check if all obligations are met to transition to Ready.
if split.deposited_amount == split.total_amount {
split.status = SplitStatus::Ready;
}
storage::set_split(&env, &split);
events::emit_deposit(&env, split_id, &participant, amount);
Ok(())
}
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(())
}
pub fn release_funds(env: Env, split_id: u64) -> Result<(), Error> {
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 creator_amount = total - fee_amount;
let token_address = storage::get_token(&env);
let token_client = token::Client::new(&env, &token_address);
token_client.transfer(
&env.current_contract_address(),
&split.creator,
&creator_amount,
);
split.status = SplitStatus::Released;
storage::set_split(&env, &split);
events::emit_released(&env, split_id, creator_amount);
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 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(())
}