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
1475 lines (1304 loc) · 53.8 KB
/
Copy pathlib.rs
File metadata and controls
1475 lines (1304 loc) · 53.8 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
//! Pricing utilities — price impact and execution price for swaps and positions.
//! Mirrors GMX's SwapPricingUtils.sol and PositionPricingUtils.sol.
//!
//! Price impact formula (both swap and position):
//! initialDiff = |sideA_usd - sideB_usd|
//! nextDiff = |sideA_usd ± delta - sideB_usd ∓ delta|
//! if nextDiff < initialDiff → positive impact: factor × (initialDiff^exp - nextDiff^exp)
//! if nextDiff > initialDiff → negative impact: factor × (nextDiff^exp - initialDiff^exp)
//! Positive impact is capped by the available impact pool amount.
#![no_std]
#![allow(dependency_on_unit_never_type_fallback)]
use gmx_keys::{
position_impact_exponent_factor_key, position_impact_factor_key,
position_impact_pool_amount_key, swap_fee_factor_key, swap_impact_exponent_factor_key,
swap_impact_factor_key, swap_impact_pool_amount_key,
};
use gmx_market_utils::{
get_open_interest_for_side, get_pool_amount, get_position_impact_pool_amount,
get_swap_impact_pool_amount,
};
use gmx_math::{mul_div_wide, mul_div_wide_up, pow_factor, FLOAT_PRECISION, TOKEN_PRECISION};
use gmx_types::MarketProps;
use soroban_sdk::{Address, BytesN, Env};
#[allow(dead_code)]
#[soroban_sdk::contractclient(name = "DataStoreClient")]
trait IDataStore {
fn get_u128(env: Env, key: BytesN<32>) -> u128;
fn get_u128_batch(env: Env, keys: soroban_sdk::Vec<BytesN<32>>) -> soroban_sdk::Vec<u128>;
fn set_u128(env: Env, caller: Address, key: BytesN<32>, value: u128) -> u128;
fn apply_delta_to_u128(env: Env, caller: Address, key: BytesN<32>, delta: i128) -> u128;
}
// ─── Internal: core impact formula ───────────────────────────────────────────
/// Compute signed price impact USD given before/after imbalance values and factors.
///
/// next_diff < initial_diff → positive impact (caps at pool)
/// next_diff > initial_diff → negative impact
fn compute_impact_usd(
env: &Env,
initial_diff: i128,
next_diff: i128,
positive_factor: i128,
negative_factor: i128,
exponent: i128,
impact_pool_usd: i128,
) -> i128 {
if initial_diff == next_diff {
return 0;
}
if next_diff < initial_diff {
// Pool balance improves → positive impact for user
let initial_pow = pow_factor(env, initial_diff, exponent);
let next_pow = pow_factor(env, next_diff, exponent);
let raw = mul_div_wide(
env,
positive_factor,
initial_pow - next_pow,
FLOAT_PRECISION,
);
// Cap by available impact pool
raw.min(impact_pool_usd)
} else {
// Pool balance worsens → negative impact for user
let initial_pow = pow_factor(env, initial_diff, exponent);
let next_pow = pow_factor(env, next_diff, exponent);
let raw = mul_div_wide(
env,
negative_factor,
next_pow - initial_pow,
FLOAT_PRECISION,
);
-raw
}
}
// ─── USD → token conversion for signed price impact ──────────────────────────
/// Convert a signed USD price impact to token units, rounding correctly for
/// the sign: a positive impact (payout to the trader) floors, while a
/// negative impact (a charge) takes the ceiling of its magnitude before
/// re-applying the sign — mirroring how fee amounts always round up so the
/// protocol never under-collects.
fn convert_impact_usd_to_tokens(env: &Env, impact_usd: i128, token_price: i128) -> i128 {
if impact_usd >= 0 {
mul_div_wide(env, impact_usd, TOKEN_PRECISION, token_price)
} else {
-mul_div_wide_up(env, -impact_usd, TOKEN_PRECISION, token_price)
}
}
// ─── Swap price impact ────────────────────────────────────────────────────────
#[allow(clippy::too_many_arguments)]
pub fn get_swap_price_impact(
env: &Env,
data_store: &Address,
market: &MarketProps,
token_in: &Address,
token_out: &Address,
amount_in: i128,
price_in: i128,
price_out: i128,
) -> i128 {
let ds = DataStoreClient::new(env, data_store);
// Pool amounts in USD (FLOAT_PRECISION)
let pool_in = get_pool_amount(env, data_store, market, token_in) as i128;
let pool_out = get_pool_amount(env, data_store, market, token_out) as i128;
let pool_in_usd = mul_div_wide(env, pool_in, price_in, TOKEN_PRECISION);
let pool_out_usd = mul_div_wide(env, pool_out, price_out, TOKEN_PRECISION);
let amount_in_usd = mul_div_wide(env, amount_in, price_in, TOKEN_PRECISION);
let initial_diff = (pool_in_usd - pool_out_usd).abs();
let next_in_usd = pool_in_usd + amount_in_usd;
let next_out_usd = pool_out_usd - amount_in_usd;
let next_diff = (next_in_usd - next_out_usd).abs();
// #381: batch the three impact-factor reads into a single cross-contract call.
let impact_keys = soroban_sdk::vec![
env,
swap_impact_factor_key(env, &market.market_token, true),
swap_impact_factor_key(env, &market.market_token, false),
swap_impact_exponent_factor_key(env, &market.market_token),
];
let impact_batch = ds.get_u128_batch(&impact_keys);
let pos_factor = impact_batch.get(0).unwrap_or(0) as i128;
let neg_factor = impact_batch.get(1).unwrap_or(0) as i128;
let exponent = impact_batch.get(2).unwrap_or(0) as i128;
// Impact pool cap (in USD of token_out)
let pool_tokens = get_swap_impact_pool_amount(env, data_store, market, token_out) as i128;
let pool_usd = mul_div_wide(env, pool_tokens, price_out, TOKEN_PRECISION);
compute_impact_usd(
env,
initial_diff,
next_diff,
pos_factor,
neg_factor,
exponent,
pool_usd,
)
}
/// Apply the computed swap impact to the impact pool in data_store.
///
/// Positive impact reduces the pool (paid to user); negative adds to it.
/// Returns the impact amount in token units.
pub fn apply_swap_impact_value(
env: &Env,
data_store: &Address,
caller: &Address,
market: &MarketProps,
token: &Address,
token_price: i128,
impact_usd: i128,
) -> i128 {
if impact_usd == 0 || token_price == 0 {
return 0;
}
// Convert USD impact to token amount
let impact_amount = convert_impact_usd_to_tokens(env, impact_usd, token_price);
// Positive impact → paid from pool (reduce pool); negative → paid into pool (increase pool)
let delta = -impact_amount;
DataStoreClient::new(env, data_store).apply_delta_to_u128(
caller,
&swap_impact_pool_amount_key(env, &market.market_token, token),
&delta,
);
impact_amount
}
// ─── Swap output amount ───────────────────────────────────────────────────────
#[allow(clippy::too_many_arguments)]
pub fn get_swap_output_amount(
env: &Env,
data_store: &Address,
market: &MarketProps,
token_in: &Address,
token_out: &Address,
amount_in: i128,
price_in: i128,
price_out: i128,
for_positive_impact: bool,
) -> (i128, i128) {
if price_out == 0 {
return (0, 0);
}
// Raw output before fees (price conversion)
let amount_out_before_fees = mul_div_wide(env, amount_in, price_in, price_out);
// Swap fee — round up so the protocol never under-collects
let fee_factor = DataStoreClient::new(env, data_store).get_u128(&swap_fee_factor_key(
env,
&market.market_token,
for_positive_impact,
)) as i128;
let fee_amount = mul_div_wide_up(env, amount_out_before_fees, fee_factor, FLOAT_PRECISION);
// Price impact (in token_out units)
let impact_usd = get_swap_price_impact(
env, data_store, market, token_in, token_out, amount_in, price_in, price_out,
);
let impact_amount = if price_out > 0 {
convert_impact_usd_to_tokens(env, impact_usd, price_out)
} else {
0
};
let net_output = (amount_out_before_fees - fee_amount + impact_amount).max(0);
(net_output, fee_amount)
}
// ─── Position price impact ────────────────────────────────────────────────────
/// Compute price impact USD for opening/closing a position of size `size_delta_usd`.
///
/// Uses open interest imbalance as the "virtual balance" (instead of pool amounts).
pub fn get_position_price_impact(
env: &Env,
data_store: &Address,
market: &MarketProps,
is_long: bool,
size_delta_usd: i128,
is_increase: bool,
index_token_price: i128,
) -> i128 {
let ds = DataStoreClient::new(env, data_store);
let long_oi = get_open_interest_for_side(env, data_store, market, true) as i128;
let short_oi = get_open_interest_for_side(env, data_store, market, false) as i128;
let initial_diff = (long_oi - short_oi).abs();
let (next_long, next_short) = match (is_long, is_increase) {
(true, true) => (long_oi + size_delta_usd, short_oi),
(false, true) => (long_oi, short_oi + size_delta_usd),
(true, false) => ((long_oi - size_delta_usd).max(0), short_oi),
(false, false) => (long_oi, (short_oi - size_delta_usd).max(0)),
};
let next_diff = (next_long - next_short).abs();
// #381: batch the three impact-factor reads into a single cross-contract call.
let impact_keys = soroban_sdk::vec![
env,
position_impact_factor_key(env, &market.market_token, true),
position_impact_factor_key(env, &market.market_token, false),
position_impact_exponent_factor_key(env, &market.market_token),
];
let impact_batch = ds.get_u128_batch(&impact_keys);
let pos_factor = impact_batch.get(0).unwrap_or(0) as i128;
let neg_factor = impact_batch.get(1).unwrap_or(0) as i128;
let exponent = impact_batch.get(2).unwrap_or(0) as i128;
// Impact pool cap (in USD of index token)
let pool_tokens = get_position_impact_pool_amount(env, data_store, market) as i128;
let pool_usd = if index_token_price > 0 {
mul_div_wide(env, pool_tokens, index_token_price, TOKEN_PRECISION)
} else {
0
};
compute_impact_usd(
env,
initial_diff,
next_diff,
pos_factor,
neg_factor,
exponent,
pool_usd,
)
}
/// Apply position price impact to the impact pool.
///
/// Returns impact_amount in index token raw units.
pub fn apply_position_impact_value(
env: &Env,
data_store: &Address,
caller: &Address,
market: &MarketProps,
impact_usd: i128,
index_token_price: i128,
) -> i128 {
if impact_usd == 0 || index_token_price == 0 {
return 0;
}
let impact_amount = convert_impact_usd_to_tokens(env, impact_usd, index_token_price);
let delta = -impact_amount; // positive impact → pool shrinks; negative → pool grows
DataStoreClient::new(env, data_store).apply_delta_to_u128(
caller,
&position_impact_pool_amount_key(env, &market.market_token),
&delta,
);
impact_amount
}
// ─── Execution price ──────────────────────────────────────────────────────────
/// Compute the execution price for a position change after applying price impact.
///
/// Returns the adjusted price in FLOAT_PRECISION (USD per whole token).
pub fn get_execution_price(
env: &Env,
index_price: i128,
size_delta_usd: i128,
price_impact_usd: i128,
is_long: bool,
is_increase: bool,
) -> i128 {
if size_delta_usd == 0 || index_price == 0 {
return index_price;
}
// A cost (negative) price impact must raise the execution price on a "buy"
// (long-increase or short-decrease) but lower it on a "sell" (long-decrease
// or short-increase). Flip the sign on the sell side before folding the
// impact into size_delta_usd so the two scenarios move in opposite directions.
let is_buy = is_long == is_increase;
let signed_impact_usd = if is_buy {
price_impact_usd
} else {
-price_impact_usd
};
// Adjusted size after price impact
let adjusted_size = size_delta_usd + signed_impact_usd;
if adjusted_size <= 0 {
return index_price;
}
// Tokens you effectively get for adjusted_size at index_price
// adjusted_tokens (raw 7-decimal units)
let adjusted_tokens = mul_div_wide(env, adjusted_size, TOKEN_PRECISION, index_price);
if adjusted_tokens == 0 {
return index_price;
}
// execution_price = size_delta_usd (USD) / adjusted_tokens (raw) × TOKEN_PRECISION
// = size_delta_usd × TOKEN_PRECISION / adjusted_tokens → FLOAT_PRECISION per whole token
mul_div_wide(env, size_delta_usd, TOKEN_PRECISION, adjusted_tokens)
}
// ─── Tests — Issue #61: negative swap price impact accounting ─────────────────
//
// Verifies that when a swap worsens pool balance:
// • The impact pool delta equals the negative impact amount (pool grows).
// • The user's output is reduced by the same amount.
// • Multiple impact magnitudes are covered.
#[cfg(test)]
mod tests {
use super::*;
use data_store::{DataStore, DataStoreClient as DsClient};
use gmx_keys::roles;
use gmx_math::{mul_div_wide, FLOAT_PRECISION, TOKEN_PRECISION};
use role_store::{RoleStore, RoleStoreClient as RsClient};
use soroban_sdk::{testutils::Address as _, Env};
fn deploy_role_store(env: &Env, admin: &Address) -> Address {
let id = env.register(RoleStore, ());
RsClient::new(env, &id).initialize(admin);
id
}
fn deploy_data_store(env: &Env, admin: &Address, rs: &Address) -> Address {
let id = env.register(DataStore, ());
DsClient::new(env, &id).initialize(admin, rs);
id
}
fn setup(env: &Env) -> (Address, Address, Address, Address, Address, Address) {
let admin = Address::generate(env);
let rs = deploy_role_store(env, &admin);
let ds = deploy_data_store(env, &admin, &rs);
let rs_c = RsClient::new(env, &rs);
rs_c.grant_role(&admin, &admin, &roles::controller(env));
let market_token = Address::generate(env);
let long_token = Address::generate(env);
let short_token = Address::generate(env);
let _index_token = Address::generate(env);
(
admin,
ds,
market_token,
_index_token,
long_token,
short_token,
)
}
fn make_market(
market_token: &Address,
index_token: &Address,
long_token: &Address,
short_token: &Address,
) -> MarketProps {
MarketProps {
market_token: market_token.clone(),
index_token: index_token.clone(),
long_token: long_token.clone(),
short_token: short_token.clone(),
}
}
/// Seed pool amounts and impact factors in data_store.
fn seed_swap_market(
env: &Env,
ds: &Address,
caller: &Address,
market: &MarketProps,
long_pool: i128,
short_pool: i128,
neg_factor: i128, // FLOAT_PRECISION
pos_factor: i128, // FLOAT_PRECISION
exponent: i128, // FLOAT_PRECISION (1.0 = linear)
) {
let ds_c = DsClient::new(env, ds);
// Pool amounts (raw token units)
ds_c.set_u128(
caller,
&gmx_keys::pool_amount_key(env, &market.market_token, &market.long_token),
&(long_pool as u128),
);
ds_c.set_u128(
caller,
&gmx_keys::pool_amount_key(env, &market.market_token, &market.short_token),
&(short_pool as u128),
);
// Impact factors
ds_c.set_u128(
caller,
&gmx_keys::swap_impact_factor_key(env, &market.market_token, false),
&(neg_factor as u128),
);
ds_c.set_u128(
caller,
&gmx_keys::swap_impact_factor_key(env, &market.market_token, true),
&(pos_factor as u128),
);
ds_c.set_u128(
caller,
&gmx_keys::swap_impact_exponent_factor_key(env, &market.market_token),
&(exponent as u128),
);
}
// ── Issue #61: negative impact increases impact pool ──────────────────────
/// When a swap worsens pool balance (token_in side already larger),
/// the impact is negative, and the impact pool for token_out grows by
/// exactly the absolute impact amount.
#[test]
fn negative_swap_impact_increases_impact_pool() {
let env = Env::default();
env.mock_all_auths();
let (admin, ds, mt, it, lt, st) = setup(&env);
let market = make_market(&mt, &it, <, &st);
// Swapping long→short worsens the imbalance → negative impact
let price = FLOAT_PRECISION; // $1 per token
let long_pool = 2_000 * TOKEN_PRECISION;
let short_pool = 1_000 * TOKEN_PRECISION;
let neg_factor = FLOAT_PRECISION / 1000; // 0.1% per unit
let pos_factor = FLOAT_PRECISION / 2000;
let exponent = FLOAT_PRECISION; // linear (exponent = 1.0)
seed_swap_market(
&env, &ds, &admin, &market, long_pool, short_pool, neg_factor, pos_factor, exponent,
);
let amount_in = 100 * TOKEN_PRECISION; // swap 100 long tokens
// Compute impact
let impact_usd =
get_swap_price_impact(&env, &ds, &market, <, &st, amount_in, price, price);
// Impact must be negative (worsens balance)
assert!(
impact_usd < 0,
"impact must be negative when worsening pool balance, got {}",
impact_usd
);
// Record impact pool before
let pool_key = gmx_keys::swap_impact_pool_amount_key(&env, &mt, &st);
let pool_before = DsClient::new(&env, &ds).get_u128(&pool_key) as i128;
// Apply impact
let impact_amount =
apply_swap_impact_value(&env, &ds, &admin, &market, &st, price, impact_usd);
let pool_after = DsClient::new(&env, &ds).get_u128(&pool_key) as i128;
// Impact amount should be negative (user loses tokens)
assert!(
impact_amount < 0,
"impact_amount must be negative for negative impact"
);
// Pool must have grown by |impact_amount| (negative impact → pool grows)
let pool_delta = pool_after - pool_before;
assert_eq!(
pool_delta, -impact_amount,
"impact pool delta must equal |impact_amount|: pool_delta={}, impact_amount={}",
pool_delta, impact_amount
);
}
/// User output is reduced by the absolute impact amount when impact is negative.
#[test]
fn negative_swap_impact_reduces_user_output() {
let env = Env::default();
env.mock_all_auths();
let (admin, ds, mt, it, lt, st) = setup(&env);
let market = make_market(&mt, &it, <, &st);
let price = FLOAT_PRECISION;
let long_pool = 3_000 * TOKEN_PRECISION;
let short_pool = 500 * TOKEN_PRECISION;
let neg_factor = FLOAT_PRECISION / 500;
let pos_factor = FLOAT_PRECISION / 1000;
let exponent = FLOAT_PRECISION;
seed_swap_market(
&env, &ds, &admin, &market, long_pool, short_pool, neg_factor, pos_factor, exponent,
);
// Set swap fee factor to 0 so we isolate impact effect
DsClient::new(&env, &ds).set_u128(
&admin,
&gmx_keys::swap_fee_factor_key(&env, &mt, false),
&0u128,
);
DsClient::new(&env, &ds).set_u128(
&admin,
&gmx_keys::swap_fee_factor_key(&env, &mt, true),
&0u128,
);
let amount_in = 200 * TOKEN_PRECISION;
// Output without any impact: amount_in * price_in / price_out = amount_in (same price)
let baseline_output = amount_in; // price_in == price_out
let (net_output, _fee) = get_swap_output_amount(
&env, &ds, &market, <, &st, amount_in, price, price,
false, // for_positive_impact = false (negative impact scenario)
);
// Net output must be less than baseline (impact reduces output)
assert!(
net_output < baseline_output,
"net_output {} must be less than baseline {} when impact is negative",
net_output,
baseline_output
);
// The reduction must equal the absolute impact amount
let impact_usd =
get_swap_price_impact(&env, &ds, &market, <, &st, amount_in, price, price);
assert!(impact_usd < 0, "impact must be negative");
let impact_tokens = mul_div_wide(&env, impact_usd.abs(), TOKEN_PRECISION, price);
let reduction = baseline_output - net_output;
assert_eq!(
reduction, impact_tokens,
"output reduction {} must equal impact tokens {}",
reduction, impact_tokens
);
}
/// Multiple impact magnitudes: larger imbalance → larger negative impact.
#[test]
fn negative_impact_scales_with_imbalance_magnitude() {
let env = Env::default();
env.mock_all_auths();
let (admin, ds, mt, it, lt, st) = setup(&env);
let market = make_market(&mt, &it, <, &st);
let price = FLOAT_PRECISION;
let neg_factor = FLOAT_PRECISION / 1_000_000;
let pos_factor = FLOAT_PRECISION / 2_000_000;
let exponent = 2 * FLOAT_PRECISION;
// Small imbalance: long=1100, short=1000
seed_swap_market(
&env,
&ds,
&admin,
&market,
1_100 * TOKEN_PRECISION,
1_000 * TOKEN_PRECISION,
neg_factor,
pos_factor,
exponent,
);
let impact_small = get_swap_price_impact(
&env,
&ds,
&market,
<,
&st,
50 * TOKEN_PRECISION,
price,
price,
);
// Large imbalance: long=5000, short=1000
seed_swap_market(
&env,
&ds,
&admin,
&market,
5_000 * TOKEN_PRECISION,
1_000 * TOKEN_PRECISION,
neg_factor,
pos_factor,
exponent,
);
let impact_large = get_swap_price_impact(
&env,
&ds,
&market,
<,
&st,
50 * TOKEN_PRECISION,
price,
price,
);
// Both must be negative
assert!(impact_small < 0, "small imbalance impact must be negative");
assert!(impact_large < 0, "large imbalance impact must be negative");
// Larger imbalance → larger (more negative) impact
assert!(
impact_large < impact_small,
"larger imbalance must produce larger negative impact: large={}, small={}",
impact_large,
impact_small
);
}
// ── Issue #61: position price impact pool accounting ─────────────────────
// ── Issue #136: property tests for pricing_utils ─────────────────────────
/// Swap price impact is zero when the pool is perfectly balanced.
#[test]
fn property_swap_impact_zero_on_balanced_pool() {
let env = Env::default();
env.mock_all_auths();
let (admin, ds, mt, it, lt, st) = setup(&env);
let market = make_market(&mt, &it, <, &st);
let price = FLOAT_PRECISION;
let pool_size = 1_000 * TOKEN_PRECISION;
let neg_factor = FLOAT_PRECISION / 1_000;
let pos_factor = FLOAT_PRECISION / 2_000;
let exponent = FLOAT_PRECISION; // linear
// Perfectly balanced: long == short
seed_swap_market(
&env, &ds, &admin, &market, pool_size, pool_size, neg_factor, pos_factor, exponent,
);
// A balanced swap should have no price impact (initial_diff == 0)
// but any non-zero swap will cause imbalance. Check that the sign of
// the impact is correctly negative when swapping into the larger side.
let impact = get_swap_price_impact(
&env,
&ds,
&market,
<,
&st,
100 * TOKEN_PRECISION,
price,
price,
);
// With equal pools, swapping long→short worsens balance → negative impact
assert!(
impact <= 0,
"swapping into larger side on balanced pool must not be positive: {impact}"
);
}
/// Larger swap amounts produce larger magnitude negative price impact
/// (monotone in amount_in when worsening pool balance).
#[test]
fn property_swap_negative_impact_monotone_in_amount() {
let env = Env::default();
env.mock_all_auths();
let (admin, ds, mt, it, lt, st) = setup(&env);
let market = make_market(&mt, &it, <, &st);
let price = FLOAT_PRECISION;
let neg_factor = FLOAT_PRECISION / 1_000_000;
let pos_factor = FLOAT_PRECISION / 2_000_000;
let exponent = 2 * FLOAT_PRECISION; // quadratic: larger swaps hurt more
// Long pool >> short pool → swapping long→short worsens imbalance
seed_swap_market(
&env,
&ds,
&admin,
&market,
5_000 * TOKEN_PRECISION,
1_000 * TOKEN_PRECISION,
neg_factor,
pos_factor,
exponent,
);
let small_impact = get_swap_price_impact(
&env,
&ds,
&market,
<,
&st,
10 * TOKEN_PRECISION,
price,
price,
);
let large_impact = get_swap_price_impact(
&env,
&ds,
&market,
<,
&st,
500 * TOKEN_PRECISION,
price,
price,
);
assert!(
small_impact <= 0,
"small swap must have non-positive impact: {small_impact}"
);
assert!(
large_impact <= 0,
"large swap must have non-positive impact: {large_impact}"
);
assert!(
large_impact <= small_impact,
"larger swap must produce worse (more negative) impact: small={small_impact}, large={large_impact}"
);
}
/// Position price impact is zero when open interest is perfectly balanced.
#[test]
fn property_position_impact_zero_on_balanced_oi() {
let env = Env::default();
env.mock_all_auths();
let (admin, ds, mt, it, lt, st) = setup(&env);
let market = make_market(&mt, &it, <, &st);
let index_price = 2_000 * FLOAT_PRECISION;
let neg_factor = FLOAT_PRECISION / 1_000;
let pos_factor = FLOAT_PRECISION / 2_000;
let exponent = FLOAT_PRECISION;
let ds_c = DsClient::new(&env, &ds);
ds_c.set_u128(
&admin,
&gmx_keys::position_impact_factor_key(&env, &mt, false),
&(neg_factor as u128),
);
ds_c.set_u128(
&admin,
&gmx_keys::position_impact_factor_key(&env, &mt, true),
&(pos_factor as u128),
);
ds_c.set_u128(
&admin,
&gmx_keys::position_impact_exponent_factor_key(&env, &mt),
&(exponent as u128),
);
// Balanced OI: long == short → initial_diff == 0, opening more long makes it unbalanced
let balanced_oi = 5_000 * FLOAT_PRECISION as u128;
ds_c.set_u128(
&admin,
&gmx_keys::open_interest_key(&env, &mt, <, true),
&balanced_oi,
);
ds_c.set_u128(
&admin,
&gmx_keys::open_interest_key(&env, &mt, <, false),
&balanced_oi,
);
// Opening a long when balanced worsens balance → negative impact
let impact = get_position_price_impact(
&env,
&ds,
&market,
true,
1_000 * FLOAT_PRECISION,
true,
index_price,
);
assert!(
impact <= 0,
"opening long on balanced OI must not produce positive impact: {impact}"
);
// Opening a short on the same balanced market also worsens balance → negative
let impact_short = get_position_price_impact(
&env,
&ds,
&market,
false,
1_000 * FLOAT_PRECISION,
true,
index_price,
);
assert!(
impact_short <= 0,
"opening short on balanced OI must not produce positive impact: {impact_short}"
);
}
/// get_execution_price with zero price_impact returns the raw index price.
#[test]
fn property_execution_price_no_impact_equals_index() {
let env = Env::default();
let index_price = 2_000 * FLOAT_PRECISION;
let size_delta_usd = 5_000 * FLOAT_PRECISION;
let result = get_execution_price(&env, index_price, size_delta_usd, 0, true, true);
assert_eq!(
result, index_price,
"zero price impact must leave execution price unchanged"
);
}
/// Negative price impact raises the effective execution price for longs
/// (trader pays more per unit). The adjusted price > index_price.
#[test]
fn property_negative_impact_raises_execution_price_for_long() {
let env = Env::default();
let index_price = 2_000 * FLOAT_PRECISION;
let size_delta_usd = 10_000 * FLOAT_PRECISION;
let neg_impact = -(100 * FLOAT_PRECISION); // −$100 in protocol precision
let exec_price =
get_execution_price(&env, index_price, size_delta_usd, neg_impact, true, true);
assert!(
exec_price > index_price,
"negative impact must raise execution price for long: exec={exec_price}, index={index_price}"
);
}
// ── Issue #376: buy/sell sign flip for get_execution_price ────────────────
/// Long-decrease (a "sell") with a cost (negative) price impact must LOWER
/// the execution price below index_price — the opposite of a long-increase
/// ("buy"), so the acceptable_price floor a trader configured for a close
/// actually protects them.
#[test]
fn property_negative_impact_lowers_execution_price_for_long_decrease() {
let env = Env::default();
let index_price = 2_000 * FLOAT_PRECISION;
let size_delta_usd = 10_000 * FLOAT_PRECISION;
let neg_impact = -(100 * FLOAT_PRECISION);
// is_long = true, is_increase = false → sell scenario
let exec_price =
get_execution_price(&env, index_price, size_delta_usd, neg_impact, true, false);
assert!(
exec_price < index_price,
"negative impact must lower execution price for long decrease: exec={exec_price}, index={index_price}"
);
}
/// Short-increase (also a "sell") with a cost price impact must likewise
/// lower the execution price below index_price.
#[test]
fn property_negative_impact_lowers_execution_price_for_short_increase() {
let env = Env::default();
let index_price = 2_000 * FLOAT_PRECISION;
let size_delta_usd = 10_000 * FLOAT_PRECISION;
let neg_impact = -(100 * FLOAT_PRECISION);
// is_long = false, is_increase = true → sell scenario
let exec_price =
get_execution_price(&env, index_price, size_delta_usd, neg_impact, false, true);
assert!(
exec_price < index_price,
"negative impact must lower execution price for short increase: exec={exec_price}, index={index_price}"
);
}
/// Short-decrease (a "buy", mirroring long-increase) with a cost price
/// impact must RAISE the execution price above index_price.
#[test]
fn property_negative_impact_raises_execution_price_for_short_decrease() {
let env = Env::default();
let index_price = 2_000 * FLOAT_PRECISION;
let size_delta_usd = 10_000 * FLOAT_PRECISION;
let neg_impact = -(100 * FLOAT_PRECISION);
// is_long = false, is_increase = false → buy scenario
let exec_price =
get_execution_price(&env, index_price, size_delta_usd, neg_impact, false, false);
assert!(
exec_price > index_price,
"negative impact must raise execution price for short decrease: exec={exec_price}, index={index_price}"
);
}
/// apply_swap_impact_value with impact_usd = 0 returns 0 without mutating state.
#[test]
fn property_apply_swap_impact_zero_impact_is_noop() {
let env = Env::default();
env.mock_all_auths();
let (admin, ds, mt, it, lt, st) = setup(&env);
let market = make_market(&mt, &it, <, &st);
let pool_key = gmx_keys::swap_impact_pool_amount_key(&env, &mt, &st);
let before = DsClient::new(&env, &ds).get_u128(&pool_key);
let result = apply_swap_impact_value(&env, &ds, &admin, &market, &st, FLOAT_PRECISION, 0);
let after = DsClient::new(&env, &ds).get_u128(&pool_key);
assert_eq!(result, 0, "zero impact must return 0");
assert_eq!(before, after, "zero impact must not mutate impact pool");
}
// ── Issue #137: differential tests against reference GMX formulas ─────────
//
// Each test computes a reference value by hand and asserts the function
// matches it exactly, catching any formula drift.
/// Reference (SwapPricingUtils): execution price with zero price impact.
/// index_price = $2 000 (FP)
/// size_delta_usd = $10 000 (FP)
/// price_impact = 0
/// execution_price = index_price (no shift)
#[test]
fn differential_execution_price_zero_impact_equals_index() {
let env = Env::default();
let index_price = 2_000 * FLOAT_PRECISION;
let size_delta_usd = 10_000 * FLOAT_PRECISION;
let exec = get_execution_price(&env, index_price, size_delta_usd, 0, true, true);
assert_eq!(
exec, index_price,
"zero-impact execution price must equal index: {exec} != {index_price}"
);
}
/// Reference: negative price impact raises execution price for a long.
/// index_price = $2 000
/// size_delta_usd = $10 000
/// impact_usd = −$100 (user gets $9 900 worth of tokens for $10 000)
/// adjusted_tokens = $9 900 / $2 000 per token × TOKEN_PRECISION
/// exec_price = $10 000 / adjusted_tokens × TOKEN_PRECISION
/// = $10 000 / (9 900 / 2 000) ≈ $2 020.20…
/// → exec_price > index_price (trader pays more per token)
#[test]
fn differential_execution_price_negative_impact_raises_long_price() {
let env = Env::default();
let index_price = 2_000 * FLOAT_PRECISION;
let size_delta_usd = 10_000 * FLOAT_PRECISION;
let impact_usd = -(100 * FLOAT_PRECISION);
let exec = get_execution_price(&env, index_price, size_delta_usd, impact_usd, true, true);
// Reference: adjusted_size = size_delta_usd + impact_usd = $9_900
let adjusted_size = size_delta_usd + impact_usd;
let adjusted_tokens = mul_div_wide(&env, adjusted_size, TOKEN_PRECISION, index_price);
let expected_exec = mul_div_wide(&env, size_delta_usd, TOKEN_PRECISION, adjusted_tokens);
assert_eq!(
exec, expected_exec,
"execution price must match reference formula: exec={exec}, expected={expected_exec}"
);
assert!(
exec > index_price,
"negative impact must raise execution price: exec={exec}, index={index_price}"
);
}
/// Reference: get_swap_output_amount with no price impact and no fee.
/// amount_in = 100 tokens (TOKEN_PRECISION)
/// price_in = $2 000 (FP)
/// price_out = $1 (FP — stable)
/// fee = 0
/// raw_out = 100 tokens * $2000 / $1 = 200_000 tokens
/// (using TOKEN_PRECISION: 100 * 10^7 * 2000*FP / FP = 200_000 * 10^7)
#[test]