forked from SO4-Markets/contracts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
1590 lines (1420 loc) · 61 KB
/
Copy pathlib.rs
File metadata and controls
1590 lines (1420 loc) · 61 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
//! Exchange router — single entry point for all user-facing protocol actions.
//! Mirrors GMX's ExchangeRouter.sol.
//!
//! Combines token transfers, vault interactions, and handler calls into
//! atomic multicall transactions. Users approve the router, then call
//! `multicall(Vec<RouterAction>)` with encoded instructions.
//!
//! Supported actions:
//! SendTokens, CreateDeposit, CancelDeposit,
//! CreateWithdrawal, CancelWithdrawal,
//! CreateOrder, UpdateOrder, CancelOrder,
//! ClaimFundingFees
#![no_std]
#![allow(dependency_on_unit_never_type_fallback)]
use gmx_keys::{global_pause_key, is_market_paused_key, scheduled_unpause_ledger_key};
use gmx_types::{CreateDepositParams, CreateOrderParams, CreateWithdrawalParams};
use soroban_sdk::{
contract, contracterror, contractimpl, contracttype, panic_with_error, token, Address, BytesN,
Env, Vec,
};
// ─── Storage keys ─────────────────────────────────────────────────────────────
#[contracttype]
enum InstanceKey {
Initialized,
Admin,
RoleStore,
DataStore,
DepositHandler,
WithdrawalHandler,
OrderHandler,
FeeHandler,
}
// ─── Router-only param structs ────────────────────────────────────────────────
// These are user-facing types for actions that have no handler equivalent.
#[contracttype]
pub struct SendTokensParams {
pub token: Address,
pub receiver: Address,
pub amount: i128,
}
#[contracttype]
pub struct UpdateOrderParams {
pub key: BytesN<32>,
pub size_delta_usd: i128,
pub acceptable_price: i128,
pub trigger_price: i128,
pub min_output_amount: i128,
}
#[contracttype]
pub struct ClaimFundingFeesParams {
pub markets: Vec<Address>,
pub tokens: Vec<Address>,
}
// ─── Multicall action discriminant ────────────────────────────────────────────
/// Each element in a multicall Vec is one action variant.
#[contracttype]
pub enum RouterAction {
SendTokens(SendTokensParams),
CreateDeposit(CreateDepositParams),
CancelDeposit(BytesN<32>),
CreateWithdrawal(CreateWithdrawalParams),
CancelWithdrawal(BytesN<32>),
CreateOrder(CreateOrderParams),
UpdateOrder(UpdateOrderParams),
CancelOrder(BytesN<32>),
ClaimFundingFees(ClaimFundingFeesParams),
}
// ─── Errors ───────────────────────────────────────────────────────────────────
#[contracterror]
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
#[repr(u32)]
pub enum Error {
AlreadyInitialized = 1,
NotInitialized = 2,
Unauthorized = 3,
Paused = 4,
BatchSizeLimitExceeded = 5,
/// `execute_unpause` was called before the timelock window expired (issue #282).
TimelockNotExpired = 6,
/// `execute_unpause` was called without a prior `schedule_unpause` (issue #282).
UnpauseNotScheduled = 7,
}
// ─── External handler clients ─────────────────────────────────────────────────
// Signatures must match the handler contract's public functions exactly.
#[allow(dead_code)]
#[soroban_sdk::contractclient(name = "DataStoreClient")]
trait IDataStore {
fn get_bool(env: Env, key: BytesN<32>) -> bool;
fn set_bool(env: Env, caller: Address, key: BytesN<32>, value: bool) -> bool;
fn get_u128(env: Env, key: BytesN<32>) -> u128;
fn set_u128(env: Env, caller: Address, key: BytesN<32>, value: u128) -> u128;
fn set_position_manager(env: Env, caller: Address, market: Address, manager: Address) -> Address;
fn get_position_manager(env: Env, owner: Address, market: Address) -> Option<Address>;
}
#[allow(dead_code)]
#[soroban_sdk::contractclient(name = "DepositHandlerClient")]
trait IDepositHandler {
fn create_deposit(env: Env, caller: Address, params: CreateDepositParams) -> BytesN<32>;
fn cancel_deposit(env: Env, caller: Address, key: BytesN<32>);
}
#[allow(dead_code)]
#[soroban_sdk::contractclient(name = "WithdrawalHandlerClient")]
trait IWithdrawalHandler {
fn create_withdrawal(env: Env, caller: Address, params: CreateWithdrawalParams) -> BytesN<32>;
fn cancel_withdrawal(env: Env, caller: Address, key: BytesN<32>);
}
#[allow(dead_code)]
#[soroban_sdk::contractclient(name = "OrderHandlerClient")]
trait IOrderHandler {
fn create_order(env: Env, caller: Address, params: CreateOrderParams) -> BytesN<32>;
fn create_orders(env: Env, caller: Address, requests: Vec<CreateOrderParams>) -> Vec<BytesN<32>>;
fn update_order(
env: Env,
caller: Address,
key: BytesN<32>,
size_delta_usd: i128,
acceptable_price: i128,
trigger_price: i128,
min_output_amount: i128,
);
fn cancel_order(env: Env, caller: Address, key: BytesN<32>);
}
#[allow(dead_code)]
#[soroban_sdk::contractclient(name = "FeeHandlerClient")]
trait IFeeHandler {
fn claim_funding_fees(env: Env, account: Address, market: Address, token: Address) -> u128;
fn set_ui_fee_factor(env: Env, ui_receiver: Address, factor: u128);
}
// ─── Contract ─────────────────────────────────────────────────────────────────
#[contract]
pub struct ExchangeRouter;
#[contractimpl]
impl ExchangeRouter {
/// One-time setup — store all handler addresses.
#[allow(clippy::too_many_arguments)]
pub fn initialize(
env: Env,
admin: Address,
role_store: Address,
data_store: Address,
deposit_handler: Address,
withdrawal_handler: Address,
order_handler: Address,
fee_handler: Address,
) {
admin.require_auth();
if env.storage().instance().has(&InstanceKey::Initialized) {
panic_with_error!(&env, Error::AlreadyInitialized);
}
env.storage()
.instance()
.set(&InstanceKey::Initialized, &true);
env.storage().instance().set(&InstanceKey::Admin, &admin);
env.storage()
.instance()
.set(&InstanceKey::RoleStore, &role_store);
env.storage()
.instance()
.set(&InstanceKey::DataStore, &data_store);
env.storage()
.instance()
.set(&InstanceKey::DepositHandler, &deposit_handler);
env.storage()
.instance()
.set(&InstanceKey::WithdrawalHandler, &withdrawal_handler);
env.storage()
.instance()
.set(&InstanceKey::OrderHandler, &order_handler);
env.storage()
.instance()
.set(&InstanceKey::FeeHandler, &fee_handler);
}
/// Upgrade the contract wasm. Only the stored admin may call this.
pub fn upgrade(env: Env, new_wasm_hash: BytesN<32>) {
let admin: Address = env
.storage()
.instance()
.get(&InstanceKey::Admin)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
admin.require_auth();
env.deployer().update_current_contract_wasm(new_wasm_hash);
}
/// Update the withdrawal_handler address. Only the stored admin may call this.
pub fn update_withdrawal_handler(env: Env, caller: Address, new_handler: Address) {
caller.require_auth();
let admin: Address = env
.storage()
.instance()
.get(&InstanceKey::Admin)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
if caller != admin {
panic_with_error!(&env, Error::Unauthorized);
}
env.storage()
.instance()
.set(&InstanceKey::WithdrawalHandler, &new_handler);
}
/// Default timelock for unpausing: ~4 hours at 5 s/ledger (issue #282).
const UNPAUSE_TIMELOCK_LEDGERS: u32 = 2880;
/// Pause the protocol immediately.
///
/// Re-pausing clears any pending `schedule_unpause` so defenders can reset
/// the timelock clock if the threat resurfaces (issue #282).
pub fn set_paused(env: Env, paused: bool) {
let admin: Address = env
.storage()
.instance()
.get(&InstanceKey::Admin)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
admin.require_auth();
let data_store: Address = env
.storage()
.instance()
.get(&InstanceKey::DataStore)
.unwrap();
let ds = DataStoreClient::new(&env, &data_store);
ds.set_bool(
&env.current_contract_address(),
&global_pause_key(&env),
&paused,
);
// Clear any pending unpause schedule when re-pausing.
if paused {
ds.set_u128(
&env.current_contract_address(),
&scheduled_unpause_ledger_key(&env),
&0,
);
}
}
/// Schedule an unpause after `UNPAUSE_TIMELOCK_LEDGERS` ledgers (issue #282).
///
/// Records `current_ledger + UNPAUSE_TIMELOCK_LEDGERS` as the earliest ledger
/// at which `execute_unpause` may succeed. Emits the scheduled ledger as an event
/// so off-chain monitoring can observe the intent. Admin only.
pub fn schedule_unpause(env: Env) {
let admin: Address = env
.storage()
.instance()
.get(&InstanceKey::Admin)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
admin.require_auth();
let data_store: Address = env
.storage()
.instance()
.get(&InstanceKey::DataStore)
.unwrap();
let scheduled_at =
(env.ledger().sequence() + Self::UNPAUSE_TIMELOCK_LEDGERS) as u128;
DataStoreClient::new(&env, &data_store).set_u128(
&env.current_contract_address(),
&scheduled_unpause_ledger_key(&env),
&scheduled_at,
);
env.events().publish(
(soroban_sdk::symbol_short!("unpause_s"),),
scheduled_at,
);
}
/// Execute a previously scheduled unpause if the timelock has expired (issue #282).
///
/// Reverts with `TimelockNotExpired` if called before the scheduled ledger,
/// and with `UnpauseNotScheduled` if `schedule_unpause` was never called (or was
/// cleared by a re-pause). On success, clears both the pause flag and the schedule.
pub fn execute_unpause(env: Env) {
let admin: Address = env
.storage()
.instance()
.get(&InstanceKey::Admin)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
admin.require_auth();
let data_store: Address = env
.storage()
.instance()
.get(&InstanceKey::DataStore)
.unwrap();
let ds = DataStoreClient::new(&env, &data_store);
let router = env.current_contract_address();
let scheduled =
ds.get_u128(&scheduled_unpause_ledger_key(&env));
if scheduled == 0 {
panic_with_error!(&env, Error::UnpauseNotScheduled);
}
if (env.ledger().sequence() as u128) < scheduled {
panic_with_error!(&env, Error::TimelockNotExpired);
}
// Clear pause and schedule.
ds.set_bool(&router, &global_pause_key(&env), &false);
ds.set_u128(&router, &scheduled_unpause_ledger_key(&env), &0);
}
pub fn reset_circuit_breaker(env: Env, market: Address) {
let admin: Address = env
.storage()
.instance()
.get(&InstanceKey::Admin)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
admin.require_auth();
let data_store: Address = env
.storage()
.instance()
.get(&InstanceKey::DataStore)
.unwrap();
DataStoreClient::new(&env, &data_store).set_bool(
&env.current_contract_address(),
&is_market_paused_key(&env, &market),
&false,
);
}
fn require_not_paused(env: &Env) {
let data_store: Address = env
.storage()
.instance()
.get(&InstanceKey::DataStore)
.unwrap_or_else(|| panic_with_error!(env, Error::NotInitialized));
let ds = DataStoreClient::new(env, &data_store);
if ds.get_bool(&global_pause_key(env)) {
panic_with_error!(env, Error::Paused);
}
}
// ── Multicall ─────────────────────────────────────────────────────────────
/// Execute a batch of actions atomically.
///
/// Single caller.require_auth() covers all sub-actions (they run inside this invocation).
/// Returns one BytesN<32> result per action (create_* returns a key; others return zero hash).
/// If any action panics, the entire transaction reverts (Soroban atomicity).
///
/// Handlers are called directly (not via the self-referential public wrappers) to avoid a
/// double require_auth() within the same invocation frame, which Soroban rejects.
pub fn multicall(env: Env, caller: Address, actions: Vec<RouterAction>) -> Vec<BytesN<32>> {
caller.require_auth();
// Issue #453: cancellations must always be available while paused, matching
// the standalone cancel_* wrappers' tested behavior. The pause check is
// applied per-action inside the dispatch loop below instead of as one
// blanket gate here, explicitly skipped for the three cancel actions.
let deposit_handler: Address = env
.storage()
.instance()
.get(&InstanceKey::DepositHandler)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
let withdrawal_handler: Address = env
.storage()
.instance()
.get(&InstanceKey::WithdrawalHandler)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
let order_handler: Address = env
.storage()
.instance()
.get(&InstanceKey::OrderHandler)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
let fee_handler: Address = env
.storage()
.instance()
.get(&InstanceKey::FeeHandler)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
let mut results: Vec<BytesN<32>> = Vec::new(&env);
let zero_key = BytesN::from_array(&env, &[0u8; 32]);
let len = actions.len();
let mut i = 0u32;
while i < len {
let action = actions.get(i).unwrap();
match action {
RouterAction::SendTokens(p) => {
Self::require_not_paused(&env);
token::Client::new(&env, &p.token).transfer(&caller, &p.receiver, &p.amount);
results.push_back(zero_key.clone());
}
RouterAction::CreateDeposit(p) => {
Self::require_not_paused(&env);
let key = DepositHandlerClient::new(&env, &deposit_handler)
.create_deposit(&caller, &p);
results.push_back(key);
}
RouterAction::CancelDeposit(key) => {
// Issue #453: cancellations must always be available while paused.
DepositHandlerClient::new(&env, &deposit_handler).cancel_deposit(&caller, &key);
results.push_back(zero_key.clone());
}
RouterAction::CreateWithdrawal(p) => {
Self::require_not_paused(&env);
let key = WithdrawalHandlerClient::new(&env, &withdrawal_handler)
.create_withdrawal(&caller, &p);
results.push_back(key);
}
RouterAction::CancelWithdrawal(key) => {
// Issue #453: cancellations must always be available while paused.
WithdrawalHandlerClient::new(&env, &withdrawal_handler)
.cancel_withdrawal(&caller, &key);
results.push_back(zero_key.clone());
}
RouterAction::CreateOrder(p) => {
Self::require_not_paused(&env);
let key =
OrderHandlerClient::new(&env, &order_handler).create_order(&caller, &p);
results.push_back(key);
}
RouterAction::UpdateOrder(p) => {
Self::require_not_paused(&env);
OrderHandlerClient::new(&env, &order_handler).update_order(
&caller,
&p.key,
&p.size_delta_usd,
&p.acceptable_price,
&p.trigger_price,
&p.min_output_amount,
);
results.push_back(zero_key.clone());
}
RouterAction::CancelOrder(key) => {
// Issue #453: cancellations must always be available while paused.
OrderHandlerClient::new(&env, &order_handler).cancel_order(&caller, &key);
results.push_back(zero_key.clone());
}
RouterAction::ClaimFundingFees(p) => {
let fee_client = FeeHandlerClient::new(&env, &fee_handler);
let mlen = p.markets.len();
let mut mi = 0u32;
while mi < mlen {
fee_client.claim_funding_fees(
&caller,
&p.markets.get(mi).unwrap(),
&p.tokens.get(mi).unwrap(),
);
mi += 1;
}
results.push_back(zero_key.clone());
}
}
i += 1;
}
results
}
// ── Individual action helpers ─────────────────────────────────────────────
//
// Issue #452: `send_tokens`, `create_order`, and `create_orders` are
// deliberately NOT exposed as standalone entrypoints here. order_vault's
// `record_transfer_in` attributes its balance delta to whoever calls
// create_order/create_orders next, regardless of who actually sent the
// tokens — if funding and order-creation were separate, separately-callable
// transactions, any address could "steal" another user's just-sent
// collateral by racing to call create_order first. Routing both steps
// through `multicall` (atomic, single caller, single transaction) is the
// only supported path for increase/swap orders. Decrease/cancel/update
// actions, which never take fresh collateral, remain available standalone.
/// Forward create_deposit to the deposit_handler.
pub fn create_deposit(env: Env, caller: Address, params: CreateDepositParams) -> BytesN<32> {
caller.require_auth();
Self::require_not_paused(&env);
let deposit_handler: Address = env
.storage()
.instance()
.get(&InstanceKey::DepositHandler)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
DepositHandlerClient::new(&env, &deposit_handler).create_deposit(&caller, ¶ms)
}
/// Forward cancel_deposit to the deposit_handler.
pub fn cancel_deposit(env: Env, caller: Address, key: BytesN<32>) {
caller.require_auth();
let deposit_handler: Address = env
.storage()
.instance()
.get(&InstanceKey::DepositHandler)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
DepositHandlerClient::new(&env, &deposit_handler).cancel_deposit(&caller, &key);
}
/// Forward create_withdrawal to the withdrawal_handler.
pub fn create_withdrawal(
env: Env,
caller: Address,
params: CreateWithdrawalParams,
) -> BytesN<32> {
caller.require_auth();
Self::require_not_paused(&env);
let withdrawal_handler: Address = env
.storage()
.instance()
.get(&InstanceKey::WithdrawalHandler)
.unwrap();
WithdrawalHandlerClient::new(&env, &withdrawal_handler).create_withdrawal(&caller, ¶ms)
}
/// Forward cancel_withdrawal to the withdrawal_handler.
pub fn cancel_withdrawal(env: Env, caller: Address, key: BytesN<32>) {
caller.require_auth();
let withdrawal_handler: Address = env
.storage()
.instance()
.get(&InstanceKey::WithdrawalHandler)
.unwrap();
WithdrawalHandlerClient::new(&env, &withdrawal_handler).cancel_withdrawal(&caller, &key);
}
/// Forward update_order to the order_handler.
pub fn update_order(env: Env, caller: Address, params: UpdateOrderParams) {
caller.require_auth();
Self::require_not_paused(&env);
let order_handler: Address = env
.storage()
.instance()
.get(&InstanceKey::OrderHandler)
.unwrap();
OrderHandlerClient::new(&env, &order_handler).update_order(
&caller,
¶ms.key,
¶ms.size_delta_usd,
¶ms.acceptable_price,
¶ms.trigger_price,
¶ms.min_output_amount,
);
}
/// Forward cancel_order to the order_handler.
pub fn cancel_order(env: Env, caller: Address, key: BytesN<32>) {
caller.require_auth();
let order_handler: Address = env
.storage()
.instance()
.get(&InstanceKey::OrderHandler)
.unwrap();
OrderHandlerClient::new(&env, &order_handler).cancel_order(&caller, &key);
}
/// Claim earned funding fees across multiple markets in one call.
pub fn claim_funding_fees(
env: Env,
caller: Address,
markets: Vec<Address>,
tokens: Vec<Address>,
) {
caller.require_auth();
let fee_handler: Address = env
.storage()
.instance()
.get(&InstanceKey::FeeHandler)
.unwrap();
let fee_client = FeeHandlerClient::new(&env, &fee_handler);
let len = markets.len();
let mut i = 0u32;
while i < len {
fee_client.claim_funding_fees(
&caller,
&markets.get(i).unwrap(),
&tokens.get(i).unwrap(),
);
i += 1;
}
}
/// Set or revoke a position manager for the caller on a specific market.
///
/// A position manager is authorized to create, increase, decrease, or close
/// positions on behalf of the owner, but cannot redirect collateral receipts.
/// The manager cannot override the receiver — funds always go to the owner.
///
/// Call with zero_address to revoke an existing manager.
pub fn set_position_manager(env: Env, caller: Address, market: Address, manager: Address) {
caller.require_auth();
let data_store: Address = env.storage().instance()
.get(&InstanceKey::DataStore)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
let data_store_client = DataStoreClient::new(&env, &data_store);
data_store_client.set_position_manager(&caller, &market, &manager);
}
/// Query the current position manager for an account on a specific market.
pub fn get_position_manager(env: Env, owner: Address, market: Address) -> Option<Address> {
let data_store: Address = env.storage().instance()
.get(&InstanceKey::DataStore)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
let data_store_client = DataStoreClient::new(&env, &data_store);
data_store_client.get_position_manager(&owner, &market)
}
/// Set the UI fee factor for a receiver. Delegates auth enforcement to fee_handler.
pub fn set_ui_fee_factor(env: Env, ui_receiver: Address, factor: u128) {
let fee_handler: Address = env
.storage()
.instance()
.get(&InstanceKey::FeeHandler)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
FeeHandlerClient::new(&env, &fee_handler).set_ui_fee_factor(&ui_receiver, &factor);
}
}
// ─── Tests — Issues #101 #102 #103 #104: Full protocol E2E harness ────────────
//
// Issue #101: Reusable setup that deploys all contracts, grants roles, creates
// tokens and markets, sets oracle prices, and seeds liquidity.
// Done: New E2E tests share a single setup(); boilerplate is not copy-pasted.
//
// Issue #102: Deposit-to-withdrawal E2E through the full handler stack.
// Done: User recovers expected tokens within acceptable rounding.
// Pool amounts return to baseline.
//
// Issue #103: LP deposit → trader opens position → price moves → position closes
// → LP withdraws. Pool accounting must be consistent throughout.
// Done: Pool accounting is consistent at every step.
// Trader PnL and LP redemption values are correct.
//
// Issue #104: Liquidation via generated contract clients (deployed-style),
// not direct utility function calls.
// Done: Test uses client-based invocation. Succeeds for underwater position.
// Fails for healthy position.
#[cfg(test)]
mod tests {
use super::*;
use data_store::{DataStore, DataStoreClient as DsClient};
use deposit_handler::{DepositHandler, DepositHandlerClient};
use deposit_vault::{DepositVault, DepositVaultClient as DVClient};
use gmx_keys::roles;
use gmx_math::FLOAT_PRECISION;
use gmx_types::{
CreateDepositParams, CreateOrderParams, CreateWithdrawalParams, OrderType, TokenPrice,
};
use liquidation_handler::{LiquidationHandler, LiquidationHandlerClient as LHClient};
use market_token::{MarketToken, MarketTokenClient as MtClient};
use oracle::{Oracle, OracleClient as OClient};
use order_handler::{OrderHandler, OrderHandlerClient as OHClient};
use order_vault::{OrderVault, OrderVaultClient as OVClient};
use role_store::{RoleStore, RoleStoreClient as RsClient};
use soroban_sdk::{testutils::Address as _, token::StellarAssetClient, Env};
use withdrawal_handler::{WithdrawalHandler, WithdrawalHandlerClient};
use withdrawal_vault::{WithdrawalVault, WithdrawalVaultClient as WVClient};
const ONE_TOKEN: i128 = 10_000_000; // Stellar 7-decimal precision
// ── Issue #101: shared full-protocol harness ──────────────────────────────
struct World {
env: Env,
admin: Address,
keeper: Address,
liq_keeper: Address,
rs: Address,
ds: Address,
oracle: Address,
dep_vault: Address,
wth_vault: Address,
ord_vault: Address,
dep_handler: Address,
wth_handler: Address,
ord_handler: Address,
liq_handler: Address,
#[allow(dead_code)]
router: Address,
market_tk: Address,
long_tk: Address,
short_tk: Address,
index_tk: Address,
}
fn setup() -> World {
let env = Env::default();
env.mock_all_auths();
env.cost_estimate().budget().reset_unlimited();
let admin = Address::generate(&env);
let keeper = Address::generate(&env);
let liq_keeper = Address::generate(&env);
// Role store
let rs = env.register(RoleStore, ());
let rs_c = RsClient::new(&env, &rs);
rs_c.initialize(&admin);
rs_c.grant_role(&admin, &admin, &roles::controller(&env));
rs_c.grant_role(&admin, &keeper, &roles::order_keeper(&env));
rs_c.grant_role(&admin, &liq_keeper, &roles::liquidation_keeper(&env));
// Data store
let ds = env.register(DataStore, ());
DsClient::new(&env, &ds).initialize(&admin, &rs);
// Oracle
let oracle_addr = env.register(Oracle, ());
let passphrase = soroban_sdk::Bytes::from_slice(&env, b"Test SDF Network ; September 2015");
OClient::new(&env, &oracle_addr).initialize(&admin, &rs, &ds, &passphrase);
// Vaults
let dep_vault = env.register(DepositVault, ());
DVClient::new(&env, &dep_vault).initialize(&admin, &rs);
let wth_vault = env.register(WithdrawalVault, ());
WVClient::new(&env, &wth_vault).initialize(&admin, &rs);
let ord_vault = env.register(OrderVault, ());
OVClient::new(&env, &ord_vault).initialize(&admin, &rs);
// Market token (LP token + pool custodian)
let market_tk = env.register(MarketToken, ());
MtClient::new(&env, &market_tk).initialize(
&admin,
&rs,
&7u32,
&soroban_sdk::String::from_str(&env, "SO4 Market"),
&soroban_sdk::String::from_str(&env, "GM"),
);
// Underlying tokens
let long_tk = env
.register_stellar_asset_contract_v2(admin.clone())
.address();
let short_tk = env
.register_stellar_asset_contract_v2(admin.clone())
.address();
let index_tk = Address::generate(&env);
// Handlers
let dep_handler = env.register(DepositHandler, ());
DepositHandlerClient::new(&env, &dep_handler).initialize(
&admin,
&rs,
&ds,
&oracle_addr,
&dep_vault,
);
let wth_handler = env.register(WithdrawalHandler, ());
WithdrawalHandlerClient::new(&env, &wth_handler).initialize(
&admin,
&rs,
&ds,
&oracle_addr,
&wth_vault,
);
let ord_handler = env.register(OrderHandler, ());
OHClient::new(&env, &ord_handler).initialize(&admin, &rs, &ds, &oracle_addr, &ord_vault);
let liq_handler = env.register(LiquidationHandler, ());
LHClient::new(&env, &liq_handler).initialize(&admin, &rs, &ds, &oracle_addr, &ord_handler);
// Exchange router (fee_handler is unused in E2E tests — dummy address)
let fee_handler_dummy = Address::generate(&env);
let router = env.register(ExchangeRouter, ());
ExchangeRouterClient::new(&env, &router).initialize(
&admin,
&rs,
&ds,
&dep_handler,
&wth_handler,
&ord_handler,
&fee_handler_dummy,
);
// Grant CONTROLLER to all handlers and the router (router writes global_pause_key)
rs_c.grant_role(&admin, &dep_handler, &roles::controller(&env));
rs_c.grant_role(&admin, &wth_handler, &roles::controller(&env));
rs_c.grant_role(&admin, &ord_handler, &roles::controller(&env));
rs_c.grant_role(&admin, &liq_handler, &roles::controller(&env));
rs_c.grant_role(&admin, &router, &roles::controller(&env));
// Register market in DataStore
let ds_c = DsClient::new(&env, &ds);
ds_c.set_address(
&admin,
&gmx_keys::market_index_token_key(&env, &market_tk),
&index_tk,
);
ds_c.set_address(
&admin,
&gmx_keys::market_long_token_key(&env, &market_tk),
&long_tk,
);
ds_c.set_address(
&admin,
&gmx_keys::market_short_token_key(&env, &market_tk),
&short_tk,
);
// Market config: 0.1% position fee, 1% min collateral factor, 100x max leverage
let fee_factor = FLOAT_PRECISION / 1000;
let min_col_factor = FLOAT_PRECISION / 100;
ds_c.set_u128(
&admin,
&gmx_keys::position_fee_factor_key(&env, &market_tk, true),
&(fee_factor as u128),
);
ds_c.set_u128(
&admin,
&gmx_keys::position_fee_factor_key(&env, &market_tk, false),
&(fee_factor as u128),
);
ds_c.set_u128(
&admin,
&gmx_keys::min_collateral_factor_key(&env, &market_tk),
&(min_col_factor as u128),
);
ds_c.set_u128(
&admin,
&gmx_keys::max_leverage_key(&env, &market_tk),
&(100 * FLOAT_PRECISION as u128),
);
World {
env,
admin,
keeper,
liq_keeper,
rs,
ds,
oracle: oracle_addr,
dep_vault,
wth_vault,
ord_vault,
dep_handler,
wth_handler,
ord_handler,
liq_handler,
router,
market_tk,
long_tk,
short_tk,
index_tk,
}
}
fn set_prices(w: &World, index_usd: i128) {
let fp = FLOAT_PRECISION;
OClient::new(&w.env, &w.oracle).set_prices_simple(
&w.keeper,
&soroban_sdk::Vec::from_array(
&w.env,
[
TokenPrice {
token: w.long_tk.clone(),
min: index_usd,
max: index_usd,
},
TokenPrice {
token: w.short_tk.clone(),
min: fp,
max: fp,
},
TokenPrice {
token: w.index_tk.clone(),
min: index_usd,
max: index_usd,
},
],
),
);
}
/// Mint tokens to `lp`, deposit them through the deposit handler, execute, return minted LP balance.
fn provide_liquidity(w: &World, lp: &Address, long_amt: i128, short_amt: i128) -> i128 {
if long_amt > 0 {
StellarAssetClient::new(&w.env, &w.long_tk).mint(lp, &long_amt);
}
if short_amt > 0 {
StellarAssetClient::new(&w.env, &w.short_tk).mint(lp, &short_amt);
}
let key = DepositHandlerClient::new(&w.env, &w.dep_handler).create_deposit(
lp,
&CreateDepositParams {
receiver: lp.clone(),
market: w.market_tk.clone(),
initial_long_token: w.long_tk.clone(),
initial_short_token: w.short_tk.clone(),
long_token_amount: long_amt,
short_token_amount: short_amt,
min_market_tokens: 1,
execution_fee: 0,
},
);
DepositHandlerClient::new(&w.env, &w.dep_handler).execute_deposit(&w.keeper, &key);
MtClient::new(&w.env, &w.market_tk).balance(lp)
}
/// Mint collateral to `user`, transfer to order vault (canonical collateral model),
/// then create and execute a MarketIncrease long order.
fn open_long_position(w: &World, user: &Address, collateral_tokens: i128, size_usd: i128) {
StellarAssetClient::new(&w.env, &w.long_tk).mint(user, &collateral_tokens);
soroban_sdk::token::Client::new(&w.env, &w.long_tk).transfer(
user,
&w.ord_vault,
&collateral_tokens,
);
let hc = OHClient::new(&w.env, &w.ord_handler);
let key = hc.create_order(
user,
&CreateOrderParams {
receiver: user.clone(),
market: w.market_tk.clone(),
initial_collateral_token: w.long_tk.clone(),
swap_path: soroban_sdk::Vec::new(&w.env),
size_delta_usd: size_usd,
collateral_delta_amount: collateral_tokens,
trigger_price: 0,
acceptable_price: 0,
execution_fee: 0,
min_output_amount: 0,
order_type: OrderType::MarketIncrease,
is_long: true,
expiry_ledger: None,
},
);
hc.execute_order(&w.keeper, &key);
}
// ── Issue #102: deposit-to-withdrawal E2E ────────────────────────────────
/// Full LP lifecycle: deposit long+short → receive LP → withdraw all → recover tokens.
/// Asserts user recovers tokens and pool returns to zero (single-depositor, no trades).
#[test]
fn e2e_deposit_then_withdraw_recovers_tokens() {
let w = setup();
let fp = FLOAT_PRECISION;
let lp = Address::generate(&w.env);
set_prices(&w, 2_000 * fp);
let long_amt = 5 * ONE_TOKEN;
let short_amt = 5_000 * ONE_TOKEN;
StellarAssetClient::new(&w.env, &w.long_tk).mint(&lp, &long_amt);
StellarAssetClient::new(&w.env, &w.short_tk).mint(&lp, &short_amt);
let lp_tokens = provide_liquidity(&w, &lp, long_amt, short_amt);
assert!(lp_tokens > 0, "LP tokens must be minted on deposit");
let ds_c = DsClient::new(&w.env, &w.ds);
assert_eq!(
ds_c.get_u128(&gmx_keys::pool_amount_key(&w.env, &w.market_tk, &w.long_tk)),
long_amt as u128,
"long pool must match deposit"
);
assert_eq!(
ds_c.get_u128(&gmx_keys::pool_amount_key(
&w.env,
&w.market_tk,
&w.short_tk
)),
short_amt as u128,
"short pool must match deposit"
);
set_prices(&w, 2_000 * fp);
// Withdraw all LP tokens
let wth_key = WithdrawalHandlerClient::new(&w.env, &w.wth_handler).create_withdrawal(
&lp,
&CreateWithdrawalParams {
receiver: lp.clone(),
market: w.market_tk.clone(),
market_token_amount: lp_tokens,
min_long_token_amount: 0,
min_short_token_amount: 0,
execution_fee: 0,
},
);
WithdrawalHandlerClient::new(&w.env, &w.wth_handler)
.execute_withdrawal(&w.keeper, &wth_key);
assert_eq!(
MtClient::new(&w.env, &w.market_tk).balance(&lp),
0,
"LP tokens must be fully burned after withdrawal"
);
let long_back = StellarAssetClient::new(&w.env, &w.long_tk).balance(&lp);
let short_back = StellarAssetClient::new(&w.env, &w.short_tk).balance(&lp);
assert!(
long_back > 0 || short_back > 0,