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
1331 lines (1175 loc) · 48.9 KB
/
Copy pathlib.rs
File metadata and controls
1331 lines (1175 loc) · 48.9 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
//! Position utilities — per-position PnL, fee calculation, validation, and liquidation check.
//! Mirrors GMX's PositionUtils.sol, PositionStoreUtils.sol, and related helpers.
#![no_std]
#![allow(dependency_on_unit_never_type_fallback)]
use gmx_keys::{
claimable_funding_amount_key, cumulative_borrowing_factor_key, funding_amount_per_size_key,
max_leverage_key, min_collateral_factor_key, position_fee_factor_key, position_key,
};
use gmx_market_utils::validate_open_interest;
use gmx_math::{mul_div_wide, mul_div_wide_up, FLOAT_PRECISION, TOKEN_PRECISION};
use gmx_types::{MarketProps, PositionFees, PositionProps, PriceProps};
use soroban_sdk::{Address, BytesN, Env};
// ─── Data-store client (same minimal interface used across libs) ───────────────
#[allow(dead_code)]
#[soroban_sdk::contractclient(name = "DataStoreClient")]
trait IDataStore {
fn get_u128(env: Env, key: BytesN<32>) -> u128;
fn get_i128(env: Env, key: BytesN<32>) -> i128;
fn set_u128(env: Env, caller: Address, key: BytesN<32>, value: u128) -> u128;
fn set_i128(env: Env, caller: Address, key: BytesN<32>, value: i128) -> i128;
fn apply_delta_to_u128(env: Env, caller: Address, key: BytesN<32>, delta: i128) -> u128;
fn apply_delta_to_i128(env: Env, caller: Address, key: BytesN<32>, delta: i128) -> i128;
}
// ─── PnL ─────────────────────────────────────────────────────────────────────
/// Unrealised PnL in USD (FLOAT_PRECISION) for a full or partial close.
///
/// `size_delta_usd` — the portion of the position being closed (= position.size_in_usd for full).
///
/// Returns (pnl_usd, uncapped_pnl_usd) — same value for now; capping happens in get_pool_value.
/// When prorating a loss (negative PnL), rounds the magnitude up so the trader pays the pool
/// the full amount owed (protocol-favoring direction). For profit (positive PnL), floors toward
/// zero (trader-favoring direction), already correct per GMX invariant.
pub fn get_position_pnl_usd(
env: &Env,
position: &PositionProps,
index_token_price: &PriceProps,
size_delta_usd: i128,
) -> (i128, i128) {
if position.size_in_usd == 0 || position.size_in_tokens == 0 {
return (0, 0);
}
// Pick the price that maximises PnL for the trader:
// Long: higher price = more profit → use max
// Short: lower price = more profit → use min
let price = index_token_price.pick_price_for_pnl(position.is_long, true);
// Current value of all position tokens in USD (FLOAT_PRECISION)
let position_value = mul_div_wide(env, position.size_in_tokens, price, TOKEN_PRECISION);
// Unrealised PnL for the full position
let total_pnl = if position.is_long {
position_value - position.size_in_usd
} else {
position.size_in_usd - position_value
};
// Scale to the slice being closed, rounding based on sign:
// Profit (total_pnl >= 0): use floor (mul_div_wide) → protocol favoring
// Loss (total_pnl < 0): round magnitude up → pool gets full amount owed
let pnl_usd = if total_pnl >= 0 {
mul_div_wide(env, total_pnl, size_delta_usd, position.size_in_usd)
} else {
// For negative PnL, negate, round up, then negate back
let magnitude_rounded_up =
mul_div_wide_up(env, -total_pnl, size_delta_usd, position.size_in_usd);
-magnitude_rounded_up
};
(pnl_usd, pnl_usd)
}
// ─── Fees ─────────────────────────────────────────────────────────────────────
/// Compute all fees owed by a position for a given size delta.
///
/// Returns `PositionFees` with each component in collateral token raw units.
pub fn get_position_fees(
env: &Env,
data_store: &Address,
market: &MarketProps,
position: &PositionProps,
collateral_token_price: i128, // FLOAT_PRECISION
size_delta_usd: i128,
for_positive_impact: bool,
) -> PositionFees {
let ds = DataStoreClient::new(env, data_store);
// 1. BORROWING FEE — round up so the protocol never under-collects
let cum_borrow_key =
cumulative_borrowing_factor_key(env, &market.market_token, position.is_long);
let cum_borrow_factor = ds.get_u128(&cum_borrow_key) as i128;
let borrow_delta = (cum_borrow_factor - position.borrowing_factor).max(0);
// fee = delta × size_in_tokens / FLOAT_PRECISION (round up → protocol favor)
let borrowing_fee_amount =
mul_div_wide_up(env, borrow_delta, position.size_in_tokens, FLOAT_PRECISION);
// 2. FUNDING FEE — round up so the protocol never under-collects
let funding_key = funding_amount_per_size_key(
env,
&market.market_token,
&position.collateral_token,
position.is_long,
);
let latest_funding = ds.get_i128(&funding_key);
let funding_delta = latest_funding - position.funding_fee_amount_per_size;
// If delta > 0: position owes funding; if <= 0: position is owed (claimable, fee = 0 here)
let funding_fee_amount = if funding_delta > 0 {
// fee in collateral tokens = delta × size_in_usd / FLOAT_PRECISION / collateral_price × TOKEN_PRECISION
// Each division rounds up to ensure the owed amount is never under-charged
let fee_usd = mul_div_wide_up(env, funding_delta, position.size_in_usd, FLOAT_PRECISION);
if collateral_token_price > 0 {
mul_div_wide_up(env, fee_usd, TOKEN_PRECISION, collateral_token_price)
} else {
0
}
} else {
0
};
// 3. POSITION FEE (opening/closing fee) — round up so the protocol never under-collects
let fee_factor_key = position_fee_factor_key(env, &market.market_token, for_positive_impact);
let fee_factor = ds.get_u128(&fee_factor_key) as i128;
let position_fee_usd = mul_div_wide_up(env, size_delta_usd, fee_factor, FLOAT_PRECISION);
let position_fee_amount = if collateral_token_price > 0 {
mul_div_wide_up(
env,
position_fee_usd,
TOKEN_PRECISION,
collateral_token_price,
)
} else {
0
};
let total_cost_amount = borrowing_fee_amount + funding_fee_amount + position_fee_amount;
PositionFees {
borrowing_fee_amount,
funding_fee_amount,
position_fee_amount,
total_cost_amount,
}
}
/// Settle accumulated funding: credit the claimable amount and update position's
/// per-size baseline so the next fee calculation starts clean.
pub fn settle_funding_fees(
env: &Env,
data_store: &Address,
caller: &Address,
market: &MarketProps,
position: &mut PositionProps,
) {
let ds = DataStoreClient::new(env, data_store);
// For each collateral token side, check if the position is owed funding (negative delta means owed)
for (collateral_token, tracker) in [
(&market.long_token, position.long_claim_fnd_per_size),
(&market.short_token, position.short_claim_fnd_per_size),
] {
let fnd_key = funding_amount_per_size_key(
env,
&market.market_token,
collateral_token,
position.is_long,
);
let latest = ds.get_i128(&fnd_key);
// Negative delta → position is owed funding from the other side
let claimable_per_size = tracker - latest; // positive if position is owed
if claimable_per_size > 0 {
// Round DOWN (floor): credit the position the floor amount so the pool
// never pays out more than it mathematically owes.
let claimable_amount = mul_div_wide(
env,
claimable_per_size,
position.size_in_usd,
FLOAT_PRECISION,
);
if claimable_amount > 0 {
let claim_key = claimable_funding_amount_key(
env,
&market.market_token,
collateral_token,
&position.account,
);
ds.apply_delta_to_u128(caller, &claim_key, &claimable_amount);
}
}
}
// Reset trackers to current values so there's no double-counting next time
let long_fnd_key = funding_amount_per_size_key(
env,
&market.market_token,
&market.long_token,
position.is_long,
);
let short_fnd_key = funding_amount_per_size_key(
env,
&market.market_token,
&market.short_token,
position.is_long,
);
position.long_claim_fnd_per_size = ds.get_i128(&long_fnd_key);
position.short_claim_fnd_per_size = ds.get_i128(&short_fnd_key);
// Also update the owed-funding tracker (for positions that PAY funding)
let owned_key = funding_amount_per_size_key(
env,
&market.market_token,
&position.collateral_token,
position.is_long,
);
position.funding_fee_amount_per_size = ds.get_i128(&owned_key);
}
// ─── Validation ───────────────────────────────────────────────────────────────
/// Validate that a position still meets leverage and collateral requirements.
/// Panics if any constraint is violated.
pub fn validate_position(
env: &Env,
data_store: &Address,
position: &PositionProps,
market: &MarketProps,
collateral_token_price: i128,
_index_token_price: &PriceProps,
) {
let ds = DataStoreClient::new(env, data_store);
// Collateral in USD
let collateral_usd = mul_div_wide(
env,
position.collateral_amount,
collateral_token_price,
TOKEN_PRECISION,
);
// 1. MIN COLLATERAL check
let min_col_key = min_collateral_factor_key(env, &market.market_token);
let min_collateral_factor = ds.get_u128(&min_col_key) as i128;
if min_collateral_factor > 0 {
let required_min = mul_div_wide(
env,
position.size_in_usd,
min_collateral_factor,
FLOAT_PRECISION,
);
if collateral_usd < required_min {
soroban_sdk::panic_with_error!(env, soroban_sdk::Error::from_contract_error(1u32));
}
}
// 2. MAX LEVERAGE check
let max_lev_key = max_leverage_key(env, &market.market_token);
let max_leverage = ds.get_u128(&max_lev_key) as i128;
if max_leverage > 0 && collateral_usd > 0 {
let effective_leverage =
mul_div_wide(env, position.size_in_usd, FLOAT_PRECISION, collateral_usd);
if effective_leverage > max_leverage {
soroban_sdk::panic_with_error!(env, soroban_sdk::Error::from_contract_error(2u32));
}
}
// 3. OPEN INTEREST check
if validate_open_interest(env, data_store, market, position.is_long).is_err() {
soroban_sdk::panic_with_error!(env, soroban_sdk::Error::from_contract_error(3u32));
}
}
/// Returns true if the position can be liquidated at current prices.
pub fn is_liquidatable(
env: &Env,
data_store: &Address,
position: &PositionProps,
market: &MarketProps,
collateral_token_price: i128,
index_token_price: &PriceProps,
) -> bool {
if position.size_in_usd == 0 {
return false;
}
// 1. All current fees (worst case: not for positive impact)
let fees = get_position_fees(
env,
data_store,
market,
position,
collateral_token_price,
position.size_in_usd,
false,
);
// 2. Unrealised PnL using price that MINIMISES profit (worst case for trader)
let worst_price = index_token_price.pick_price_for_pnl(position.is_long, false);
let worst_price_props = PriceProps {
min: worst_price,
max: worst_price,
};
let (pnl_usd, _) =
get_position_pnl_usd(env, position, &worst_price_props, position.size_in_usd);
// 3. Remaining collateral in USD after fees and PnL
let collateral_usd = mul_div_wide(
env,
position.collateral_amount,
collateral_token_price,
TOKEN_PRECISION,
);
let fees_usd = mul_div_wide(
env,
fees.total_cost_amount,
collateral_token_price,
TOKEN_PRECISION,
);
// net_collateral excludes PnL — used for the min_collateral_factor adequacy check.
// PnL should not mask a collateral shortfall: a profitable unrealised gain does
// not mean the deposited collateral is sufficient to absorb liquidation costs.
let net_collateral = collateral_usd - fees_usd;
let remaining = net_collateral + pnl_usd;
// 4. Min required collateral
let ds = DataStoreClient::new(env, data_store);
let min_col_key = min_collateral_factor_key(env, &market.market_token);
let min_collateral_factor = ds.get_u128(&min_col_key) as i128;
if min_collateral_factor == 0 {
// No limit configured — fall back to: remaining < 0
return remaining < 0;
}
let min_required = mul_div_wide(
env,
position.size_in_usd,
min_collateral_factor,
FLOAT_PRECISION,
);
// Fold PnL into the comparison so adverse index-price moves cannot hide insolvency.
remaining < min_required
}
// ─── Position key ─────────────────────────────────────────────────────────────
/// Compute the data_store key for a position.
pub fn get_position_key(
env: &Env,
account: &Address,
market_token: &Address,
collateral_token: &Address,
is_long: bool,
) -> BytesN<32> {
position_key(env, account, market_token, collateral_token, is_long)
}
// ─── Tests ────────────────────────────────────────────────────────────────────
#[cfg(test)]
mod tests {
use super::*;
use data_store::{DataStore, DataStoreClient as DsClient};
use gmx_keys::roles;
use gmx_math::{FLOAT_PRECISION, TOKEN_PRECISION};
use gmx_types::{MarketProps, PositionProps, PriceProps};
use role_store::{RoleStore, RoleStoreClient as RsClient};
use soroban_sdk::{testutils::Address as _, Env};
const ONE_TOKEN: i128 = 10_000_000;
const FP: i128 = FLOAT_PRECISION;
struct World {
env: Env,
admin: Address,
ds: Address,
market_tk: Address,
long_tk: Address,
short_tk: Address,
index_tk: Address,
}
fn setup() -> World {
let env = Env::default();
env.mock_all_auths();
let admin = Address::generate(&env);
let rs = env.register(RoleStore, ());
RsClient::new(&env, &rs).initialize(&admin);
RsClient::new(&env, &rs).grant_role(&admin, &admin, &roles::controller(&env));
let ds = env.register(DataStore, ());
DsClient::new(&env, &ds).initialize(&admin, &rs);
let market_tk = Address::generate(&env);
let long_tk = Address::generate(&env);
let short_tk = Address::generate(&env);
let index_tk = Address::generate(&env);
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,
);
World {
env,
admin,
ds,
market_tk,
long_tk,
short_tk,
index_tk,
}
}
fn make_market(w: &World) -> MarketProps {
// Issue #248: build via the shared constructor instead of a per-field literal.
MarketProps::new(&w.market_tk, &w.index_tk, &w.long_tk, &w.short_tk)
}
fn make_position(
w: &World,
size_usd: i128,
collateral: i128,
index_price: i128,
) -> PositionProps {
let size_in_tokens = gmx_math::mul_div_wide(&w.env, size_usd, TOKEN_PRECISION, index_price);
PositionProps {
account: w.admin.clone(),
market: w.market_tk.clone(),
collateral_token: w.long_tk.clone(),
size_in_usd: size_usd,
size_in_tokens,
collateral_amount: collateral,
pending_impact_amount: 0,
borrowing_factor: 0,
funding_fee_amount_per_size: 0,
long_claim_fnd_per_size: 0,
short_claim_fnd_per_size: 0,
increased_at_time: 1_000,
decreased_at_time: 0,
is_long: true,
}
}
// ── Task 1: get_position_fees ─────────────────────────────────────────────
/// With zero fee factors configured, all fee components are zero.
#[test]
fn position_fees_are_zero_when_factors_unset() {
let w = setup();
let market = make_market(&w);
let position = make_position(&w, 1_000 * FP, ONE_TOKEN * 10, 2_000 * FP);
let fees = get_position_fees(
&w.env,
&w.ds,
&market,
&position,
2_000 * FP,
1_000 * FP,
true,
);
assert_eq!(
fees.borrowing_fee_amount, 0,
"borrowing fee must be 0 with no factor"
);
assert_eq!(
fees.funding_fee_amount, 0,
"funding fee must be 0 with no delta"
);
assert_eq!(
fees.position_fee_amount, 0,
"position fee must be 0 with no factor"
);
assert_eq!(fees.total_cost_amount, 0);
}
/// Position fee matches the expected bps formula.
#[test]
fn position_fee_matches_bps_formula() {
let w = setup();
let fee_bps: i128 = 30; // 30 bps
let fee_factor = fee_bps * FP / 10_000;
let ds_c = DsClient::new(&w.env, &w.ds);
ds_c.set_u128(
&w.admin,
&gmx_keys::position_fee_factor_key(&w.env, &w.market_tk, true),
&(fee_factor as u128),
);
let market = make_market(&w);
let index_price = 2_000 * FP;
let size_delta = 1_000 * FP;
let position = make_position(&w, size_delta, ONE_TOKEN * 10, index_price);
let fees = get_position_fees(
&w.env,
&w.ds,
&market,
&position,
index_price,
size_delta,
true,
);
let fee_usd = gmx_math::mul_div_wide(&w.env, size_delta, fee_factor, FP);
let expected_fee_tok =
gmx_math::mul_div_wide(&w.env, fee_usd, TOKEN_PRECISION, index_price);
assert!(
fees.position_fee_amount > 0,
"position fee must be non-zero"
);
assert_eq!(
fees.position_fee_amount, expected_fee_tok,
"position fee must match formula"
);
}
/// Borrowing fee is proportional to the cumulative factor delta and position size in tokens.
#[test]
fn borrowing_fee_proportional_to_cum_factor_delta() {
let w = setup();
let ds_c = DsClient::new(&w.env, &w.ds);
// Seed a cumulative borrowing factor > position snapshot (0)
let cum_factor: i128 = FP / 1_000; // small factor
ds_c.set_u128(
&w.admin,
&gmx_keys::cumulative_borrowing_factor_key(&w.env, &w.market_tk, true),
&(cum_factor as u128),
);
let market = make_market(&w);
let position = make_position(&w, 1_000 * FP, ONE_TOKEN * 10, 2_000 * FP);
// position.borrowing_factor = 0, cum = cum_factor → delta = cum_factor
let fees = get_position_fees(
&w.env,
&w.ds,
&market,
&position,
2_000 * FP,
1_000 * FP,
true,
);
let expected = gmx_math::mul_div_wide(&w.env, cum_factor, position.size_in_tokens, FP);
assert_eq!(
fees.borrowing_fee_amount, expected,
"borrowing fee must match formula"
);
}
// ── Task 1: settle_funding_fees ───────────────────────────────────────────
/// settle_funding_fees credits claimable amount when position is owed funding.
#[test]
fn settle_funding_credits_claimable_when_owed() {
let w = setup();
let ds_c = DsClient::new(&w.env, &w.ds);
// Set global funding-per-size to negative: position (tracker=0) is owed funding
let fnd_key = gmx_keys::funding_amount_per_size_key(&w.env, &w.market_tk, &w.long_tk, true);
let funding_per_size: i128 = -(FP / 100_000); // small negative
ds_c.apply_delta_to_i128(&w.admin, &fnd_key, &funding_per_size);
let market = make_market(&w);
let mut pos = make_position(&w, 1_000 * FP, ONE_TOKEN * 10, 2_000 * FP);
// pos.long_claim_fnd_per_size = 0 > funding_per_size → claimable
settle_funding_fees(&w.env, &w.ds, &w.admin, &market, &mut pos);
let claim_key =
gmx_keys::claimable_funding_amount_key(&w.env, &w.market_tk, &w.long_tk, &w.admin);
let claimable = ds_c.get_u128(&claim_key);
assert!(
claimable > 0,
"claimable funding must be credited when position is owed funding"
);
}
/// After settle_funding_fees, the position's tracker is updated to the current global value.
#[test]
fn settle_funding_resets_tracker_to_current_global() {
let w = setup();
let ds_c = DsClient::new(&w.env, &w.ds);
let fnd_key = gmx_keys::funding_amount_per_size_key(&w.env, &w.market_tk, &w.long_tk, true);
let global_value: i128 = FP / 50_000;
ds_c.apply_delta_to_i128(&w.admin, &fnd_key, &global_value);
let market = make_market(&w);
let mut pos = make_position(&w, 1_000 * FP, ONE_TOKEN * 10, 2_000 * FP);
settle_funding_fees(&w.env, &w.ds, &w.admin, &market, &mut pos);
// After settlement the position's funding_fee_amount_per_size must equal the global
assert_eq!(
pos.funding_fee_amount_per_size, global_value,
"position tracker must be reset to current global after settlement"
);
}
// ── Issue #256: dominant OI side always pays the subordinate side ────────
/// Short-dominated market: a short position being decreased must be charged a
/// funding debit (funding_fee_amount > 0), never credited.
#[test]
fn get_position_fees_short_holder_pays_debit_when_shorts_dominate() {
let w = setup();
let ds_c = DsClient::new(&w.env, &w.ds);
// Shorts dominate → the short-side accumulator (short_token, is_long=false)
// increases, exactly as market_utils::update_funding_state computes it.
let fnd_key = gmx_keys::funding_amount_per_size_key(&w.env, &w.market_tk, &w.short_tk, false);
let funding_per_size: i128 = FP / 100_000;
ds_c.apply_delta_to_i128(&w.admin, &fnd_key, &funding_per_size);
let market = make_market(&w);
let mut position = make_position(&w, 1_000 * FP, ONE_TOKEN * 10, 2_000 * FP);
position.is_long = false;
position.collateral_token = w.short_tk.clone();
let fees = get_position_fees(&w.env, &w.ds, &market, &position, FP, 1_000 * FP, true);
assert!(
fees.funding_fee_amount > 0,
"short holder must be charged a funding debit when shorts dominate, got {}",
fees.funding_fee_amount
);
}
/// Long-dominated market: a long position being decreased must be charged a
/// funding debit (funding_fee_amount > 0), never credited.
#[test]
fn get_position_fees_long_holder_pays_debit_when_longs_dominate() {
let w = setup();
let ds_c = DsClient::new(&w.env, &w.ds);
// Longs dominate → the long-side accumulator (long_token, is_long=true) increases.
let fnd_key = gmx_keys::funding_amount_per_size_key(&w.env, &w.market_tk, &w.long_tk, true);
let funding_per_size: i128 = FP / 100_000;
ds_c.apply_delta_to_i128(&w.admin, &fnd_key, &funding_per_size);
let market = make_market(&w);
let position = make_position(&w, 1_000 * FP, ONE_TOKEN * 10, 2_000 * FP);
// default make_position is already is_long: true, collateral_token: long_tk
let fees = get_position_fees(&w.env, &w.ds, &market, &position, FP, 1_000 * FP, true);
assert!(
fees.funding_fee_amount > 0,
"long holder must be charged a funding debit when longs dominate, got {}",
fees.funding_fee_amount
);
}
// ── Issue #136: property tests for position_utils ─────────────────────────
/// get_position_pnl_usd returns 0 when the position has zero size.
#[test]
fn property_pnl_zero_for_zero_size_position() {
let w = setup();
let mut pos = make_position(&w, 0, 0, 2_000 * FP);
pos.size_in_tokens = 0;
let price_props = PriceProps {
min: 2_000 * FP,
max: 2_000 * FP,
};
let (pnl, _) = get_position_pnl_usd(&w.env, &pos, &price_props, 0);
assert_eq!(pnl, 0, "zero-size position must have zero PnL");
}
/// A long position has zero PnL when the current price equals the entry price.
#[test]
fn property_long_pnl_zero_at_entry_price() {
let w = setup();
let entry_price = 2_000 * FP;
let size_usd = 1_000 * FP;
let pos = make_position(&w, size_usd, ONE_TOKEN * 10, entry_price);
let price_props = PriceProps {
min: entry_price,
max: entry_price,
};
let (pnl, _) = get_position_pnl_usd(&w.env, &pos, &price_props, size_usd);
// pnl = tokens * price / TOKEN_PRECISION - size_in_usd
// = (size_usd / entry_price * TOKEN_PRECISION) * entry_price / TOKEN_PRECISION - size_usd
// ≈ 0 (up to rounding)
let tol = 1i128;
assert!(
pnl.abs() <= tol,
"long PnL must be ~0 at entry price; got {pnl}"
);
}
/// A long position has negative PnL when the price drops below entry.
#[test]
fn property_long_pnl_negative_when_price_falls() {
let w = setup();
let entry_price = 2_000 * FP;
let exit_price = 1_000 * FP; // halved
let size_usd = 1_000 * FP;
let pos = make_position(&w, size_usd, ONE_TOKEN * 10, entry_price);
let price_props = PriceProps {
min: exit_price,
max: exit_price,
};
let (pnl, _) = get_position_pnl_usd(&w.env, &pos, &price_props, size_usd);
assert!(
pnl < 0,
"long position must have negative PnL when price falls; got {pnl}"
);
}
/// A long position has positive PnL when the price rises above entry.
#[test]
fn property_long_pnl_positive_when_price_rises() {
let w = setup();
let entry_price = 2_000 * FP;
let exit_price = 4_000 * FP; // doubled
let size_usd = 1_000 * FP;
let pos = make_position(&w, size_usd, ONE_TOKEN * 10, entry_price);
let price_props = PriceProps {
min: exit_price,
max: exit_price,
};
let (pnl, _) = get_position_pnl_usd(&w.env, &pos, &price_props, size_usd);
assert!(
pnl > 0,
"long position must have positive PnL when price rises; got {pnl}"
);
}
/// All fee components are non-negative (no underflow into negative fees).
#[test]
fn property_position_fees_never_negative() {
let w = setup();
let ds_c = DsClient::new(&w.env, &w.ds);
// Seed non-zero fee factors
let fee_factor: i128 = FP / 1_000; // 0.1%
ds_c.set_u128(
&w.admin,
&gmx_keys::position_fee_factor_key(&w.env, &w.market_tk, true),
&(fee_factor as u128),
);
let cum_factor: i128 = FP / 500;
ds_c.set_u128(
&w.admin,
&gmx_keys::cumulative_borrowing_factor_key(&w.env, &w.market_tk, true),
&(cum_factor as u128),
);
let market = make_market(&w);
let position = make_position(&w, 1_000 * FP, ONE_TOKEN * 5, 2_000 * FP);
let fees = get_position_fees(
&w.env,
&w.ds,
&market,
&position,
2_000 * FP,
1_000 * FP,
true,
);
assert!(
fees.borrowing_fee_amount >= 0,
"borrowing fee must not be negative: {}",
fees.borrowing_fee_amount
);
assert!(
fees.funding_fee_amount >= 0,
"funding fee must not be negative: {}",
fees.funding_fee_amount
);
assert!(
fees.position_fee_amount >= 0,
"position fee must not be negative: {}",
fees.position_fee_amount
);
assert!(
fees.total_cost_amount >= 0,
"total cost must not be negative: {}",
fees.total_cost_amount
);
}
/// total_cost_amount == borrowing + funding + position fees (no hidden component).
#[test]
fn property_total_cost_is_sum_of_components() {
let w = setup();
let ds_c = DsClient::new(&w.env, &w.ds);
let fee_factor: i128 = FP / 2_000;
ds_c.set_u128(
&w.admin,
&gmx_keys::position_fee_factor_key(&w.env, &w.market_tk, true),
&(fee_factor as u128),
);
let market = make_market(&w);
let position = make_position(&w, 2_000 * FP, ONE_TOKEN * 8, 2_000 * FP);
let fees = get_position_fees(
&w.env,
&w.ds,
&market,
&position,
2_000 * FP,
1_000 * FP,
true,
);
assert_eq!(
fees.total_cost_amount,
fees.borrowing_fee_amount + fees.funding_fee_amount + fees.position_fee_amount,
"total_cost must equal sum of components"
);
}
/// Partial close PnL scales linearly with size_delta (property: proportionality).
/// Closing 50% of a position should yield 50% of the full PnL (within rounding).
#[test]
fn property_partial_close_pnl_proportional_to_size() {
let w = setup();
let entry_price = 2_000 * FP;
let exit_price = 3_000 * FP;
let size_usd = 1_000 * FP;
let pos = make_position(&w, size_usd, ONE_TOKEN * 10, entry_price);
let price_props = PriceProps {
min: exit_price,
max: exit_price,
};
let (full_pnl, _) = get_position_pnl_usd(&w.env, &pos, &price_props, size_usd);
let (half_pnl, _) = get_position_pnl_usd(&w.env, &pos, &price_props, size_usd / 2);
// half_pnl should be ~50% of full_pnl (within 1 unit rounding)
let expected_half = full_pnl / 2;
assert!(
(half_pnl - expected_half).abs() <= 1,
"partial close PnL must be proportional: full={full_pnl}, half={half_pnl}, expected_half={expected_half}"
);
}
/// is_liquidatable returns false for a well-collateralised position at entry price.
#[test]
fn property_healthy_position_is_not_liquidatable() {
let w = setup();
let ds_c = DsClient::new(&w.env, &w.ds);
let entry_p = 2_000 * FP;
let market = make_market(&w);
// Set min collateral factor (1%)
ds_c.set_u128(
&w.admin,
&gmx_keys::min_collateral_factor_key(&w.env, &w.market_tk),
&((FP / 100) as u128),
);
// Large collateral relative to size → very healthy
let position = make_position(&w, 1_000 * FP, ONE_TOKEN * 100, entry_p);
let price_props = PriceProps {
min: entry_p,
max: entry_p,
};
assert!(
!is_liquidatable(&w.env, &w.ds, &position, &market, entry_p, &price_props),
"well-collateralised position at entry price must not be liquidatable"
);
}
// ── Issue #83: min collateral factor edge-case tests ─────────────────────
//
// Done: Missing config key, zero value, and very high value each produce safe
// and documented behavior. Tests cover all three.
/// When min_collateral_factor_key is never set (DataStore returns 0 for any
/// unset key), is_liquidatable falls back to the `remaining < 0` check.
#[test]
fn is_liquidatable_missing_key_falls_back_to_remaining_check() {
let w = setup();
let market = make_market(&w);
let entry_p = 2_000 * FP;
// Deeply leveraged long: 1 token collateral, $10 000 notional
let position = make_position(&w, 10_000 * FP, ONE_TOKEN, entry_p);
// Price crashes 90% → remaining = collateral_usd + pnl < 0
let crash_price = 200 * FP;
let crash_props = PriceProps {
min: crash_price,
max: crash_price,
};
assert!(
is_liquidatable(&w.env, &w.ds, &position, &market, crash_price, &crash_props),
"leveraged long with crashed price and no factor configured must be liquidatable"
);
// Well-collateralised long at entry price → remaining > 0 → not liquidatable
let safe_position = make_position(&w, 1_000 * FP, ONE_TOKEN * 100, entry_p);
let entry_props = PriceProps {
min: entry_p,
max: entry_p,
};
assert!(
!is_liquidatable(
&w.env,
&w.ds,
&safe_position,
&market,
entry_p,
&entry_props
),
"well-collateralised position with no factor configured must not be liquidatable"
);
}
/// Explicitly setting min_collateral_factor to 0 produces the same behaviour as
/// never setting it — the code path is identical (DataStore returns 0 for both).
#[test]
fn is_liquidatable_zero_factor_explicit_same_as_missing() {
let w = setup();
let ds_c = DsClient::new(&w.env, &w.ds);
let market = make_market(&w);
let entry_p = 2_000 * FP;
ds_c.set_u128(
&w.admin,
&gmx_keys::min_collateral_factor_key(&w.env, &w.market_tk),
&0u128,
);
let position = make_position(&w, 10_000 * FP, ONE_TOKEN, entry_p);
let crash_price = 200 * FP;
let crash_props = PriceProps {
min: crash_price,
max: crash_price,
};
assert!(
is_liquidatable(&w.env, &w.ds, &position, &market, crash_price, &crash_props),
"factor=0 explicit must behave the same as missing key (remaining < 0)"
);
let safe_position = make_position(&w, 1_000 * FP, ONE_TOKEN * 100, entry_p);
let entry_props = PriceProps {
min: entry_p,
max: entry_p,
};
assert!(
!is_liquidatable(
&w.env,
&w.ds,
&safe_position,
&market,
entry_p,
&entry_props
),
"factor=0 explicit: healthy position must not be liquidatable"
);
}
/// A very high min_collateral_factor (100% = FLOAT_PRECISION) makes positions
/// with collateral_usd < size_in_usd liquidatable. The same position passes
/// with a low factor.
#[test]
fn is_liquidatable_very_high_factor_triggers_liquidation() {
let w = setup();
let ds_c = DsClient::new(&w.env, &w.ds);
let market = make_market(&w);
let price = 2_000 * FP;
let props = PriceProps {
min: price,
max: price,
};
// Position: $10 000 notional, 1 token collateral → collateral_usd = $2 000