-
Notifications
You must be signed in to change notification settings - Fork 311
Expand file tree
/
Copy pathlib.rs
More file actions
3201 lines (2847 loc) · 134 KB
/
Copy pathlib.rs
File metadata and controls
3201 lines (2847 loc) · 134 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
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! TalentTrust escrow contract for milestone-based freelancer payments.
//!
//! The crate root exposes the Soroban contract and still owns several public
//! entrypoints directly: initialization, settlement-token binding, deposits,
//! milestone release/refund/cancel flows, reputation, work evidence, protocol
//! fee withdrawal, and dispute entrypoints. Supporting modules keep reusable
//! validation, storage, governance, and lifecycle helpers close to the paths
//! that use them.
//!
//! ## Escrow source tree map
//!
//! | Source | Responsibility | Storage keys owned or touched |
//! | --- | --- | --- |
//! | `lib.rs` | Contract wrapper plus root entrypoints for setup, custody, money movement, reads, reputation, work evidence, pause/emergency, fee withdrawal, and ABI-compatible dispute wrappers. | `DataKey::Initialized`, `Admin`, `SettlementToken`, `Paused`, `Emergency`, `ReadinessChecklist`, `Contract(id)`, `(Contract(id), "milestones")`, `MilestoneApprovals`, `AccumulatedProtocolFees`, `ReputationIssued`, `PendingReputationCredits`, `Reputation`, `ReputationComment`, `ReputationConfigKey` |
//! | `amount_validation` | Stateless validation and checked arithmetic for stroop amounts and milestone totals. | None directly; callers write validated amounts to `Contract(id)` and milestone vectors. |
//! | `approvals` | Temporary milestone release approvals and release-authorization checks. | Temporary `DataKey::MilestoneApprovals(contract_id, milestone_index)`; reads `Contract(id)` and `(Contract(id), "milestones")`. |
//! | `deposit` | Deposit preflight and post-transfer accounting used by `deposit_funds`. | `DataKey::Contract(contract_id)` and `(DataKey::Contract(contract_id), "milestones")`. |
//! | `finalize` | Immutable finalization records, finalization guards, and final contract summaries. | `DataKey::Finalization(contract_id)`; reads `Contract(id)`, `(Contract(id), "milestones")`, `Paused`, and `Emergency`. |
//! | `migration` | Client migration proposals, acceptance checks, cancellation, and pending-migration reads. | Temporary `DataKey::PendingClientMigration(contract_id)`; reads and updates `DataKey::Contract(contract_id)`. |
//! | `rollback` | Guarded rollback of unchanged, unresolved disputes. | `DataKey::DisputeRollback(contract_id)`; reads and updates `DataKey::Contract(contract_id)` and its milestones. |
//! | `ttl` | TTL constants plus helpers for temporary and persistent storage renewal. | Extends caller-provided keys, especially `Contract(id)`, `(Contract(id), "milestones")`, `NextContractId`, participant indexes, approvals, and migrations. |
//! | `types` | Shared Soroban types, error enums, summaries, governance records, dispute records, and the canonical `DataKey` enum. | Declares storage key schema only; does not access storage itself. |
//! | `utils` | Small deterministic helpers shared by entrypoints, currently ledger timestamp access. | None. |
//! | `create_contract` | Contract creation, participant/milestone validation, ID allocation, and creation events. | `DataKey::Contract(id)`, `(DataKey::Contract(id), "milestones")`, `NextContractId`, and `GovernedParameters`. |
//! | `dispute` | Dispute payout arithmetic, lifecycle orchestration, final-status selection, and arbiter dispute-split config storage. | `DataKey::DisputeConfigKey`, `DataKey::Contract(id)`, and dispute rollback records. |
//! | `governance` | Admin-controlled protocol fee, governed parameter, readiness, and admin-rotation entrypoints. | `DataKey::Admin`, `ProtocolFeeBps`, `PendingAdmin`, `GovernedParameters`, and `ReadinessChecklist`. |
//!
//! Generate this map with `cargo doc -p escrow --no-deps` and open
//! `target/doc/escrow/index.html`.
#![no_std]
#![allow(dead_code)]
#![allow(clippy::derivable_impls)]
#![allow(clippy::manual_range_contains)]
#![allow(clippy::assertions_on_constants)]
#![allow(clippy::too_many_arguments)]
#![allow(clippy::type_complexity)]
#![allow(clippy::needless_range_loop)]
#![allow(clippy::collapsible_if)]
#![allow(clippy::collapsible_else_if)]
#![allow(clippy::redundant_field_names)]
#![allow(clippy::ptr_arg)]
#![allow(clippy::useless_vec)]
#![allow(clippy::let_and_return)]
#![allow(clippy::inconsistent_digit_grouping)]
#![allow(clippy::int_plus_one)]
#![allow(clippy::duplicated_attributes)]
#![allow(clippy::unreadable_literal)]
#![allow(clippy::redundant_clone)]
#![allow(clippy::bool_assert_comparison)]
#![allow(clippy::needless_borrow)]
#![allow(clippy::clone_on_copy)]
#![allow(clippy::module_inception)]
#![allow(clippy::single_match)]
#![allow(clippy::useless_conversion)]
#![allow(clippy::doc_markdown)]
#![allow(clippy::doc_lazy_continuation)]
#![allow(clippy::len_zero)]
#![allow(clippy::unnecessary_cast)]
#![allow(clippy::unnecessary_fold)]
#![allow(clippy::empty_line_after_outer_attr)]
#![allow(clippy::redundant_pattern_matching)]
#![allow(unused_imports)]
#![allow(unused_variables)]
#![allow(unused_doc_comments)]
#![allow(deprecated)]
#![allow(mismatched_lifetime_syntaxes)]
mod amount_validation;
mod approvals;
mod authorization;
mod constants;
mod contracts;
mod create_contract;
mod deposit;
mod dispute;
mod events;
mod finalize;
mod governance;
mod governance_proposal;
mod keys;
mod migration;
mod milestone_transitions;
mod milestones;
pub mod milestones_consts;
mod refund_impl;
mod release;
mod reputation;
mod rollback;
mod schema_migration;
mod settlement;
mod simulate;
mod storage;
mod storage_validation;
pub mod token_scale;
mod ttl;
mod types;
mod utils;
use crate::utils::now_seconds;
use soroban_sdk::{
contract, contracterror, contractimpl, symbol_short, token, Address, BytesN, Env, String,
Symbol, Vec,
};
pub use amount_validation::accumulate_amounts;
pub use amount_validation::safe_add_amounts;
pub use amount_validation::safe_subtract_amounts;
pub use amount_validation::validate_deposit_amount;
pub use amount_validation::validate_milestone_amounts;
pub use amount_validation::validate_single_amount;
pub use amount_validation::MAX_SINGLE_AMOUNT_STROOPS;
pub use constants::PAGE_CEILING;
pub use contracts::{
MainnetReadinessInfo, DEFAULT_MAX_ARBITERS, DEFAULT_MAX_MILESTONES,
DEFAULT_MAX_TOTAL_ESCROW_STROOPS, MAINNET_MAX_TOTAL_ESCROW_PER_CONTRACT_STROOPS,
MAINNET_PROTOCOL_VERSION, MAX_MAX_ARBITERS, MAX_MAX_BATCH_SETTLEMENT, MAX_MAX_MILESTONES,
MIN_MAX_ARBITERS, MIN_MAX_BATCH_SETTLEMENT, MIN_MAX_ESCROW_STROOPS, MIN_MAX_MILESTONES,
};
pub use dispute::final_status_after_resolution;
pub use dispute::resolution_payouts;
pub use dispute::DisputeInfo;
pub use events::{EventInput, MAX_EVENT_BATCH_SIZE};
pub use migration::PendingClientMigration;
pub use milestones_consts::PROTOCOL_FEE_BPS_DENOMINATOR;
pub use token_scale::{normalized_amount, scale_multiplier, MAX_TOKEN_DECIMALS};
pub use ttl::{
ADMIN_ROTATION_MIN_DELAY_LEDGERS, ADMIN_ROTATION_PROPOSAL_TTL_LEDGERS,
PENDING_MIGRATION_TTL_LEDGERS,
};
pub use types::{
AuthorizationRecord, Contract, ContractBounds, ContractStatus, ContractSummary, DataKey,
DepositMode, DisputeConfig, DisputeMetadata, DisputeResolution, DisputeSplit,
GovernanceProposal, GovernanceProposalKind, GovernanceProposalState, GovernedParameters,
Milestone, MilestoneApprovals, MilestoneProgress, MilestoneSummary, PauseScope, PauseTarget,
PendingAdminProposal, ReadinessChecklist, ReleaseAuthorization, Reputation, ReputationConfig,
SplitAmounts, CONTRACT_SUMMARY_SCHEMA_VERSION, DISPUTE_STORAGE_VERSION,
};
// Maximum bounds constants - re-export from amount_validation for API visibility
pub const MAX_MILESTONES: u32 = 10;
pub const MAX_BATCH_MILESTONES: u32 = 10;
pub const MAX_FEE_BPS: u32 = 10_000;
pub const MAX_TOTAL_ESCROW_STROOPS: i128 = MAX_SINGLE_AMOUNT_STROOPS;
// Default maximum number of contracts finalizable in a single batch settlement call.
pub const DEFAULT_MAX_BATCH_SETTLEMENT: u32 = 10;
// Backward-compatible alias for the default max batch settlement.
pub const MAX_BATCH_SETTLEMENT: u32 = DEFAULT_MAX_BATCH_SETTLEMENT;
#[contract]
pub struct Escrow;
pub use types::Error;
pub use types::Error as EscrowError;
impl Escrow {
// Get the settlement token address from the canonical `DataKey` binding.
pub(crate) fn read_settlement_token(env: &Env) -> Option<Address> {
env.storage().persistent().get(&DataKey::SettlementToken)
}
// Persist the settlement token address under the canonical `DataKey` binding.
pub(crate) fn write_settlement_token(env: &Env, token: &Address) {
env.storage()
.persistent()
.set(&DataKey::SettlementToken, token);
}
// Returns the effective max batch settlement, falling back to the default.
pub(crate) fn effective_max_settlement(env: &Env) -> u32 {
env.storage()
.persistent()
.get(&DataKey::MaxSettlement)
.unwrap_or(DEFAULT_MAX_BATCH_SETTLEMENT)
}
}
#[contractimpl]
impl Escrow {
// Bind the single Stellar Asset Contract (SAC) token this escrow instance will custody.
//
// This is a **write-once** step: once a token is recorded under
// [`DataKey::SettlementToken`] all subsequent money-flow entrypoints
// (`deposit_funds`, `release_milestone`, `refund_unreleased_milestones`,
// `cancel_contract`, `withdraw_protocol_fees`) read that address to execute SAC
// `transfer` calls. A second call with any token address is rejected with
// `SettlementTokenAlreadyBound`.
//
// # Pre-bind probe (issue #723)
//
// Before persisting the token address, this entrypoint performs a **read-only
// probe** to verify the supplied address is a live SAC token contract:
//
// 1. Calls `token::Client::balance(env.current_contract_address())` against
// the candidate address. If the address does not implement the SAC token
// interface, the call panics and the bind is rejected with
// `InvalidSettlementToken`.
// 2. Rejects `env.current_contract_address()` (the escrow contract itself)
// with `SettlementTokenIsSelf` — binding self creates a circular custody
// reference.
// 3. Rejects the stored admin address with `SettlementTokenIsAdmin` —
// conflating governance authority with the settlement token role is a
// privilege-separation violation.
//
// # Reentrancy mitigation
//
// All downstream money-flow entrypoints (`deposit_funds`, `release_milestone`,
// `cancel_contract`, `refund_unreleased_milestones`) follow strict
// **state-before-transfer** (Checks-Effects-Interactions) ordering: contract
// state is finalized *before* any `token::Client::transfer` call. A
// malicious token contract that re-enters the escrow during a transfer will
// observe the already-mutated state and cannot double-spend or front-run
// the operation. The probe itself performs no state mutation — it only
// reads the token balance — so it cannot be used as a reentrancy vector.
//
// See [`docs/escrow/sac-custody.md`](../../../docs/escrow/sac-custody.md) for the
// full custody model, accounting invariant, and lifecycle sequence diagram.
//
// # Arguments
// * `env` - The Soroban environment
// * `admin` - The admin address (must match stored admin)
// * `token` - The SAC token address
//
// # Errors
// * `NotInitialized` if `initialize` has not been called
// * `UnauthorizedRole` if `admin` is not the stored admin
// * `SettlementTokenAlreadyBound` if a token is already bound
// * `InvalidSettlementToken` if the probe call to `token::Client::balance` panics
// * `SettlementTokenIsSelf` if `token == env.current_contract_address()`
// * `SettlementTokenIsAdmin` if `token == stored_admin`
//
// # Events
// On a successful, authorized bind this publishes a `settlement_token_bound`
// event so off-chain indexers and monitoring dashboards can observe which
// asset an escrow settles in, and when the binding happened.
//
// * Topics: `(Symbol "settlement_token_bound",)`
// * Data: `(admin: Address, token: Address, timestamp: u64)`
//
// The event only fires after the write succeeds. Rejected binds
// (uninitialized, unauthorized, invalid token, self, admin) panic before
// this point and therefore publish nothing. All payload fields are public
// configuration.
pub fn bind_settlement_token(env: Env, admin: Address, token: Address) -> bool {
Self::require_initialized(&env);
let stored_admin: Address = env
.storage()
.persistent()
.get(&DataKey::Admin)
.unwrap_or_else(|| env.panic_with_error(EscrowError::NotInitialized));
if admin != stored_admin {
env.panic_with_error(EscrowError::UnauthorizedRole);
}
admin.require_auth();
// Reject double-bind: once a settlement token is recorded, any
// subsequent bind attempt is rejected. This is a write-once field.
if Self::read_settlement_token(&env).is_some() {
env.panic_with_error(EscrowError::SettlementTokenAlreadyBound);
}
// ── Pre-bind probe (issue #723) ─────────────────────────────────────
//
// Reject the escrow contract's own address — binding self would create
// a circular custody reference and brick every transfer path.
if token == env.current_contract_address() {
env.panic_with_error(EscrowError::SettlementTokenAlreadyBound);
}
// Reject the admin address — conflating governance authority with the
// settlement token role is a privilege-separation violation.
if token == stored_admin {
env.panic_with_error(EscrowError::SettlementTokenAlreadyBound);
}
// Read-only probe: call `token::Client::balance` against the escrow
// contract address. If `token` does not implement the SAC token
// interface, the host panics and we translate that into
// `InvalidSettlementToken`.
//
// This is safe because:
// - `balance` is a read-only entrypoint (no state mutation on the
// token contract).
// - We have not yet written anything to storage — a panic here leaves
// no partial state.
// - The probe cannot be used for reentrancy: it calls `balance`, not
// `transfer`, and the escrow has no callback the token could invoke.
let token_client = token::Client::new(&env, &token);
let _probe: i128 = token_client.balance(&env.current_contract_address());
Self::write_settlement_token(&env, &token);
// Capture and persist the token's decimal count for scale validation.
// This is a read-only probe (decimals() is a pure getter) — no funds
// are moved and no re-entrancy risk exists. Stored under
// DataKey::TokenScale for use by create_contract and the read views.
token_scale::capture_and_store_token_scale(&env, &token);
// Emit after the binding write succeeds so indexers can track the bound
// asset. Consistent topic naming with `init` / `protocol_fee_bps` events.
env.events().publish(
(Symbol::new(&env, "settlement_token_bound"),),
(admin, token, env.ledger().timestamp()),
);
true
}
// ── Contract Creation & Funding ──────────────────────────────────────────
/// Creates a new escrow contract with the specified participants and milestone amounts.
/// Pull the settlement-token deposit from the client into the escrow contract.
pub fn deposit_funds(env: Env, contract_id: u32, caller: Address, amount: i128) -> bool {
Self::require_initialized(&env);
Self::require_not_paused(&env);
let validated = deposit::validate_deposit(&env, contract_id, &caller, amount);
let token = Self::read_settlement_token(&env)
.unwrap_or_else(|| env.panic_with_error(Error::SettlementTokenNotConfigured));
// State update and event emission first
let result = deposit::apply_validated_deposit(&env, contract_id, caller.clone(), validated);
// Token transfer interaction last
let token_client = token::Client::new(&env, &token);
token_client.transfer(&caller, &env.current_contract_address(), &amount);
result
}
// ── Client Migrations ────────────────────────────────────────────────────
pub fn propose_client_migration(
env: Env,
contract_id: u32,
current_client: Address,
new_client: Address,
) -> bool {
Self::require_not_paused(&env);
Self::propose_client_migration_impl(&env, contract_id, current_client, new_client)
}
pub fn accept_client_migration(env: Env, contract_id: u32, new_client: Address) -> bool {
Self::require_not_paused(&env);
Self::accept_client_migration_impl(&env, contract_id, new_client)
}
pub fn has_pending_client_migration(env: Env, contract_id: u32) -> bool {
Self::has_pending_client_migration_impl(&env, contract_id)
}
pub fn get_pending_client_migration(env: Env, contract_id: u32) -> PendingClientMigration {
Self::get_pending_client_migration_impl(&env, contract_id)
}
// ── Milestone Releases & Refunds ──────────────────────────────────────────
pub fn approve_milestone_release(
env: Env,
contract_id: u32,
caller: Address,
milestone_index: u32,
) -> bool {
Self::require_not_paused(&env);
Self::require_not_finalized(&env, contract_id);
approvals::approve_milestone(&env, contract_id, milestone_index, &caller)
.unwrap_or_else(|e| env.panic_with_error(e));
// 🔔 NEW EVENT: Emit approval event after successful storage write.
env.events().publish(
(symbol_short!("mlstn_app"), contract_id),
(milestone_index, caller.clone(), env.ledger().timestamp()),
);
true
}
pub fn release_milestone(
env: Env,
contract_id: u32,
caller: Address,
milestone_index: u32,
) -> bool {
Self::require_not_paused(&env);
caller.require_auth();
let mut contract: Contract = env
.storage()
.persistent()
.get(&DataKey::Contract(contract_id))
.unwrap_or_else(|| env.panic_with_error(EscrowError::ContractNotFound));
ttl::extend_contract_ttl(&env, contract_id);
Self::require_not_finalized(&env, contract_id);
// Disputed contracts are release-locked until the arbiter resolves the
// dispute via the permitted path. This preserves the invariant that no
// milestone funds may leave escrow while a dispute remains active.
if contract.status == ContractStatus::Disputed || contract.status != ContractStatus::Funded
{
env.panic_with_error(Error::InvalidState);
}
let is_client = caller == contract.client;
let is_freelancer = caller == contract.freelancer;
let is_arbiter = contract.arbiter.as_ref() == Some(&caller);
match contract.release_authorization {
ReleaseAuthorization::ClientOnly => {
if !is_client {
env.panic_with_error(EscrowError::UnauthorizedRole);
}
}
ReleaseAuthorization::ArbiterOnly => {
if !is_arbiter {
env.panic_with_error(EscrowError::UnauthorizedRole);
}
}
ReleaseAuthorization::ClientAndArbiter => {
if !is_client && !is_arbiter {
env.panic_with_error(EscrowError::UnauthorizedRole);
}
}
ReleaseAuthorization::MultiSig => {
if !is_client && !is_freelancer {
env.panic_with_error(EscrowError::UnauthorizedRole);
}
}
}
let mut milestones: Vec<Milestone> = ttl::load_milestones(&env, contract_id);
ttl::extend_milestone_ttl(&env, contract_id);
if milestone_index >= milestones.len() {
env.panic_with_error(Error::IndexOutOfBounds);
}
let mut milestone = milestones.get(milestone_index).unwrap();
if milestone.released {
env.panic_with_error(Error::MilestoneAlreadyReleased);
}
if milestone.refunded {
env.panic_with_error(EscrowError::AlreadyRefunded);
}
approvals::check_approvals(&env, &contract, contract_id, milestone_index)
.unwrap_or_else(|e| env.panic_with_error(e));
let gross_amount = milestone.amount;
let protocol_fee: i128 = if Self::is_initialized(&env) {
let fee_bps = Self::read_protocol_fee_bps(&env);
if fee_bps > 0 {
Self::calculate_protocol_fee(&env, gross_amount, fee_bps)
} else {
0
}
} else {
0
};
let net_amount = gross_amount - protocol_fee;
let accumulated_fees: i128 = env
.storage()
.persistent()
.get(&DataKey::AccumulatedProtocolFees)
.unwrap_or(0);
let available_balance = contract
.funded_amount
.checked_sub(contract.released_amount)
.and_then(|remaining| remaining.checked_sub(contract.refunded_amount))
.and_then(|remaining| remaining.checked_sub(accumulated_fees))
.unwrap_or_else(|| env.panic_with_error(EscrowError::PotentialOverflow));
if available_balance < gross_amount {
env.panic_with_error(EscrowError::InsufficientFunds);
}
let token = Self::read_settlement_token(&env)
.unwrap_or_else(|| env.panic_with_error(Error::SettlementTokenNotConfigured));
if protocol_fee > 0 {
let new_accumulated = accumulated_fees
.checked_add(protocol_fee)
.unwrap_or_else(|| env.panic_with_error(EscrowError::PotentialOverflow));
env.storage()
.persistent()
.set(&DataKey::AccumulatedProtocolFees, &new_accumulated);
}
milestone.released = true;
milestone.funded_amount = gross_amount;
milestones.set(milestone_index, milestone.clone());
contract.released_amount = contract
.released_amount
.checked_add(net_amount)
.unwrap_or_else(|| env.panic_with_error(EscrowError::PotentialOverflow));
let new_accumulated = accumulated_fees + protocol_fee;
let invariant_sum = contract.released_amount + contract.refunded_amount + new_accumulated;
if invariant_sum > contract.funded_amount {
env.panic_with_error(EscrowError::AccountingInvariantViolated);
}
approvals::clear_approvals(&env, contract_id, milestone_index);
let all_released = milestones.iter().all(|m| m.released || m.refunded);
if all_released {
contract.status = ContractStatus::Completed;
Self::grant_pending_reputation_credit(&env, &contract.freelancer);
}
ttl::store_milestones(&env, contract_id, &milestones);
env.storage()
.persistent()
.set(&DataKey::Contract(contract_id), &contract);
ttl::extend_contract_ttl(&env, contract_id);
env.events().publish(
(symbol_short!("mlstn_rls"), contract_id),
(
milestone_index,
gross_amount,
protocol_fee,
contract.released_amount,
caller.clone(),
env.ledger().timestamp(),
),
);
if all_released {
env.events().publish(
(symbol_short!("ctrct_cmp"), contract_id),
(caller, env.ledger().timestamp()),
);
}
let token_client = token::Client::new(&env, &token);
token_client.transfer(
&env.current_contract_address(),
&contract.freelancer,
&net_amount,
);
true
}
/// Releases multiple milestones atomically in a single bounded batch invocation.
///
/// # Safety & Invariants
/// - Bounded: `milestone_indices` length must be between 1 and `MAX_BATCH_MILESTONES` (10).
/// - All-or-nothing: All items are strictly validated before any state mutation or token transfer.
/// If any index is out of bounds, already released, refunded, unapproved, duplicated, or if
/// the combined gross amount exceeds available balance, the entire batch reverts.
/// - Emits a `mlstn_rls` event for every successfully released milestone.
/// - If the contract transitions to all-milestones-settled, marks `ContractStatus::Completed` and emits `ctrct_cmp`.
pub fn release_milestone_batch(
env: Env,
contract_id: u32,
caller: Address,
milestone_indices: Vec<u32>,
) -> bool {
Self::require_not_paused(&env);
caller.require_auth();
if milestone_indices.is_empty() {
env.panic_with_error(Error::EmptyBatch);
}
if milestone_indices.len() > crate::milestones_consts::MAX_BATCH_MILESTONES {
env.panic_with_error(Error::BatchLimitExceeded);
}
let mut contract: Contract = env
.storage()
.persistent()
.get(&DataKey::Contract(contract_id))
.unwrap_or_else(|| env.panic_with_error(EscrowError::ContractNotFound));
ttl::extend_contract_ttl(&env, contract_id);
Self::require_not_finalized(&env, contract_id);
if contract.status != ContractStatus::Funded {
env.panic_with_error(Error::InvalidState);
}
let is_client = caller == contract.client;
let is_freelancer = caller == contract.freelancer;
let is_arbiter = contract.arbiter.as_ref() == Some(&caller);
match contract.release_authorization {
ReleaseAuthorization::ClientOnly => {
if !is_client {
env.panic_with_error(EscrowError::UnauthorizedRole);
}
}
ReleaseAuthorization::ArbiterOnly => {
if !is_arbiter {
env.panic_with_error(EscrowError::UnauthorizedRole);
}
}
ReleaseAuthorization::ClientAndArbiter => {
if !is_client && !is_arbiter {
env.panic_with_error(EscrowError::UnauthorizedRole);
}
}
ReleaseAuthorization::MultiSig => {
if !is_client && !is_freelancer {
env.panic_with_error(EscrowError::UnauthorizedRole);
}
}
}
let mut milestones: Vec<Milestone> = ttl::load_milestones(&env, contract_id);
ttl::extend_milestone_ttl(&env, contract_id);
let batch_len = milestone_indices.len();
for i in 0..batch_len {
let idx_i = milestone_indices.get(i).unwrap();
for j in (i + 1)..batch_len {
let idx_j = milestone_indices.get(j).unwrap();
if idx_i == idx_j {
env.panic_with_error(Error::DuplicateMilestoneInBatch);
}
}
}
// Pass 1: Strict Validation (All-or-Nothing)
let mut total_gross_amount: i128 = 0;
for i in 0..batch_len {
let milestone_index = milestone_indices.get(i).unwrap();
if milestone_index >= milestones.len() {
env.panic_with_error(Error::IndexOutOfBounds);
}
let milestone = milestones.get(milestone_index).unwrap();
if milestone.released {
env.panic_with_error(Error::MilestoneAlreadyReleased);
}
if milestone.refunded {
env.panic_with_error(EscrowError::AlreadyRefunded);
}
approvals::check_approvals(&env, &contract, contract_id, milestone_index)
.unwrap_or_else(|e| env.panic_with_error(e));
total_gross_amount = total_gross_amount
.checked_add(milestone.amount)
.unwrap_or_else(|| env.panic_with_error(EscrowError::PotentialOverflow));
}
let mut accumulated_fees: i128 = env
.storage()
.persistent()
.get(&DataKey::AccumulatedProtocolFees)
.unwrap_or(0);
let available_balance = contract.funded_amount
- contract.released_amount
- contract.refunded_amount
- accumulated_fees;
if available_balance < total_gross_amount {
env.panic_with_error(EscrowError::InsufficientFunds);
}
let fee_bps = if Self::is_initialized(&env) {
Self::read_protocol_fee_bps(&env)
} else {
0
};
// Pass 2: Atomic Execution
for i in 0..batch_len {
let milestone_index = milestone_indices.get(i).unwrap();
let mut milestone = milestones.get(milestone_index).unwrap();
let gross_amount = milestone.amount;
let protocol_fee: i128 = if fee_bps > 0 {
Self::calculate_protocol_fee(&env, gross_amount, fee_bps)
} else {
0
};
let net_amount = gross_amount - protocol_fee;
if let Some(token) = Self::read_settlement_token(&env) {
let token_client = token::Client::new(&env, &token);
token_client.transfer(
&env.current_contract_address(),
&contract.freelancer,
&net_amount,
);
}
if protocol_fee > 0 {
accumulated_fees = accumulated_fees
.checked_add(protocol_fee)
.unwrap_or_else(|| env.panic_with_error(EscrowError::PotentialOverflow));
env.storage()
.persistent()
.set(&DataKey::AccumulatedProtocolFees, &accumulated_fees);
}
milestone.released = true;
milestone.funded_amount = gross_amount;
milestones.set(milestone_index, milestone.clone());
contract.released_amount = contract
.released_amount
.checked_add(net_amount)
.unwrap_or_else(|| env.panic_with_error(EscrowError::PotentialOverflow));
let invariant_sum =
contract.released_amount + contract.refunded_amount + accumulated_fees;
if invariant_sum > contract.funded_amount {
env.panic_with_error(EscrowError::AccountingInvariantViolated);
}
approvals::clear_approvals(&env, contract_id, milestone_index);
env.events().publish(
(symbol_short!("mlstn_rls"), contract_id),
(
milestone_index,
gross_amount,
protocol_fee,
contract.released_amount,
caller.clone(),
env.ledger().timestamp(),
),
);
}
let all_released = milestones.iter().all(|m| m.released || m.refunded);
if all_released {
contract.status = ContractStatus::Completed;
Self::grant_pending_reputation_credit(&env, &contract.freelancer);
}
ttl::store_milestones(&env, contract_id, &milestones);
env.storage()
.persistent()
.set(&DataKey::Contract(contract_id), &contract);
ttl::extend_contract_ttl(&env, contract_id);
if all_released {
env.events().publish(
(symbol_short!("ctrct_cmp"), contract_id),
(caller, env.ledger().timestamp()),
);
}
true
}
/// Deprecated thin delegate for [`bind_settlement_token`](Self::bind_settlement_token).
///
/// Retained for backward compatibility with external callers that used the historical API name.
/// Delegates directly to [`bind_settlement_token`](Self::bind_settlement_token) and inherits
/// every security guard (`SettlementTokenAlreadyBound`, admin auth check, SAC interface probe,
/// self/admin validation) and event emission.
///
/// # Arguments
/// * `env` - The Soroban environment
/// * `admin` - The admin address (must match stored admin)
/// * `token` - The SAC token address
///
/// # Deprecated
/// Use [`bind_settlement_token`](Self::bind_settlement_token) instead.
#[deprecated(note = "Use bind_settlement_token instead.")]
pub fn set_settlement_token(env: Env, admin: Address, token: Address) -> bool {
Self::bind_settlement_token(env, admin, token)
}
// Returns the bound settlement token, or `None` if no token has been bound.
pub fn get_settlement_token(env: Env) -> Option<Address> {
Self::read_settlement_token(&env)
}
// Returns `true` exactly when a settlement token is bound.
//
// This is the recommended cheap pre-flight readiness check before calling
// `deposit_funds`, which panics when no settlement token has been bound.
// Integrators that only need to know *whether* the escrow can accept
// deposits — without caring about the specific token address — should use
// this instead of fetching and discarding the `Address` from
// `get_settlement_token`.
//
// Read-only and auth-free: it performs no state mutation (no TTL write is
// needed for the simple binding key).
//
// # Returns
// * `true` if a settlement token is bound
// * `false` if no settlement token has been bound yet
pub fn is_settlement_token_bound(env: Env) -> bool {
Self::read_settlement_token(&env).is_some()
}
// ── Initialization ───────────────────────────────────────────────────────
// Initializes the escrow contract with the operational admin.
//
// Single-use. Stores the admin address that controls pause, emergency,
// protocol-fee, and governance operations. All escrow lifecycle operations
// (create, deposit, release, refund, cancel) call `require_initialized`
// so that these safety rails are always bound before money can move.
pub fn initialize(env: Env, admin: Address) -> bool {
if env
.storage()
.persistent()
.get::<_, bool>(&DataKey::Initialized)
.unwrap_or(false)
{
env.panic_with_error(Error::AlreadyInitialized);
}
admin.require_auth();
env.storage().persistent().set(&DataKey::Initialized, &true);
env.storage().persistent().set(&DataKey::Admin, &admin);
env.storage()
.persistent()
.set(&DataKey::NextContractId, &1u32);
let mut checklist: ReadinessChecklist = env
.storage()
.persistent()
.get(&DataKey::ReadinessChecklist)
.unwrap_or_default();
checklist.initialized = true;
env.storage()
.persistent()
.set(&DataKey::ReadinessChecklist, &checklist);
env.events().publish(
(symbol_short!("init"), Symbol::new(&env, "admin_set")),
(admin.clone(), env.ledger().timestamp()),
);
true
}
// Returns the stored governance admin address.
pub fn get_admin(env: Env) -> Option<Address> {
env.storage().persistent().get(&DataKey::Admin)
}
// Returns the current arbiter dispute-split configuration.
//
// If no configuration has been stored yet, returns the protocol default:
// `partial_refund_freelancer_bps = 3000`, `partial_refund_client_bps = 7000`.
pub fn get_arbiter_config(env: Env) -> DisputeConfig {
dispute::get_dispute_config(&env).unwrap_or_default()
}
// Set the arbiter refund split configuration in basis points.
pub fn set_arbiter_config(env: Env, freelancer_bps: u32, client_bps: u32) -> bool {
Self::require_initialized(&env);
let admin: Address = env
.storage()
.persistent()
.get(&DataKey::Admin)
.unwrap_or_else(|| env.panic_with_error(EscrowError::NotInitialized));
admin.require_auth();
if freelancer_bps > crate::milestones_consts::MAX_FEE_BPS
|| client_bps > crate::milestones_consts::MAX_FEE_BPS
|| freelancer_bps + client_bps != crate::milestones_consts::PROTOCOL_FEE_BPS_DENOMINATOR
{
env.panic_with_error(Error::InvalidProtocolParameters);
}
let old_config = dispute::get_dispute_config(&env).unwrap_or_default();
let new_config = DisputeConfig {
partial_refund_freelancer_bps: freelancer_bps,
partial_refund_client_bps: client_bps,
};
dispute::set_dispute_config(&env, new_config.clone());
env.events().publish(
(Symbol::new(&env, "arbiter_cfg"),),
(old_config, new_config, admin, env.ledger().timestamp()),
);
true
}
// Admin-configurable maximum number of contracts finalizable in a single
// `finalize_contracts_batch` call.
//
// Default is [`DEFAULT_MAX_BATCH_SETTLEMENT`] (10). Valid range is
// [`MIN_MAX_BATCH_SETTLEMENT`]..=[`MAX_MAX_BATCH_SETTLEMENT`] (1..=100).
//
// # Errors
// * [`EscrowError::NotInitialized`] if `initialize` has not been called.
// * [`EscrowError::UnauthorizedRole`] if `admin` is not the stored admin.
// * [`EscrowError::LimitOutOfRange`] if `max_settlement` is outside bounds.
//
// # Events
// `("limits", "max_settlement")` → `(max_settlement: u32, timestamp: u64)`
pub fn set_max_settlement(env: Env, max_settlement: u32) -> bool {
Self::require_initialized(&env);
let admin: Address = env
.storage()
.persistent()
.get(&DataKey::Admin)
.unwrap_or_else(|| env.panic_with_error(EscrowError::NotInitialized));
admin.require_auth();
if max_settlement < MIN_MAX_BATCH_SETTLEMENT || max_settlement > MAX_MAX_BATCH_SETTLEMENT {
env.panic_with_error(EscrowError::LimitOutOfRange);
}
env.storage()
.persistent()
.set(&DataKey::MaxSettlement, &max_settlement);
env.events().publish(
(symbol_short!("limits"), Symbol::new(&env, "max_settlement")),
(max_settlement, env.ledger().timestamp()),
);
true
}
// Returns the effective maximum number of contracts finalizable in a
// single batch settlement call.
//
// Returns [`DEFAULT_MAX_BATCH_SETTLEMENT`] when no admin override has been
// set.
pub fn get_max_settlement(env: Env) -> u32 {
Self::effective_max_settlement(&env)
}
// Returns protocol-wide hard-coded limits as a [`ContractBounds`] struct.
//
// This is a read-only accessor — it does **not** require authorization
// and succeeds even before `initialize` has been called.
//
// # Fields
// - `max_milestones`: maximum number of milestones per contract.
// - `max_single_milestone_stroops`: maximum amount per individual milestone.
// - `max_total_escrow_stroops`: maximum sum of all milestone amounts.
// - `max_fee_bps`: protocol fee ceiling in basis points (10 000 = 100 %).
// - `max_settlement`: effective maximum contracts per batch settlement call.
pub fn get_bounds(env: Env) -> ContractBounds {
ContractBounds {
max_milestones: MAX_MILESTONES,
max_single_milestone_stroops: MAX_SINGLE_AMOUNT_STROOPS,
max_total_escrow_stroops: MAX_TOTAL_ESCROW_STROOPS,
max_fee_bps: MAX_FEE_BPS,
max_settlement: Self::effective_max_settlement(&env),
}
}
/// Return the decimal count of the bound settlement token, or `None` when
/// no token has been bound yet.
///
/// The scale is captured at `bind_settlement_token` time by calling
/// `token::Client::decimals()` and is stored as a `u32` under
/// `DataKey::TokenScale`. All milestone amounts submitted to
/// `create_contract` must be exactly divisible by `10^decimals`.
///
/// # Returns
///
/// `Some(decimals)` — the number of decimal places the token uses, or
/// `None` if `bind_settlement_token` has not been called yet.
pub fn get_token_scale(env: Env) -> Option<u32> {
token_scale::read_token_scale(&env)
}
/// Convert a raw on-chain amount to its human-visible (normalized) value
/// using the stored token scale.
///
/// Returns `amount / 10^decimals`. Because `create_contract` enforces
/// exact representability, the division is always exact for any amount that
/// was accepted into storage.
///
/// # Errors
///
/// Panics with [`Error::TokenScaleNotSet`] when `bind_settlement_token` has
/// not been called yet.
///
/// # Examples
///
/// With a 7-decimal token (standard Stellar stroops):
///
/// * `10_000_000` → `1` (1 token)
/// * `500_000_000` → `50` (50 tokens)
pub fn get_normalized_amount(env: Env, raw_amount: i128) -> i128 {
let decimals = token_scale::require_token_scale(&env);
token_scale::normalized_amount(raw_amount, decimals)
}
/// Returns the current mainnet readiness checklist.
///