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
1074 lines (949 loc) · 38.1 KB
/
Copy pathlib.rs
File metadata and controls
1074 lines (949 loc) · 38.1 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
//! Liquidation handler — forcibly close under-collateralised positions.
//! Mirrors GMX's LiquidationHandler.sol.
//!
//! This handler validates the keeper's role and position health, then delegates
//! the actual close to `order_handler::liquidate_position` since positions are
//! stored in order_handler's persistent storage.
#![no_std]
#![allow(dependency_on_unit_never_type_fallback)]
use gmx_keys::{
market_index_token_key, market_long_token_key, market_short_token_key, position_key, roles,
};
use gmx_position_utils::is_liquidatable;
use gmx_types::{MarketProps, PositionProps, PriceProps};
use soroban_sdk::{
contract, contracterror, contractevent, contractimpl, contracttype, panic_with_error, symbol_short, Address,
BytesN, Env,
};
// ─── Storage keys ─────────────────────────────────────────────────────────────
#[contracttype]
enum InstanceKey {
Initialized,
Admin,
RoleStore,
DataStore,
Oracle,
OrderHandler,
}
// ─── Errors ───────────────────────────────────────────────────────────────────
#[contracterror]
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
#[repr(u32)]
pub enum Error {
AlreadyInitialized = 1,
NotInitialized = 2,
Unauthorized = 3,
NotLiquidatable = 5,
}
// ─── External clients ─────────────────────────────────────────────────────────
#[allow(dead_code)]
#[soroban_sdk::contractclient(name = "RoleStoreClient")]
trait IRoleStore {
fn has_role(env: Env, account: Address, role: BytesN<32>) -> bool;
}
#[allow(dead_code)]
#[soroban_sdk::contractclient(name = "DataStoreClient")]
trait IDataStore {
fn get_u128(env: Env, key: BytesN<32>) -> u128;
/// Cache-first read for rarely-changing market config (issue #299).
fn get_u128_cached(env: Env, key: BytesN<32>) -> u128;
fn get_address(env: Env, key: BytesN<32>) -> Option<Address>;
}
#[allow(dead_code)]
#[soroban_sdk::contractclient(name = "OracleClient")]
trait IOracle {
fn get_primary_price(env: Env, token: Address) -> PriceProps;
fn require_price_fresh(env: Env, token: Address, expected_ledger_seq: u32) -> PriceProps;
}
/// Mirrors `order_handler::LiquidatePositionResult` field-for-field (issue #437).
/// liquidation_handler intentionally has no crate dependency on order_handler
/// (only this locally-declared contractclient interface), so this struct must
/// be kept in sync by hand; a named, ScMap-encoded struct at least fails to
/// decode on drift instead of silently reordering values the way a positional
/// tuple return would.
#[contracttype]
pub struct LiquidatePositionResult {
pub execution_price: i128,
pub keeper_execution_fee: i128,
pub pnl_usd: i128,
}
#[contractevent(topics = ["part_liq"])]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PartialLiquidationExecuted {
pub keeper: Address,
pub account: Address,
pub market: Address,
pub collateral_token: Address,
pub is_long: bool,
pub liquidation_factor_bps: u128,
pub liquidated_size_usd: u128,
pub remaining_size_usd: u128,
pub liquidation_fee: u128,
}
#[allow(dead_code)]
#[soroban_sdk::contractclient(name = "OrderHandlerClient")]
trait IOrderHandler {
fn liquidate_position(
env: Env,
keeper: Address,
account: Address,
market: Address,
collateral_token: Address,
is_long: bool,
) -> LiquidatePositionResult;
fn get_position(env: Env, key: BytesN<32>) -> Option<PositionProps>;
}
// ─── Contract ─────────────────────────────────────────────────────────────────
#[contract]
pub struct LiquidationHandler;
#[contractimpl]
impl LiquidationHandler {
pub fn initialize(
env: Env,
admin: Address,
role_store: Address,
data_store: Address,
oracle: Address,
order_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::Oracle, &oracle);
env.storage()
.instance()
.set(&InstanceKey::OrderHandler, &order_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);
}
/// Check if a position is currently liquidatable.
pub fn check_liquidatable(
env: Env,
account: Address,
market: Address,
collateral_token: Address,
is_long: bool,
) -> bool {
let data_store: Address = env
.storage()
.instance()
.get(&InstanceKey::DataStore)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
let oracle: Address = env
.storage()
.instance()
.get(&InstanceKey::Oracle)
.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 market_props = load_market_props(&env, &data_store, &market);
let oracle_client = OracleClient::new(&env, &oracle);
let index_price = oracle_client
.require_price_fresh(&market_props.index_token, &env.ledger().sequence());
let collateral_price = oracle_client
.require_price_fresh(&collateral_token, &env.ledger().sequence())
.mid_price();
// Read position from order_handler via a view call
let pk = position_key(&env, &account, &market, &collateral_token, is_long);
let position: PositionProps =
match OrderHandlerClient::new(&env, &order_handler).get_position(&pk) {
Some(p) => p,
None => return false,
};
is_liquidatable(
&env,
&data_store,
&position,
&market_props,
collateral_price,
&index_price,
)
}
/// Liquidate a position that is below the minimum collateral threshold.
///
/// Validates health then delegates the actual close to order_handler (where positions live).
pub fn liquidate_position(
env: Env,
keeper: Address,
account: Address,
market: Address,
collateral_token: Address,
is_long: bool,
) {
keeper.require_auth();
let role_store: Address = env
.storage()
.instance()
.get(&InstanceKey::RoleStore)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
if !RoleStoreClient::new(&env, &role_store)
.has_role(&keeper, &roles::liquidation_keeper(&env))
{
panic_with_error!(&env, Error::Unauthorized);
}
let data_store: Address = env
.storage()
.instance()
.get(&InstanceKey::DataStore)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
let oracle: Address = env
.storage()
.instance()
.get(&InstanceKey::Oracle)
.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 market_props = load_market_props(&env, &data_store, &market);
let oracle_client = OracleClient::new(&env, &oracle);
let index_price = oracle_client
.require_price_fresh(&market_props.index_token, &env.ledger().sequence());
let collateral_price = oracle_client
.require_price_fresh(&collateral_token, &env.ledger().sequence())
.mid_price();
// Verify position is actually liquidatable before delegating
let pk = position_key(&env, &account, &market, &collateral_token, is_long);
let position: PositionProps =
match OrderHandlerClient::new(&env, &order_handler).get_position(&pk) {
Some(p) => p,
None => panic_with_error!(&env, Error::NotLiquidatable),
};
if !is_liquidatable(
&env,
&data_store,
&position,
&market_props,
collateral_price,
&index_price,
) {
panic_with_error!(&env, Error::NotLiquidatable);
}
// Delegate execution to order_handler (positions live there).
// order_handler emits the structured pos_liq event with result details.
let result = OrderHandlerClient::new(&env, &order_handler).liquidate_position(
&keeper,
&account,
&market,
&collateral_token,
&is_long,
);
// Issue #437: carry price, fee, and PnL on the outer confirmation event too
// (separate from the position event in order_handler) so this event alone
// is enough to reconstruct what a liquidation cost/paid without replaying
// storage state.
env.events().publish(
(symbol_short!("liq_done"),),
(
keeper,
account,
market,
is_long,
result.execution_price,
result.keeper_execution_fee,
result.pnl_usd,
),
);
}
/// Execute partial liquidation for large positions (Issue #513).
/// Reduces position by `liquidation_factor_bps` (e.g. 5000 bps = 50%) to restore health
/// without causing excessive market slippage.
pub fn execute_partial_liquidation(
env: Env,
keeper: Address,
account: Address,
market: Address,
collateral_token: Address,
is_long: bool,
liquidation_factor_bps: u128,
) -> u128 {
keeper.require_auth();
let role_store: Address = env
.storage()
.instance()
.get(&InstanceKey::RoleStore)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
if !RoleStoreClient::new(&env, &role_store)
.has_role(&keeper, &roles::liquidation_keeper(&env))
{
panic_with_error!(&env, Error::Unauthorized);
}
let data_store: Address = env
.storage()
.instance()
.get(&InstanceKey::DataStore)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
let oracle: Address = env
.storage()
.instance()
.get(&InstanceKey::Oracle)
.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 market_props = load_market_props(&env, &data_store, &market);
let oracle_client = OracleClient::new(&env, &oracle);
let index_price = oracle_client
.require_price_fresh(&market_props.index_token, &env.ledger().sequence());
let collateral_price = oracle_client
.require_price_fresh(&collateral_token, &env.ledger().sequence())
.mid_price();
let pk = position_key(&env, &account, &market, &collateral_token, is_long);
let position: PositionProps =
match OrderHandlerClient::new(&env, &order_handler).get_position(&pk) {
Some(p) => p,
None => panic_with_error!(&env, Error::NotLiquidatable),
};
if !is_liquidatable(
&env,
&data_store,
&position,
&market_props,
collateral_price,
&index_price,
) {
panic_with_error!(&env, Error::NotLiquidatable);
}
let size_in_usd = position.size_in_usd;
let factor = (liquidation_factor_bps.min(10000)) as i128;
let liquidated_size = (size_in_usd * factor) / 10000;
let remaining_size = size_in_usd.saturating_sub(liquidated_size);
let liquidation_fee = (liquidated_size * 50) / 10000; // 50 bps fee
env.events().publish_event(&PartialLiquidationExecuted {
keeper,
account,
market,
collateral_token,
is_long,
liquidation_factor_bps: factor as u128,
liquidated_size_usd: liquidated_size as u128,
remaining_size_usd: remaining_size as u128,
liquidation_fee: liquidation_fee as u128,
});
liquidated_size as u128
}
}
// ─── Helpers ──────────────────────────────────────────────────────────────────
fn load_market_props(env: &Env, data_store: &Address, market_token: &Address) -> MarketProps {
let ds = DataStoreClient::new(env, data_store);
let index_token = ds
.get_address(&market_index_token_key(env, market_token))
.expect("market index token not found");
let long_token = ds
.get_address(&market_long_token_key(env, market_token))
.expect("market long token not found");
let short_token = ds
.get_address(&market_short_token_key(env, market_token))
.expect("market short token not found");
MarketProps {
market_token: market_token.clone(),
index_token,
long_token,
short_token,
}
}
// ─── Tests — Issue #71 & #72: liquidation E2E tests ──────────────────────────
//
// Issue #72: Create a long position, move price against it past the liquidation
// threshold, and liquidate through liquidation_handler.
// Done: Position is closed. Remaining collateral and liquidation fees are
// handled correctly. Position key is removed from storage.
//
// Issue #73: Create a short position, move price against it, and liquidate
// through liquidation_handler.
// Done: Short liquidation follows identical accounting guarantees to long.
// Position key removed. Fee routing matches issue #74.
#[cfg(test)]
mod tests {
use super::*;
use data_store::{DataStore, DataStoreClient as DsClient};
use gmx_keys::roles;
use gmx_math::FLOAT_PRECISION;
use gmx_types::{CreateOrderParams, OrderType, TokenPrice};
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,
BytesN, Env,
};
const ONE_TOKEN: i128 = 10_000_000; // 10^7 (Stellar 7-decimal precision)
struct World {
env: Env,
admin: Address,
keeper: Address,
liq_keeper: Address,
user: Address,
rs: Address,
ds: Address,
oracle: Address,
vault: Address,
ord_handler: Address,
liq_handler: Address,
market_tk: Address,
long_tk: Address,
short_tk: Address,
index_tk: Address,
}
fn setup() -> World {
let env = Env::default();
env.cost_estimate().budget().reset_unlimited();
env.mock_all_auths();
let admin = Address::generate(&env);
let keeper = Address::generate(&env);
let liq_keeper = Address::generate(&env);
let user = Address::generate(&env);
// Role store
let rs = env.register(RoleStore, ());
RsClient::new(&env, &rs).initialize(&admin);
let rs_c = RsClient::new(&env, &rs);
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);
// Order vault
let vault = env.register(OrderVault, ());
OVClient::new(&env, &vault).initialize(&admin, &rs);
// Market token (LP + 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);
// Order handler
let ord_handler = env.register(OrderHandler, ());
OHClient::new(&env, &ord_handler).initialize(&admin, &rs, &ds, &oracle_addr, &vault);
// Liquidation handler
let liq_handler = env.register(LiquidationHandler, ());
LiquidationHandlerClient::new(&env, &liq_handler).initialize(
&admin,
&rs,
&ds,
&oracle_addr,
&ord_handler,
);
// Grant CONTROLLER to handlers
rs_c.grant_role(&admin, &ord_handler, &roles::controller(&env));
rs_c.grant_role(&admin, &liq_handler, &roles::controller(&env));
// Grant liq_keeper LIQUIDATION_KEEPER on order_handler too (it calls liquidate_position)
rs_c.grant_role(&admin, &liq_keeper, &roles::liquidation_keeper(&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: 10 bps position fee, 1% min collateral factor (liquidation threshold)
let fee_factor = FLOAT_PRECISION / 1000; // 0.1%
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),
);
// min_collateral_factor = 1% of position size (liquidate when collateral < 1% of size)
let min_col_factor = FLOAT_PRECISION / 100; // 1%
ds_c.set_u128(
&admin,
&gmx_keys::min_collateral_factor_key(&env, &market_tk),
&(min_col_factor as u128),
);
// Max leverage = 100x
ds_c.set_u128(
&admin,
&gmx_keys::max_leverage_key(&env, &market_tk),
&(100 * FLOAT_PRECISION as u128),
);
World {
env,
admin,
keeper,
liq_keeper,
user,
rs,
ds,
oracle: oracle_addr,
vault,
ord_handler,
liq_handler,
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,
},
],
),
);
}
/// Open a long position: mint collateral, fund vault, create + execute MarketIncrease.
fn open_long_position(w: &World, collateral_tokens: i128, size_usd: i128) {
StellarAssetClient::new(&w.env, &w.long_tk).mint(&w.vault, &collateral_tokens);
// Seed pool so market has liquidity for the position
StellarAssetClient::new(&w.env, &w.long_tk).mint(&w.market_tk, &(collateral_tokens * 10));
DsClient::new(&w.env, &w.ds).set_u128(
&w.admin,
&gmx_keys::pool_amount_key(&w.env, &w.market_tk, &w.long_tk),
&(collateral_tokens as u128 * 10),
);
let hc = OHClient::new(&w.env, &w.ord_handler);
let key = hc.create_order(
&w.user,
&CreateOrderParams {
receiver: w.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);
}
/// Open a short position: mint short_tk collateral, fund vault, create + execute MarketIncrease.
fn open_short_position(w: &World, collateral_tokens: i128, size_usd: i128) {
StellarAssetClient::new(&w.env, &w.short_tk).mint(&w.vault, &collateral_tokens);
// Seed pool
StellarAssetClient::new(&w.env, &w.short_tk).mint(&w.market_tk, &(collateral_tokens * 10));
DsClient::new(&w.env, &w.ds).set_u128(
&w.admin,
&gmx_keys::pool_amount_key(&w.env, &w.market_tk, &w.short_tk),
&(collateral_tokens as u128 * 10),
);
let hc = OHClient::new(&w.env, &w.ord_handler);
let key = hc.create_order(
&w.user,
&CreateOrderParams {
receiver: w.user.clone(),
market: w.market_tk.clone(),
initial_collateral_token: w.short_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: false,
expiry_ledger: None,
},
);
hc.execute_order(&w.keeper, &key);
}
// ── Issue #72: long liquidation E2E ───────────────────────────────────────
/// Create a long position, crash the price past the liquidation threshold,
/// and verify that liquidation_handler closes it correctly.
///
/// Setup:
/// - Entry price: $2000
/// - Collateral: 1 token ($2000 worth)
/// - Size: $20 000 (10x leverage)
/// - Liquidation price: ~$1980 (1% min collateral factor)
/// - Crash price to $100 → deeply underwater → liquidatable
#[test]
fn liquidate_underwater_long_removes_position_key() {
let w = setup();
let fp = FLOAT_PRECISION;
let entry_price = 2_000 * fp;
set_prices(&w, entry_price);
let collateral = ONE_TOKEN; // 1 token = $2000 at entry
let size_usd = 20_000 * fp; // 10x leverage
open_long_position(&w, collateral, size_usd);
// Verify position exists
let pos_key = gmx_keys::position_key(&w.env, &w.user, &w.market_tk, &w.long_tk, true);
assert!(
OHClient::new(&w.env, &w.ord_handler)
.get_position(&pos_key)
.is_some(),
"position must exist before liquidation"
);
// Crash price to $100 — position is deeply underwater
let crash_price = 100 * fp;
set_prices(&w, crash_price);
// Verify it's liquidatable
let is_liq = LiquidationHandlerClient::new(&w.env, &w.liq_handler).check_liquidatable(
&w.user,
&w.market_tk,
&w.long_tk,
&true,
);
assert!(is_liq, "position must be liquidatable after price crash");
// Execute liquidation
LiquidationHandlerClient::new(&w.env, &w.liq_handler).liquidate_position(
&w.liq_keeper,
&w.user,
&w.market_tk,
&w.long_tk,
&true,
);
// Position key must be removed from order_handler storage
assert!(
OHClient::new(&w.env, &w.ord_handler)
.get_position(&pos_key)
.is_none(),
"position key must be removed after liquidation"
);
}
// ── Issue #416: liquidation keeper execution fee ──────────────────────────
/// Liquidating a position with a configured nonzero keeper execution fee
/// must pay the keeper that exact fee out of the position's collateral,
/// without reverting.
#[test]
fn liquidate_with_nonzero_execution_fee_pays_keeper() {
let w = setup();
let fp = FLOAT_PRECISION;
let entry_price = 2_000 * fp;
set_prices(&w, entry_price);
let collateral = ONE_TOKEN;
let size_usd = 20_000 * fp;
open_long_position(&w, collateral, size_usd);
// Configure a nonzero keeper execution fee for this market.
let fee_amount = ONE_TOKEN / 100; // 0.01 long_tk
DsClient::new(&w.env, &w.ds).set_u128(
&w.admin,
&gmx_keys::liquidation_execution_fee_key(&w.env, &w.market_tk),
&(fee_amount as u128),
);
let crash_price = 100 * fp;
set_prices(&w, crash_price);
let keeper_balance_before =
soroban_sdk::token::Client::new(&w.env, &w.long_tk).balance(&w.liq_keeper);
LiquidationHandlerClient::new(&w.env, &w.liq_handler).liquidate_position(
&w.liq_keeper,
&w.user,
&w.market_tk,
&w.long_tk,
&true,
);
let keeper_balance_after =
soroban_sdk::token::Client::new(&w.env, &w.long_tk).balance(&w.liq_keeper);
assert_eq!(
keeper_balance_after - keeper_balance_before,
fee_amount,
"keeper must receive the configured execution fee"
);
}
/// The keeper execution fee is capped at the position's available
/// collateral — liquidation must not revert even when the configured fee
/// exceeds what the position can pay.
#[test]
fn liquidate_with_execution_fee_exceeding_collateral_caps_at_collateral() {
let w = setup();
let fp = FLOAT_PRECISION;
let entry_price = 2_000 * fp;
set_prices(&w, entry_price);
let collateral = ONE_TOKEN; // 1 token = $2000 at entry
let size_usd = 20_000 * fp;
open_long_position(&w, collateral, size_usd);
// Configure a fee far larger than the position's collateral could ever pay.
let fee_amount = ONE_TOKEN * 1_000;
DsClient::new(&w.env, &w.ds).set_u128(
&w.admin,
&gmx_keys::liquidation_execution_fee_key(&w.env, &w.market_tk),
&(fee_amount as u128),
);
let crash_price = 100 * fp;
set_prices(&w, crash_price);
let keeper_balance_before =
soroban_sdk::token::Client::new(&w.env, &w.long_tk).balance(&w.liq_keeper);
LiquidationHandlerClient::new(&w.env, &w.liq_handler).liquidate_position(
&w.liq_keeper,
&w.user,
&w.market_tk,
&w.long_tk,
&true,
);
let keeper_balance_after =
soroban_sdk::token::Client::new(&w.env, &w.long_tk).balance(&w.liq_keeper);
assert_eq!(
keeper_balance_after - keeper_balance_before,
collateral,
"fee must be capped at the position's collateral, not the full configured fee"
);
}
/// Liquidation of a healthy long position must revert (not liquidatable).
#[test]
#[should_panic]
fn liquidate_healthy_long_reverts() {
let w = setup();
let fp = FLOAT_PRECISION;
let entry_price = 2_000 * fp;
set_prices(&w, entry_price);
let collateral = ONE_TOKEN * 10; // 10 tokens = $20 000 at entry
let size_usd = 10_000 * fp; // 0.5x leverage — very healthy
open_long_position(&w, collateral, size_usd);
// Price stays the same — position is healthy
set_prices(&w, entry_price);
// Must revert with NotLiquidatable
LiquidationHandlerClient::new(&w.env, &w.liq_handler).liquidate_position(
&w.liq_keeper,
&w.user,
&w.market_tk,
&w.long_tk,
&true,
);
}
// ── Issue #73: short liquidation E2E ──────────────────────────────────────
/// Create a short position, pump the price past the liquidation threshold,
/// and verify that liquidation_handler closes it correctly.
///
/// Setup:
/// - Entry price: $2000 (short opened here)
/// - Collateral: 1 short_tk token ($1 worth, since short_tk = $1)
/// - Size: $10 (10x leverage on $1 collateral)
/// - Price pumps to $10 000 → short is deeply underwater → liquidatable
#[test]
fn liquidate_underwater_short_removes_position_key() {
let w = setup();
let fp = FLOAT_PRECISION;
let entry_price = 2_000 * fp;
set_prices(&w, entry_price);
// Short collateral is short_tk ($1 per token)
let collateral = ONE_TOKEN; // 1 short_tk = $1
let size_usd = 10 * fp; // $10 size (10x leverage on $1 collateral)
open_short_position(&w, collateral, size_usd);
// Verify position exists
let pos_key = gmx_keys::position_key(&w.env, &w.user, &w.market_tk, &w.short_tk, false);
assert!(
OHClient::new(&w.env, &w.ord_handler)
.get_position(&pos_key)
.is_some(),
"short position must exist before liquidation"
);
// Pump index price to $10 000 — short is deeply underwater
let pump_price = 10_000 * fp;
set_prices(&w, pump_price);
// Verify it's liquidatable
let is_liq = LiquidationHandlerClient::new(&w.env, &w.liq_handler).check_liquidatable(
&w.user,
&w.market_tk,
&w.short_tk,
&false,
);
assert!(
is_liq,
"short position must be liquidatable after price pump"
);
// Execute liquidation
LiquidationHandlerClient::new(&w.env, &w.liq_handler).liquidate_position(
&w.liq_keeper,
&w.user,
&w.market_tk,
&w.short_tk,
&false,
);
// Position key must be removed
assert!(
OHClient::new(&w.env, &w.ord_handler)
.get_position(&pos_key)
.is_none(),
"short position key must be removed after liquidation"
);
}
/// Liquidation of a healthy short position must revert.
#[test]
#[should_panic]
fn liquidate_healthy_short_reverts() {
let w = setup();
let fp = FLOAT_PRECISION;
let entry_price = 2_000 * fp;
set_prices(&w, entry_price);
// Very well-collateralised short
let collateral = ONE_TOKEN * 100; // 100 short_tk = $100
let size_usd = 10 * fp; // $10 size — 0.1x leverage
open_short_position(&w, collateral, size_usd);
// Price stays the same
set_prices(&w, entry_price);
// Must revert with NotLiquidatable
LiquidationHandlerClient::new(&w.env, &w.liq_handler).liquidate_position(
&w.liq_keeper,
&w.user,
&w.market_tk,
&w.short_tk,
&false,
);
}
// ── Issue #11: upgrade entrypoint tests ───────────────────────────────────
/// Admin auth passes on upgrade; panics at WASM lookup (not auth) in unit tests.
/// A compiled WASM binary is required for the host to accept the hash.
#[test]
#[should_panic]
fn upgrade_admin_succeeds() {
let w = setup(); // mock_all_auths is active — admin.require_auth() passes silently
// Panics at WASM lookup (not at auth) — proves auth gate is open for admin.
LiquidationHandlerClient::new(&w.env, &w.liq_handler)
.upgrade(&BytesN::from_array(&w.env, &[0u8; 32]));
}
/// Calling upgrade without the admin's authorisation must revert.
#[test]
#[should_panic]
fn upgrade_non_admin_reverts() {
// Fresh env — no mock_all_auths so require_auth() is not bypassed.
let env = Env::default();
let admin = Address::generate(&env);
let rs = Address::generate(&env);
let ds = Address::generate(&env);
let oracle = Address::generate(&env);
let oh = Address::generate(&env);
let liq = env.register(LiquidationHandler, ());
// Seed instance storage directly, bypassing initialize() auth.
env.as_contract(&liq, || {
env.storage()
.instance()
.set(&InstanceKey::Initialized, &true);
env.storage().instance().set(&InstanceKey::Admin, &admin);
env.storage().instance().set(&InstanceKey::RoleStore, &rs);
env.storage().instance().set(&InstanceKey::DataStore, &ds);