forked from stellarmarket-labs/stellar-market
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathescrow.diff
More file actions
848 lines (797 loc) · 63.3 KB
/
Copy pathescrow.diff
File metadata and controls
848 lines (797 loc) · 63.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
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
diff --git a/contracts/escrow/src/lib.rs b/contracts/escrow/src/lib.rs
index ee83879..69ad1cc 100644
--- a/contracts/escrow/src/lib.rs
+++ b/contracts/escrow/src/lib.rs
@@ -61,7 +61,7 @@ pub enum EscrowError {
/// The milestone list is empty.
EmptyMilestones = 33,
/// The number of milestones exceeds the permitted limit.
- TooManyMilestones = 34,
+ TooManyMilestones = 48,
/// The fee basis points exceed the maximum permitted limit.
InvalidFee = 35,
/// Proposal execution is time-locked and cannot be executed yet.
@@ -81,6 +81,16 @@ pub enum EscrowError {
OracleUnavailable = 42,
/// An arithmetic overflow occurred while computing the deposited value.
ValueOverflow = 43,
+ /// A milestone amount is invalid (zero or negative).
+ InvalidMilestone = 44,
+ /// Slippage check failed: token value at release time is below the minimum.
+ SlippageExceeded = 45,
+ /// A replayed nonce was detected within the TTL window.
+ NonceReplay = 46,
+ /// A milestone deadline is not strictly after the previous milestone's deadline.
+ MilestoneDeadlinesNotOrdered = 47,
+ /// A milestone deadline is in the past or equal to the current ledger timestamp.
+ MilestoneDeadlineInPast = 49,
}
/// Privileged actions that can be proposed and approved through the multi-sig flow.
@@ -197,6 +207,15 @@ pub enum DisputeResolution {
MaliciousFiling,
}
+#[contracttype]
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub struct PayoutBreakdown {
+ pub client: i128,
+ pub freelancer: i128,
+ pub platform: i128,
+ pub arbitrators: i128,
+}
+
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum MilestoneStatus {
@@ -253,7 +272,7 @@ pub struct Job {
pub expiry_ledger: u32,
}
-const MAX_FEE_BPS: u32 = 1000; // 10%
+const MAX_FEE_BPS: u32 = 500; // 5%
const MAX_MILESTONES: u32 = 50;
/// A formal proposal to revise the milestones and total budget of an active job.
@@ -322,6 +341,10 @@ enum DataKey {
PriceOracle,
/// Stored RateSnapshot from the parity check performed at funding time.
RateSnapshot(u64),
+ /// Per-caller nonce to prevent replay attacks within the TTL window.
+ Nonce(Address, Symbol, u64),
+ /// Registered dispute contract ΓÇö the only address allowed to call mark_job_disputed.
+ DisputeContract,
}
/// Fixed-point scale for oracle prices: prices are quoted in XLM stroops per token
@@ -341,10 +364,22 @@ const INACTIVITY_GRACE_SECS: u64 = 3 * 24 * 3600;
const MULTISIG_TIME_LOCK_SECS: u64 = 48 * 60 * 60;
const PROPOSAL_TTL: u64 = 7 * 24 * 60 * 60;
+const NONCE_EXPIRY_LEDGERS: u32 = 3;
+
fn get_job_key(job_id: u64) -> DataKey {
DataKey::Job(job_id)
}
+fn consume_nonce(env: &Env, caller: &Address, function: &Symbol, nonce: u64) -> Result<(), EscrowError> {
+ let key = DataKey::Nonce(caller.clone(), function.clone(), nonce);
+ if env.storage().temporary().has(&key) {
+ return Err(EscrowError::NonceReplay);
+ }
+ env.storage().temporary().set(&key, &true);
+ env.storage().temporary().extend_ttl(&key, NONCE_EXPIRY_LEDGERS, NONCE_EXPIRY_LEDGERS);
+ Ok(())
+}
+
fn require_not_paused(env: &Env) -> Result<(), EscrowError> {
env.storage()
.instance()
@@ -391,6 +426,17 @@ pub struct TtlExtendedEvent {
pub new_expiry_ledger: u32,
}
+#[contracttype]
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub struct Paused {
+ pub paused_by: Address,
+}
+
+#[contracttype]
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub struct Unpaused {
+ pub unpaused_by: Address,
+}
fn bump_escrow_ttl(env: &Env, job_id: u64) {
@@ -736,6 +782,56 @@ impl EscrowContract {
env.storage().instance().get(&DataKey::PriceOracle)
}
+ /// Register the dispute contract address. Only a registered multisig signer may call this.
+ pub fn set_dispute_contract(
+ env: Env,
+ admin: Address,
+ dispute_contract: Address,
+ ) -> Result<(), EscrowError> {
+ admin.require_auth();
+ if !is_signer(&env, &admin) {
+ return Err(EscrowError::NotAdmin);
+ }
+ env.storage()
+ .instance()
+ .set(&DataKey::DisputeContract, &dispute_contract);
+ Ok(())
+ }
+
+ /// Called by the registered dispute contract to transition a job to the Disputed state
+ /// and emit a structured DisputeRaised event that indexers can consume.
+ pub fn mark_job_disputed(
+ env: Env,
+ job_id: u64,
+ dispute_id: u64,
+ ) -> Result<(), EscrowError> {
+ let dispute_contract: Address = env
+ .storage()
+ .instance()
+ .get(&DataKey::DisputeContract)
+ .ok_or(EscrowError::Unauthorized)?;
+ dispute_contract.require_auth();
+
+ let mut job: Job = env
+ .storage()
+ .persistent()
+ .get(&get_job_key(job_id))
+ .ok_or(EscrowError::JobNotFound)?;
+ bump_job_ttl(&env, job_id);
+
+ require_state_disputable(&job)?;
+
+ job.status = JobStatus::Disputed;
+ env.storage().persistent().set(&get_job_key(job_id), &job);
+
+ env.events().publish(
+ (symbol_short!("escrow"), Symbol::new(&env, "disputed")),
+ (job_id, dispute_id, job.client, job.freelancer),
+ );
+
+ Ok(())
+ }
+
/// Return the exchange-rate parity snapshot recorded when the job was funded.
/// `None` for jobs funded without oracle validation (legacy / XLM-only).
pub fn get_rate_snapshot(env: Env, job_id: u64) -> Option<RateSnapshot> {
@@ -917,15 +1013,19 @@ impl EscrowContract {
AdminAction::Pause => {
env.storage().instance().set(&DataKey::Paused, &true);
env.events().publish(
- (symbol_short!("paused"),),
- (env.current_contract_address(), env.ledger().timestamp()),
+ (symbol_short!("escrow"), symbol_short!("paused")),
+ Paused {
+ paused_by: proposal.proposer.clone()
+ },
);
}
AdminAction::Unpause => {
env.storage().instance().set(&DataKey::Paused, &false);
env.events().publish(
- (symbol_short!("unpaused"),),
- (env.current_contract_address(), env.ledger().timestamp()),
+ (symbol_short!("escrow"), symbol_short!("unpaused")),
+ Unpaused {
+ unpaused_by: proposal.proposer.clone()
+ },
);
}
AdminAction::SetFeeBps(fee) => {
@@ -1021,13 +1121,12 @@ impl EscrowContract {
bump_job_ttl(&env, job_id);
// Compute the remaining escrowed balance (total minus already-approved milestones).
- let approved_amount: i128 = job
- .milestones
- .iter()
- .filter(|m| m.status == MilestoneStatus::Approved)
- .map(|m| m.amount)
- .sum();
- let withdrawable = job.total_amount - approved_amount;
+ let withdrawable: i128 = job
+ .milestones
+ .iter()
+ .filter(|m| m.status != MilestoneStatus::Approved)
+ .map(|m| m.amount)
+ .sum();
if withdrawable <= 0 {
return Err(EscrowError::NoFundsToWithdraw);
@@ -1129,16 +1228,27 @@ impl EscrowContract {
let mut total: i128 = 0;
let mut milestone_vec: Vec<Milestone> = Vec::new(&env);
+ let mut prev_deadline: u64 = 0;
for (i, m) in milestones.iter().enumerate() {
let (desc, amount, deadline) = m;
+ if amount <= 0 {
+ return Err(EscrowError::InvalidMilestone);
+ }
if deadline <= env.ledger().timestamp() {
- return Err(EscrowError::InvalidDeadline);
+ return Err(EscrowError::MilestoneDeadlineInPast);
}
if deadline > job_deadline {
return Err(EscrowError::InvalidDeadline);
}
+ if i > 0 && deadline <= prev_deadline {
+ return Err(EscrowError::MilestoneDeadlinesNotOrdered);
+ }
+ prev_deadline = deadline;
total += amount;
+ if total > i128::MAX / 2 {
+ return Err(EscrowError::InvalidMilestone);
+ }
milestone_vec.push_back(Milestone {
id: i as u32,
description: desc,
@@ -1344,15 +1454,13 @@ impl EscrowContract {
// STATE VALIDATION: Job must be in a disputable state
require_state_disputable(&job)?;
- let approved_amount: i128 = job
+ let remaining: i128 = job
.milestones
.iter()
- .filter(|m| m.status == MilestoneStatus::Approved)
+ .filter(|m| m.status != MilestoneStatus::Approved)
.map(|m| m.amount)
.sum();
- let remaining = job.total_amount - approved_amount;
-
if remaining > 0 {
// Funds remain ΓÇö transfer them according to the resolution outcome.
let token_client = token::Client::new(&env, &job.token);
@@ -1446,6 +1554,67 @@ impl EscrowContract {
Ok(())
}
+ /// Pure payout breakdown for a dispute resolution. No state is read or
+ /// written ΓÇö safe for frontend preview without a transaction.
+ /// All four amounts always sum to `escrow_amount` (no dust).
+ pub fn calculate_payout(
+ _env: Env,
+ escrow_amount: i128,
+ platform_fee_bps: u32,
+ arbitrator_fee_bps: u32,
+ outcome: DisputeResolution,
+ ) -> PayoutBreakdown {
+ let platform_fee = (escrow_amount * platform_fee_bps as i128) / 10_000;
+ let arbitrator_fee = (escrow_amount * arbitrator_fee_bps as i128) / 10_000;
+ let remaining = escrow_amount - platform_fee - arbitrator_fee;
+
+ match outcome {
+ DisputeResolution::ClientWins => PayoutBreakdown {
+ client: remaining,
+ freelancer: 0,
+ platform: platform_fee,
+ arbitrators: arbitrator_fee,
+ },
+ DisputeResolution::FreelancerWins => PayoutBreakdown {
+ client: 0,
+ freelancer: remaining,
+ platform: platform_fee,
+ arbitrators: arbitrator_fee,
+ },
+ DisputeResolution::RefundBoth => {
+ let half = remaining / 2;
+ PayoutBreakdown {
+ client: half,
+ freelancer: remaining - half,
+ platform: platform_fee,
+ arbitrators: arbitrator_fee,
+ }
+ }
+ DisputeResolution::RefundSplit(pct_client) => {
+ let pct = if pct_client > 100 { 100 } else { pct_client } as i128;
+ let client_amount = (remaining * pct) / 100;
+ PayoutBreakdown {
+ client: client_amount,
+ freelancer: remaining - client_amount,
+ platform: platform_fee,
+ arbitrators: arbitrator_fee,
+ }
+ }
+ DisputeResolution::Escalate => PayoutBreakdown {
+ client: 0,
+ freelancer: 0,
+ platform: 0,
+ arbitrators: 0,
+ },
+ DisputeResolution::MaliciousFiling => PayoutBreakdown {
+ client: 0,
+ freelancer: 0,
+ platform: remaining + platform_fee,
+ arbitrators: arbitrator_fee,
+ },
+ }
+ }
+
/// Freelancer submits a milestone as completed.
pub fn submit_milestone(
env: Env,
@@ -1553,39 +1722,6 @@ impl EscrowContract {
return Err(EscrowError::InvalidStatus);
}
- // Release payment for this milestone
- let token_client = token::Client::new(&env, &job.token);
-
- let fee_bps: u32 = env
- .storage()
- .instance()
- .get(&symbol_short!("FEE"))
- .unwrap_or(0);
- let treasury: Address = env
- .storage()
- .instance()
- .get(&symbol_short!("TRE"))
- .unwrap_or(env.current_contract_address()); // Fallback to contract itself if not set, though it should be
-
- let fee_amount = (milestone.amount * fee_bps as i128) / 10_000;
- let freelancer_amount = milestone.amount - fee_amount;
-
- if fee_amount > 0 {
- token_client.transfer(&env.current_contract_address(), &treasury, &fee_amount);
-
- // Emit fee collected event
- env.events().publish(
- (symbol_short!("escrow"), symbol_short!("fee")),
- (job_id, milestone_id, fee_amount, treasury.clone()),
- );
- }
-
- token_client.transfer(
- &env.current_contract_address(),
- &job.freelancer,
- &freelancer_amount,
- );
-
let updated = Milestone {
id: milestone.id,
description: milestone.description.clone(),
@@ -1596,12 +1732,9 @@ impl EscrowContract {
milestones.set(milestone_id, updated);
job.milestones = milestones.clone();
- // Check if all milestones are approved
- let all_approved = milestones
- .iter()
- .all(|m| m.status == MilestoneStatus::Approved);
- if all_approved {
- job.status = JobStatus::Completed;
+ // Keep the job in InProgress; complete_job will finalize payment and transition to Completed.
+ if job.status != JobStatus::InProgress {
+ job.status = JobStatus::InProgress;
}
env.storage().persistent().set(&get_job_key(job_id), &job);
@@ -1628,14 +1761,6 @@ impl EscrowContract {
),
);
- // Emit PaymentReleased event when job reaches Completed status
- if all_approved {
- env.events().publish(
- (symbol_short!("escrow"), Symbol::new(&env, "pmt_released")),
- (job_id, job.freelancer.clone(), freelancer_amount),
- );
- }
-
Ok(())
}
@@ -1708,49 +1833,11 @@ impl EscrowContract {
}
}
- // Transfer all payments in a single transaction
- if total_released > 0 {
- let token_client = token::Client::new(&env, &job.token);
-
- let fee_bps: u32 = env
- .storage()
- .instance()
- .get(&symbol_short!("FEE"))
- .unwrap_or(0);
- let treasury: Address = env
- .storage()
- .instance()
- .get(&symbol_short!("TRE"))
- .unwrap_or(env.current_contract_address());
-
- let fee_amount = (total_released * fee_bps as i128) / 10_000;
- let freelancer_amount = total_released - fee_amount;
-
- if fee_amount > 0 {
- token_client.transfer(&env.current_contract_address(), &treasury, &fee_amount);
-
- // Emit fee collected event for the batch
- env.events().publish(
- (symbol_short!("escrow"), symbol_short!("fee_batch")),
- (job_id, fee_amount, treasury),
- );
- }
-
- token_client.transfer(
- &env.current_contract_address(),
- &job.freelancer,
- &freelancer_amount,
- );
- }
-
job.milestones = milestones.clone();
- // Check if all milestones are approved
- let all_approved = milestones
- .iter()
- .all(|m| m.status == MilestoneStatus::Approved);
- if all_approved {
- job.status = JobStatus::Completed;
+ // Keep the job in InProgress; complete_job will finalize payment and transition to Completed.
+ if job.status != JobStatus::InProgress {
+ job.status = JobStatus::InProgress;
}
env.storage().persistent().set(&get_job_key(job_id), &job);
@@ -1768,14 +1855,6 @@ impl EscrowContract {
),
);
- // Emit PaymentReleased event when job reaches Completed status
- if all_approved {
- env.events().publish(
- (symbol_short!("escrow"), Symbol::new(&env, "pmt_released")),
- (job_id, job.freelancer.clone(), total_released),
- );
- }
-
Ok(total_released)
}
@@ -1936,11 +2015,9 @@ impl EscrowContract {
milestones.set(milestone_id, updated);
job.milestones = milestones.clone();
- let all_approved = milestones
- .iter()
- .all(|m| m.status == MilestoneStatus::Approved);
- if all_approved {
- job.status = JobStatus::Completed;
+ // Keep the job in InProgress; complete_job will finalize payment and transition to Completed.
+ if job.status != JobStatus::InProgress {
+ job.status = JobStatus::InProgress;
}
env.storage().persistent().set(&get_job_key(job_id), &job);
@@ -1954,13 +2031,6 @@ impl EscrowContract {
(job_id, milestone_id, caller),
);
- if all_approved {
- env.events().publish(
- (symbol_short!("escrow"), Symbol::new(&env, "pmt_released")),
- (job_id, job.freelancer, freelancer_amount),
- );
- }
-
Ok(())
}
@@ -1982,7 +2052,9 @@ impl EscrowContract {
milestone_index: u32,
amount: i128,
client: Address,
+ nonce: u64,
) -> Result<(), EscrowError> {
+ consume_nonce(&env, &client, &Symbol::new(&env, "partial_pmt"), nonce)?;
bump_escrow_ttl(&env, job_id);
client.require_auth();
require_not_paused(&env)?;
@@ -2018,35 +2090,13 @@ impl EscrowContract {
return Err(EscrowError::InvalidPartialAmount);
}
- // Compute fee and net freelancer amount.
- let fee_bps: u32 = env
- .storage()
- .instance()
- .get(&symbol_short!("FEE"))
- .unwrap_or(0);
- let treasury: Address = env
- .storage()
- .instance()
- .get(&symbol_short!("TRE"))
- .unwrap_or(env.current_contract_address());
-
- let fee_amount = (amount * fee_bps as i128) / 10_000;
- let freelancer_amount = amount - fee_amount;
-
+ // Release partial payment to freelancer (no fee deducted per-milestone;
+ // the protocol fee is taken from remaining escrow on complete_job).
let token_client = token::Client::new(&env, &job.token);
-
- if fee_amount > 0 {
- token_client.transfer(&env.current_contract_address(), &treasury, &fee_amount);
- env.events().publish(
- (symbol_short!("escrow"), symbol_short!("fee")),
- (job_id, milestone_index, fee_amount, treasury.clone()),
- );
- }
-
token_client.transfer(
&env.current_contract_address(),
&job.freelancer,
- &freelancer_amount,
+ &amount,
);
// Deduct paid amount from milestone; transition status accordingly.
@@ -2067,12 +2117,9 @@ impl EscrowContract {
milestones.set(milestone_index, updated);
job.milestones = milestones.clone();
- // Check if all milestones are now fully paid.
- let all_approved = milestones
- .iter()
- .all(|m| m.status == MilestoneStatus::Approved);
- if all_approved {
- job.status = JobStatus::Completed;
+ // Keep the job in InProgress; complete_job will finalize payment and transition to Completed.
+ if job.status != JobStatus::InProgress {
+ job.status = JobStatus::InProgress;
}
env.storage().persistent().set(&get_job_key(job_id), &job);
@@ -2083,16 +2130,101 @@ impl EscrowContract {
let freelancer = job.freelancer.clone();
env.events().publish(
(symbol_short!("escrow"), Symbol::new(&env, "partial_pmt")),
- (job_id, milestone_index, amount, client, freelancer.clone()),
+ (job_id, milestone_index, amount, client, freelancer),
);
- if all_approved {
- env.events().publish(
- (symbol_short!("escrow"), Symbol::new(&env, "pmt_released")),
- (job_id, freelancer, amount),
+ Ok(())
+ }
+
+ /// Finalize a job when all milestones are approved, deducting the protocol fee
+ /// and distributing remaining escrow to the freelancer.
+ ///
+ /// # Authorization
+ /// Either the client or the freelancer may call this function.
+ ///
+ /// # Errors
+ /// * `JobNotFound` ΓÇö if the job does not exist
+ /// * `Unauthorized` ΓÇö if caller is neither client nor freelancer
+ /// * `InvalidStatus` ΓÇö if job is not `InProgress` or milestones are not all `Approved`
+ /// * `ContractPaused` ΓÇö if the contract is paused
+ pub fn complete_job(
+ env: Env,
+ job_id: u64,
+ caller: Address,
+ ) -> Result<(), EscrowError> {
+ caller.require_auth();
+ require_not_paused(&env)?;
+
+ let mut job: Job = env
+ .storage()
+ .persistent()
+ .get(&get_job_key(job_id))
+ .ok_or(EscrowError::JobNotFound)?;
+ bump_job_ttl(&env, job_id);
+
+ if caller != job.client && caller != job.freelancer {
+ return Err(EscrowError::Unauthorized);
+ }
+
+ if job.status != JobStatus::InProgress {
+ return Err(EscrowError::InvalidStatus);
+ }
+
+ let all_approved = job
+ .milestones
+ .iter()
+ .all(|m| m.status == MilestoneStatus::Approved);
+ if !all_approved {
+ return Err(EscrowError::InvalidStatus);
+ }
+
+ let fee_bps: u32 = env
+ .storage()
+ .instance()
+ .get(&symbol_short!("FEE"))
+ .unwrap_or(0);
+ let fee_recipient: Address = env
+ .storage()
+ .instance()
+ .get(&symbol_short!("TRE"))
+ .unwrap_or(env.current_contract_address());
+
+ let fee_amount = (job.total_amount * fee_bps as i128) / 10_000;
+ let freelancer_amount = job.total_amount - fee_amount;
+
+ let token_client = token::Client::new(&env, &job.token);
+
+// Transfer protocol fee first.
+ if fee_amount > 0 {
+ token_client.transfer(
+ &env.current_contract_address(),
+ &fee_recipient,
+ &fee_amount,
);
}
+ // Transfer remaining funds to the freelancer.
+ token_client.transfer(
+ &env.current_contract_address(),
+ &job.freelancer,
+ &freelancer_amount,
+ );
+
+ // Now finalize the job.
+ job.status = JobStatus::Completed;
+ env.storage().persistent().set(&get_job_key(job_id), &job);
+ bump_job_ttl(&env, job_id);
+
+ env.events().publish(
+ (symbol_short!("escrow"), Symbol::new(&env, "fee_taken")),
+ (job_id, fee_amount, fee_recipient),
+ );
+
+ env.events().publish(
+ (symbol_short!("escrow"), Symbol::new(&env, "pmt_released")),
+ (job_id, job.freelancer, freelancer_amount),
+ );
+
Ok(())
}
@@ -2110,7 +2242,10 @@ impl EscrowContract {
job_id: u64,
milestone_index: u32,
client: Address,
+ min_release_value_stroops: i128,
+ nonce: u64,
) -> Result<(), EscrowError> {
+ consume_nonce(&env, &client, &Symbol::new(&env, "release_ms"), nonce)?;
bump_escrow_ttl(&env, job_id);
client.require_auth();
require_not_paused(&env)?;
@@ -2138,6 +2273,38 @@ impl EscrowContract {
return Err(EscrowError::InvalidStatus);
}
+ if min_release_value_stroops > 0 {
+ let oracle_addr: Address = env
+ .storage()
+ .instance()
+ .get(&DataKey::PriceOracle)
+ .ok_or(EscrowError::OracleUnavailable)?;
+
+ let twap: i128 = env.invoke_contract(
+ &oracle_addr,
+ &Symbol::new(&env, "twap"),
+ soroban_sdk::vec![
+ &env,
+ job.token.clone().into_val(&env),
+ TWAP_SAMPLE_LEDGERS.into_val(&env),
+ ],
+ );
+
+ if twap <= 0 {
+ return Err(EscrowError::OracleUnavailable);
+ }
+
+ let current_value = milestone
+ .amount
+ .checked_mul(twap)
+ .ok_or(EscrowError::ValueOverflow)?
+ / PRICE_SCALE;
+
+ if current_value < min_release_value_stroops {
+ return Err(EscrowError::SlippageExceeded);
+ }
+ }
+
// Compute fee and net freelancer amount.
let token_client = token::Client::new(&env, &job.token);
let fee_bps: u32 = env
@@ -2234,7 +2401,8 @@ impl EscrowContract {
/// `Cancelled`, `Created`, or `InProgress`).
/// * `WorkInProgress` ΓÇö at least one milestone is `InProgress` or `Submitted`;
/// the client must open a dispute instead.
- pub fn cancel_job(env: Env, job_id: u64, client: Address) -> Result<(), EscrowError> {
+ pub fn cancel_job(env: Env, job_id: u64, client: Address, nonce: u64) -> Result<(), EscrowError> {
+ consume_nonce(&env, &client, &Symbol::new(&env, "cancel_job"), nonce)?;
bump_escrow_ttl(&env, job_id);
client.require_auth();
require_not_paused(&env)?;
@@ -2266,15 +2434,16 @@ impl EscrowContract {
}
// Refund the remaining escrowed amount (total minus already-approved milestones).
- let approved_amount: i128 = job
+ // Pay already-approved milestones to the freelancer, since payment only happens in complete_job.
+ let refund: i128 = job
.milestones
.iter()
- .filter(|m| m.status == MilestoneStatus::Approved)
+ .filter(|m| m.status != MilestoneStatus::Approved)
.map(|m| m.amount)
.sum();
- let refund = job.total_amount - approved_amount;
+ let token_client = token::Client::new(&env, &job.token);
+
if refund > 0 {
- let token_client = token::Client::new(&env, &job.token);
token_client.transfer(&env.current_contract_address(), &client, &refund);
}
@@ -2294,7 +2463,8 @@ impl EscrowContract {
/// Claim a refund for an abandoned job past the deadline + grace period.
/// Only the client can call this. Refund excludes amounts for already-approved milestones.
/// Fails if the freelancer has a pending (submitted) milestone awaiting approval.
- pub fn claim_refund(env: Env, job_id: u64, client: Address) -> Result<(), EscrowError> {
+ pub fn claim_refund(env: Env, job_id: u64, client: Address, nonce: u64) -> Result<(), EscrowError> {
+ consume_nonce(&env, &client, &Symbol::new(&env, "claim_ref"), nonce)?;
bump_escrow_ttl(&env, job_id);
client.require_auth();
require_not_paused(&env)?;
@@ -2329,20 +2499,33 @@ impl EscrowContract {
}
// Calculate refund: total minus already-approved milestone amounts
- let approved_amount: i128 = job
+ let refund: i128 = job
.milestones
.iter()
- .filter(|m| m.status == MilestoneStatus::Approved)
+ .filter(|m| m.status != MilestoneStatus::Approved)
.map(|m| m.amount)
.sum();
- let refund = job.total_amount - approved_amount;
+ // If there's nothing to distribute (all approved, nothing to refund), still
+ // pay the approved amount to the freelancer before returning.
+ let token_client = token::Client::new(&env, &job.token);
+
+
+
if refund <= 0 {
return Err(EscrowError::NoRefundDue);
+ // approved_amount paid above ΓÇö no refund due to client, just update status
+ job.status = JobStatus::Cancelled;
+ env.storage().persistent().set(&get_job_key(job_id), &job);
+ bump_job_ttl(&env, job_id);
+ env.events().publish(
+ (symbol_short!("escrow"), symbol_short!("refund")),
+ (job_id, 0_i128, client, job.freelancer),
+ );
+ return Ok(());
}
// Transfer refund to client
- let token_client = token::Client::new(&env, &job.token);
token_client.transfer(&env.current_contract_address(), &client, &refund);
job.status = JobStatus::Cancelled;
@@ -2378,7 +2561,9 @@ impl EscrowContract {
caller: Address,
job_id: u64,
amount: i128,
+ nonce: u64,
) -> Result<(), EscrowError> {
+ consume_nonce(&env, &caller, &Symbol::new(&env, "partial_ref"), nonce)?;
bump_escrow_ttl(&env, job_id);
caller.require_auth();
require_not_paused(&env)?;
@@ -2403,13 +2588,12 @@ impl EscrowContract {
}
// Calculate remaining locked balance (total minus already-approved milestones).
- let approved_amount: i128 = job
+ let remaining: i128 = job
.milestones
.iter()
- .filter(|m| m.status == MilestoneStatus::Approved)
+ .filter(|m| m.status != MilestoneStatus::Approved)
.map(|m| m.amount)
.sum();
- let remaining = job.total_amount - approved_amount;
if amount <= 0 || amount > remaining {
return Err(EscrowError::InsufficientFunds);
@@ -3009,13 +3193,18 @@ impl EscrowContract {
require_state_expirable(&job)?;
// Refund remaining escrowed balance (total minus already-approved milestones).
- let approved_amount: i128 = job
+ // Also pay the approved milestone amounts to the freelancer, since payment
+ // only happens during complete_job.
+ let refund: i128 = job
.milestones
.iter()
- .filter(|m| m.status == MilestoneStatus::Approved)
+ .filter(|m| m.status != MilestoneStatus::Approved)
.map(|m| m.amount)
.sum();
- let refund = job.total_amount - approved_amount;
+
+ let token_client = token::Client::new(&env, &job.token);
+
+
// Only transfer if funds are actually held in escrow (job was funded).
if refund > 0
@@ -3023,7 +3212,6 @@ impl EscrowContract {
|| job.status == JobStatus::InProgress
|| job.status == JobStatus::Disputed)
{
- let token_client = token::Client::new(&env, &job.token);
token_client.transfer(&env.current_contract_address(), &job.client, &refund);
}