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
2089 lines (1841 loc) · 80.1 KB
/
Copy pathlib.rs
File metadata and controls
2089 lines (1841 loc) · 80.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
//! Reader — read-only view contract for aggregating protocol state.
//! Mirrors GMX's Reader.sol.
//!
//! Aggregates data across data_store, oracle, and position/market utils
//! into rich structs the frontend consumes without needing multiple calls.
//! All functions are view-only — no writes, no auth.
#![no_std]
#![allow(dependency_on_unit_never_type_fallback)]
use gmx_keys::{
account_deposit_list_key, account_order_list_key, account_position_list_key,
account_withdrawal_list_key, claimable_fee_amount_key, deposit_list_key,
funding_amount_per_size_key, funding_updated_at_key, keeper_heartbeat_timeout_key,
last_keeper_activity_key, market_index_token_key, market_long_token_key,
market_short_token_key, open_interest_key, order_list_key, position_key, position_list_key,
saved_funding_factor_per_second_key, withdrawal_list_key, DEFAULT_KEEPER_HEARTBEAT_TIMEOUT,
};
use gmx_market_utils::{get_open_interest_for_side, get_pool_value};
use gmx_math::{mul_div_wide, FLOAT_PRECISION, TOKEN_PRECISION};
use gmx_position_utils::{get_position_fees, get_position_pnl_usd, is_liquidatable};
use gmx_pricing_utils::{get_execution_price, get_position_price_impact};
use gmx_types::{
AdlCandidate, DepositProps, FundingAmountResult, FundingInfo, FundingRateInfo,
KeeperHeartbeatStatus, LiquidatablePosition, MarketProps, OrderProps, PoolValueInfo,
PositionFees, PositionInfo, PositionLeverage, PositionProps, PriceProps, ProtocolStats,
SwapEstimate, WithdrawalProps, PendingOrder,
};
use soroban_sdk::{
contract, contracterror, contractimpl, contracttype, panic_with_error, Address, BytesN, Env,
Vec,
};
// ─── Constants ────────────────────────────────────────────────────────────────
/// Upper bound on the number of markets `get_protocol_stats` will aggregate in a
/// single call (issue #251). Bounds the per-call instruction cost — each market
/// requires several cross-contract reads — so a large `markets` vec cannot push
/// the call past Soroban's budget. Callers with more markets must paginate by
/// invoking the view across multiple subsets and summing client-side.
const MAX_STATS_MARKETS: u32 = 20;
// ─── Storage keys ─────────────────────────────────────────────────────────────
#[contracttype]
enum InstanceKey {
Initialized,
Admin,
}
// ─── Errors ───────────────────────────────────────────────────────────────────
#[contracterror]
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
#[repr(u32)]
pub enum Error {
NotInitialized = 1,
AlreadyInitialized = 2,
Unauthorized = 3,
/// `get_protocol_stats` was passed more than `MAX_STATS_MARKETS` markets.
TooManyMarkets = 4,
}
// ─── External clients ─────────────────────────────────────────────────────────
#[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 get_address(env: Env, key: BytesN<32>) -> Option<Address>;
fn get_bytes32_set_count(env: Env, set_key: BytesN<32>) -> u32;
fn get_bytes32_set_at(env: Env, set_key: BytesN<32>, start: u32, end: u32) -> Vec<BytesN<32>>;
}
#[allow(dead_code)]
#[soroban_sdk::contractclient(name = "OracleClient")]
trait IOracle {
fn get_primary_price(env: Env, token: Address) -> PriceProps;
}
#[allow(dead_code)]
#[soroban_sdk::contractclient(name = "OrderHandlerClient")]
trait IOrderHandler {
fn bump_position_ttl(env: Env, caller: Address, key: BytesN<32>) -> bool;
fn get_position(env: Env, key: BytesN<32>) -> Option<PositionProps>;
fn get_order(env: Env, key: BytesN<32>) -> Option<OrderProps>;
}
#[soroban_sdk::contractclient(name = "MarketTokenClient")]
trait IMarketToken {
fn total_supply(env: Env) -> i128;
}
#[allow(dead_code)]
#[soroban_sdk::contractclient(name = "DepositHandlerClient")]
trait IDepositHandler {
fn get_deposit(env: Env, key: BytesN<32>) -> Option<DepositProps>;
}
#[allow(dead_code)]
#[soroban_sdk::contractclient(name = "WithdrawalHandlerClient")]
trait IWithdrawalHandler {
fn get_withdrawal(env: Env, key: BytesN<32>) -> Option<WithdrawalProps>;
}
// ─── Contract ─────────────────────────────────────────────────────────────────
#[contract]
pub struct Reader;
#[contractimpl]
impl Reader {
/// One-time setup — store the admin address.
pub fn initialize(env: Env, admin: 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);
}
/// 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);
}
// ── Market views ─────────────────────────────────────────────────────────
/// Load full MarketProps for a given market_token address from data_store.
pub fn get_market(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,
index_token,
long_token,
short_token,
}
}
/// Get the full pool value breakdown for a market at current oracle prices.
pub fn get_market_pool_value_info(
env: Env,
data_store: Address,
oracle: Address,
market_token: Address,
maximize: bool,
) -> PoolValueInfo {
let market = Self::get_market(env.clone(), data_store.clone(), market_token);
let oracle_client = OracleClient::new(&env, &oracle);
let long_price = oracle_client
.get_primary_price(&market.long_token)
.mid_price();
let short_price = oracle_client
.get_primary_price(&market.short_token)
.mid_price();
let index_price = oracle_client
.get_primary_price(&market.index_token)
.mid_price();
get_pool_value(
&env,
&data_store,
&market,
long_price,
short_price,
index_price,
maximize,
)
}
/// Issue #276: USD price per 1 market (GM) token, FLOAT_PRECISION scaled.
/// `maximize = true` uses oracle max prices (conservative for minting);
/// `maximize = false` uses oracle min prices (conservative for burning).
/// Zero-supply pools return a 1.00 USD seed price rather than panicking.
pub fn get_market_token_price(
env: Env,
data_store: Address,
oracle: Address,
market: Address,
maximize: bool,
) -> u128 {
let supply = MarketTokenClient::new(&env, &market).total_supply();
if supply <= 0 {
return FLOAT_PRECISION as u128; // seed price: 1.00 USD per GM token
}
let info = Self::get_market_pool_value_info(env.clone(), data_store, oracle, market, maximize);
// pool_value is USD at FLOAT_PRECISION; supply is GM tokens at TOKEN_PRECISION raw units.
// price_per_token (FLOAT_PRECISION USD) = pool_value × TOKEN_PRECISION / supply.
mul_div_wide(&env, info.pool_value.max(0), TOKEN_PRECISION, supply) as u128
}
/// Get open interest for both sides of a market.
/// Returns (long_oi_usd, short_oi_usd).
pub fn get_open_interest(env: Env, data_store: Address, market_token: Address) -> (i128, i128) {
let market = Self::get_market(env.clone(), data_store.clone(), market_token);
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;
(long_oi, short_oi)
}
/// Get the aggregate funding state for a market.
pub fn get_funding_info(env: Env, data_store: Address, market_token: Address) -> FundingInfo {
let market = Self::get_market(env.clone(), data_store.clone(), market_token.clone());
let ds = DataStoreClient::new(&env, &data_store);
let funding_factor_per_second =
ds.get_i128(&saved_funding_factor_per_second_key(&env, &market_token));
// Long side tracks funding in long_token collateral; short in short_token
let long_funding_amount_per_size = ds.get_i128(&funding_amount_per_size_key(
&env,
&market_token,
&market.long_token,
true,
));
let short_funding_amount_per_size = ds.get_i128(&funding_amount_per_size_key(
&env,
&market_token,
&market.short_token,
false,
));
FundingInfo {
funding_factor_per_second,
long_funding_amount_per_size,
short_funding_amount_per_size,
}
}
/// Aggregate protocol-wide statistics across the supplied markets (issue #251).
///
/// Returns total pool value (TVL), long/short open interest, and accumulated
/// (unclaimed) fees — all in USD at the current oracle prices — plus the
/// market count and the ledger the snapshot was taken at. Lets the frontend
/// fetch headline numbers in one call instead of N per-market round-trips.
///
/// Issue #207: per-hour funding rate view for the frontend.
///
/// For **historical** funding rates, use the off-chain event indexer: `execute_order`
/// emits a `FundingRateSnapshot` Soroban event (topic: `"fund_snap"`) after every
/// position order execution. Filter by topic and market address to reconstruct the
/// funding rate time-series. Historical data is not stored on-chain to avoid
/// Soroban storage cost at every position execution (issue #286).
pub fn get_funding_rate_info(
env: Env,
data_store: Address,
market_token: Address,
) -> FundingRateInfo {
let market = Self::get_market(env.clone(), data_store.clone(), market_token.clone());
let ds = DataStoreClient::new(&env, &data_store);
const LEDGERS_PER_HOUR: i128 = 720;
let factor_key = saved_funding_factor_per_second_key(&env, &market_token);
let funding_factor_per_second = ds.get_i128(&factor_key);
let long_funding_rate_per_hour = funding_factor_per_second.saturating_mul(LEDGERS_PER_HOUR);
let short_funding_rate_per_hour = long_funding_rate_per_hour.saturating_neg();
// Long side tracks funding in long_token collateral; short in short_token
// (issue #397 — these must match get_funding_info's key derivation).
let long_fnd_key =
funding_amount_per_size_key(&env, &market_token, &market.long_token, true);
let short_fnd_key =
funding_amount_per_size_key(&env, &market_token, &market.short_token, false);
let long_funding_amount_per_size = ds.get_i128(&long_fnd_key);
let short_funding_amount_per_size = ds.get_i128(&short_fnd_key);
let updated_at_key = funding_updated_at_key(&env, &market_token);
let funding_updated_at_ledger = ds.get_u128(&updated_at_key) as u64;
let long_oi_key = open_interest_key(&env, &market_token, &market.long_token, true);
let short_oi_key = open_interest_key(&env, &market_token, &market.short_token, false);
let long_open_interest_usd = ds.get_u128(&long_oi_key);
let short_open_interest_usd = ds.get_u128(&short_oi_key);
FundingRateInfo {
long_funding_rate_per_hour,
short_funding_rate_per_hour,
long_funding_amount_per_size,
short_funding_amount_per_size,
funding_updated_at_ledger,
long_open_interest_usd,
short_open_interest_usd,
}
}
/// View-only: reads `data_store` and `oracle`, writes nothing.
///
/// Panics with `TooManyMarkets` if `markets.len() > MAX_STATS_MARKETS`, which
/// bounds the per-call compute cost. An empty `markets` vec is valid and
/// returns all-zero stats (with `market_count = 0`). A market whose pool value
/// is zero simply contributes zero — no special-casing, no panic.
pub fn get_protocol_stats(
env: Env,
data_store: Address,
oracle: Address,
markets: Vec<Address>,
) -> ProtocolStats {
if markets.len() > MAX_STATS_MARKETS {
panic_with_error!(&env, Error::TooManyMarkets);
}
let ds = DataStoreClient::new(&env, &data_store);
let oracle_client = OracleClient::new(&env, &oracle);
let mut total_pool_value_usd: i128 = 0;
let mut total_long_open_interest_usd: i128 = 0;
let mut total_short_open_interest_usd: i128 = 0;
let mut total_accumulated_fees_usd: i128 = 0;
for i in 0..markets.len() {
let market_token = markets.get_unchecked(i);
let market = Self::get_market(env.clone(), data_store.clone(), market_token.clone());
let long_price = oracle_client.get_primary_price(&market.long_token);
let short_price = oracle_client.get_primary_price(&market.short_token);
let index_price = oracle_client.get_primary_price(&market.index_token);
// Pool value (TVL contribution). Use the conservative (minimized) pool
// value so headline TVL never overstates what LPs could withdraw.
let pool = get_pool_value(
&env,
&data_store,
&market,
long_price.mid_price(),
short_price.mid_price(),
index_price.mid_price(),
false,
);
total_pool_value_usd += pool.pool_value;
// Open interest is already tracked in USD (FLOAT_PRECISION).
total_long_open_interest_usd +=
get_open_interest_for_side(&env, &data_store, &market, true) as i128;
total_short_open_interest_usd +=
get_open_interest_for_side(&env, &data_store, &market, false) as i128;
// Unclaimed fees are stored as raw token amounts per (market, token);
// convert each side to USD with that token's oracle price.
let long_fee = ds.get_u128(&claimable_fee_amount_key(
&env,
&market_token,
&market.long_token,
)) as i128;
let short_fee = ds.get_u128(&claimable_fee_amount_key(
&env,
&market_token,
&market.short_token,
)) as i128;
total_accumulated_fees_usd +=
mul_div_wide(&env, long_fee, long_price.mid_price(), TOKEN_PRECISION);
total_accumulated_fees_usd +=
mul_div_wide(&env, short_fee, short_price.mid_price(), TOKEN_PRECISION);
}
ProtocolStats {
total_pool_value_usd,
total_long_open_interest_usd,
total_short_open_interest_usd,
total_accumulated_fees_usd,
market_count: markets.len(),
computed_at_ledger: env.ledger().sequence() as u64,
}
}
/// Read a keeper role's liveness status from data_store (issue #249).
///
/// View-only mirror of the heartbeat check so the frontend / monitoring can
/// surface stale keepers without calling into order_handler. Returns the
/// last-active ledger, the gap since then, and whether that gap exceeds the
/// role's configured heartbeat timeout (falling back to the 2880-ledger
/// default when unset). A role with no recorded activity reports
/// `last_active_ledger = 0` and is treated as stale.
pub fn check_keeper_heartbeat(
env: Env,
data_store: Address,
role: BytesN<32>,
) -> KeeperHeartbeatStatus {
let ds = DataStoreClient::new(&env, &data_store);
let last_active_ledger =
ds.get_u128(&last_keeper_activity_key(&env, &role)) as u64;
let current_ledger = env.ledger().sequence() as u64;
let ledgers_since_last_activity = current_ledger.saturating_sub(last_active_ledger);
let stored_timeout = ds.get_u128(&keeper_heartbeat_timeout_key(&env, &role));
let timeout = if stored_timeout == 0 {
DEFAULT_KEEPER_HEARTBEAT_TIMEOUT
} else {
stored_timeout as u64
};
KeeperHeartbeatStatus {
last_active_ledger,
ledgers_since_last_activity,
is_stale: ledgers_since_last_activity > timeout,
}
}
// ── Position views ────────────────────────────────────────────────────────
/// Get a single position enriched with PnL, fees, and liquidation price.
///
/// Reads position from the canonical location (order_handler storage) via cross-contract call.
/// This ensures all consumers (liquidation_handler, adl_handler, reader) agree on position state.
pub fn get_position_info(
env: Env,
data_store: Address,
oracle: Address,
order_handler: Address,
account: Address,
market: Address,
collateral_token: Address,
is_long: bool,
) -> Option<PositionInfo> {
// Read position from canonical location (order_handler storage)
let pk = position_key(&env, &account, &market, &collateral_token, is_long);
// Bump TTL on read so monitoring via Reader keeps positions alive.
OrderHandlerClient::new(&env, &order_handler).bump_position_ttl(&env.current_contract_address(), &pk);
let position: PositionProps =
match OrderHandlerClient::new(&env, &order_handler).get_position(&pk) {
Some(p) => p,
None => return None,
};
let market_props =
Self::get_market(env.clone(), data_store.clone(), position.market.clone());
let oracle_client = OracleClient::new(&env, &oracle);
let index_price = oracle_client.get_primary_price(&market_props.index_token);
let collateral_price = oracle_client
.get_primary_price(&position.collateral_token)
.mid_price();
// PnL for the full position size
let (pnl_usd, uncapped_pnl_usd) =
get_position_pnl_usd(&env, &position, &index_price, position.size_in_usd);
// Fees in collateral token units
let fees: PositionFees = get_position_fees(
&env,
&data_store,
&market_props,
&position,
collateral_price,
position.size_in_usd,
false,
);
// Convert fee amounts (collateral token raw) → USD (FLOAT_PRECISION)
let borrowing_fee_usd = mul_div_wide(
&env,
fees.borrowing_fee_amount,
collateral_price,
TOKEN_PRECISION,
);
let funding_fee_usd = mul_div_wide(
&env,
fees.funding_fee_amount,
collateral_price,
TOKEN_PRECISION,
);
let position_fee_usd = mul_div_wide(
&env,
fees.position_fee_amount,
collateral_price,
TOKEN_PRECISION,
);
// Approximate liquidation price:
// For a long: liq_price = (size_usd - collateral_usd + fees_usd) / size_in_tokens × TOKEN_PRECISION
// For a short: liq_price = (size_usd + collateral_usd - fees_usd) / size_in_tokens × TOKEN_PRECISION
let collateral_usd = mul_div_wide(
&env,
position.collateral_amount,
collateral_price,
TOKEN_PRECISION,
);
let total_fees_usd = borrowing_fee_usd + funding_fee_usd + position_fee_usd;
let liquidation_price = if position.size_in_tokens > 0 {
let numerator = if position.is_long {
position.size_in_usd - collateral_usd + total_fees_usd
} else {
position.size_in_usd + collateral_usd - total_fees_usd
};
if numerator > 0 {
mul_div_wide(&env, numerator, TOKEN_PRECISION, position.size_in_tokens)
} else {
0
}
} else {
0
};
// Issue #260: compute weighted average entry price from accumulated size_in_usd / size_in_tokens.
let avg_entry_price = if position.size_in_tokens > 0 {
mul_div_wide(&env, position.size_in_usd, TOKEN_PRECISION, position.size_in_tokens)
} else {
0
};
Some(PositionInfo {
position,
pnl_usd,
uncapped_pnl_usd,
borrowing_fee_usd,
funding_fee_usd,
position_fee_usd,
liquidation_price,
avg_entry_price,
})
}
/// Issue #275: read-only view of a position's pending (not-yet-settled) funding,
/// without mutating any state. Mirrors the exact math `settle_funding_fees`
/// (claimable side) and `get_position_fees` (owed side) apply during a real
/// decrease, so the returned amounts match what would actually be
/// credited/debited if the position were decreased right now.
pub fn get_claimable_funding_amount(
env: Env,
data_store: Address,
oracle: Address,
order_handler: Address,
account: Address,
market: Address,
collateral_token: Address,
is_long: bool,
) -> Option<FundingAmountResult> {
let pk = position_key(&env, &account, &market, &collateral_token, is_long);
let position: PositionProps =
OrderHandlerClient::new(&env, &order_handler).get_position(&pk)?;
let market_props = Self::get_market(env.clone(), data_store.clone(), position.market.clone());
let ds = DataStoreClient::new(&env, &data_store);
// Claimable side: same per-size delta settle_funding_fees computes, for both tokens.
let mut claimable = [0i128, 0i128]; // [long_token, short_token]
for (i, (tok, tracker)) in [
(&market_props.long_token, position.long_claim_fnd_per_size),
(&market_props.short_token, position.short_claim_fnd_per_size),
]
.into_iter()
.enumerate()
{
let fnd_key = funding_amount_per_size_key(&env, &market_props.market_token, tok, position.is_long);
let latest = ds.get_i128(&fnd_key);
let claimable_per_size = tracker - latest;
if claimable_per_size > 0 {
claimable[i] = mul_div_wide(&env, claimable_per_size, position.size_in_usd, FLOAT_PRECISION);
}
}
// Owed side: same funding_fee_amount get_position_fees computes on a real decrease,
// expressed in the position's own collateral token (long_token or short_token).
let oracle_client = OracleClient::new(&env, &oracle);
let collateral_price = oracle_client.get_primary_price(&position.collateral_token).mid_price();
let fees = get_position_fees(&env, &data_store, &market_props, &position, collateral_price, 0, false);
let mut long_token_amount = claimable[0];
let mut short_token_amount = claimable[1];
if position.collateral_token == market_props.long_token {
long_token_amount -= fees.funding_fee_amount;
} else if position.collateral_token == market_props.short_token {
short_token_amount -= fees.funding_fee_amount;
}
Some(FundingAmountResult {
long_token_amount,
short_token_amount,
at_ledger: env.ledger().sequence() as u64,
})
}
/// Compute the execution price a user would get for a given size and order direction.
///
/// Useful for the UI to preview slippage before placing an order.
pub fn get_execution_price_preview(
env: Env,
data_store: Address,
oracle: Address,
market_token: Address,
is_long: bool,
is_increase: bool,
size_delta_usd: i128,
) -> i128 {
let market = Self::get_market(env.clone(), data_store.clone(), market_token);
let oracle_client = OracleClient::new(&env, &oracle);
let index_price = oracle_client
.get_primary_price(&market.index_token)
.mid_price();
let impact_usd = get_position_price_impact(
&env,
&data_store,
&market,
is_long,
size_delta_usd,
is_increase,
index_price,
);
get_execution_price(
&env,
index_price,
size_delta_usd,
impact_usd,
is_long,
is_increase,
)
}
/// Return whether a position is currently liquidatable at oracle prices.
///
/// Reads position from the canonical location (order_handler storage) via cross-contract call.
pub fn is_position_liquidatable(
env: Env,
data_store: Address,
oracle: Address,
order_handler: Address,
account: Address,
market: Address,
collateral_token: Address,
is_long: bool,
) -> bool {
// Read position from canonical location (order_handler storage)
let pk = position_key(&env, &account, &market, &collateral_token, is_long);
OrderHandlerClient::new(&env, &order_handler).bump_position_ttl(&env.current_contract_address(), &pk);
let position: PositionProps =
match OrderHandlerClient::new(&env, &order_handler).get_position(&pk) {
Some(p) => p,
None => return false,
};
let market_props =
Self::get_market(env.clone(), data_store.clone(), position.market.clone());
let oracle_client = OracleClient::new(&env, &oracle);
let index_price = oracle_client.get_primary_price(&market_props.index_token);
let collateral_price = oracle_client
.get_primary_price(&position.collateral_token)
.mid_price();
is_liquidatable(
&env,
&data_store,
&position,
&market_props,
collateral_price,
&index_price,
)
}
/// Return a stored order by key, or None if not found.
pub fn get_order(env: Env, order_handler: Address, key: BytesN<32>) -> Option<OrderProps> {
OrderHandlerClient::new(&env, &order_handler).get_order(&key)
}
/// Return paginated orders for an account.
pub fn get_account_orders(
env: Env,
data_store: Address,
order_handler: Address,
account: Address,
page: u32,
page_size: u32,
) -> Vec<OrderProps> {
let ds = DataStoreClient::new(&env, &data_store);
let set_key = account_order_list_key(&env, &account);
if page == 0 || page_size == 0 {
return Vec::new(&env);
}
let start = (page - 1).saturating_mul(page_size);
let end = start.saturating_add(page_size);
let keys: Vec<BytesN<32>> = ds.get_bytes32_set_at(&set_key, &start, &end);
let mut out: Vec<OrderProps> = Vec::new(&env);
for i in 0..keys.len() {
let k = keys.get_unchecked(i);
if let Some(o) = OrderHandlerClient::new(&env, &order_handler).get_order(&k) {
out.push_back(o);
}
}
out
}
/// Return paginated pending orders for a given market.
pub fn get_pending_orders(
env: Env,
data_store: Address,
order_handler: Address,
market: Address,
offset: u32,
limit: u32,
) -> Vec<PendingOrder> {
let ds = DataStoreClient::new(&env, &data_store);
let set_key = order_list_key(&env);
let total_count = ds.get_bytes32_set_count(&set_key);
let mut matching_orders = Vec::new(&env);
let mut skipped = 0;
let keys = ds.get_bytes32_set_at(&set_key, &0, &total_count);
let oh_client = OrderHandlerClient::new(&env, &order_handler);
for i in 0..keys.len() {
let k = keys.get_unchecked(i);
if let Some(order) = oh_client.get_order(&k) {
if order.market == market {
if skipped < offset {
skipped += 1;
continue;
}
matching_orders.push_back(PendingOrder {
owner: order.account,
market: order.market.clone(),
order_type: order.order_type,
size_delta_usd: order.size_delta_usd,
execution_fee: order.execution_fee,
updated_at_time: order.updated_at_time,
is_long: order.is_long,
});
if matching_orders.len() >= limit {
break;
}
}
}
}
matching_orders
}
/// Get position info by canonical position key (BytesN<32>), returning enriched `PositionInfo`.
pub fn get_position_info_by_key(
env: Env,
data_store: Address,
oracle: Address,
order_handler: Address,
position_key: BytesN<32>,
) -> Option<PositionInfo> {
OrderHandlerClient::new(&env, &order_handler).bump_position_ttl(&env.current_contract_address(), &position_key);
let position: PositionProps =
match OrderHandlerClient::new(&env, &order_handler).get_position(&position_key) {
Some(p) => p,
None => return None,
};
let market_props =
Self::get_market(env.clone(), data_store.clone(), position.market.clone());
let oracle_client = OracleClient::new(&env, &oracle);
let index_price = oracle_client.get_primary_price(&market_props.index_token);
let collateral_price = oracle_client
.get_primary_price(&position.collateral_token)
.mid_price();
let (pnl_usd, uncapped_pnl_usd) =
get_position_pnl_usd(&env, &position, &index_price, position.size_in_usd);
let fees: PositionFees = get_position_fees(
&env,
&data_store,
&market_props,
&position,
collateral_price,
position.size_in_usd,
false,
);
let borrowing_fee_usd = mul_div_wide(
&env,
fees.borrowing_fee_amount,
collateral_price,
TOKEN_PRECISION,
);
let funding_fee_usd = mul_div_wide(
&env,
fees.funding_fee_amount,
collateral_price,
TOKEN_PRECISION,
);
let position_fee_usd = mul_div_wide(
&env,
fees.position_fee_amount,
collateral_price,
TOKEN_PRECISION,
);
let collateral_usd = mul_div_wide(
&env,
position.collateral_amount,
collateral_price,
TOKEN_PRECISION,
);
let total_fees_usd = borrowing_fee_usd + funding_fee_usd + position_fee_usd;
let liquidation_price = if position.size_in_tokens > 0 {
let numerator = if position.is_long {
position.size_in_usd - collateral_usd + total_fees_usd
} else {
position.size_in_usd + collateral_usd - total_fees_usd
};
if numerator > 0 {
mul_div_wide(&env, numerator, TOKEN_PRECISION, position.size_in_tokens)
} else {
0
}
} else {
0
};
// Issue #260: weighted average entry price.
let avg_entry_price = if position.size_in_tokens > 0 {
mul_div_wide(&env, position.size_in_usd, TOKEN_PRECISION, position.size_in_tokens)
} else {
0
};
Some(PositionInfo {
position,
pnl_usd,
uncapped_pnl_usd,
borrowing_fee_usd,
funding_fee_usd,
position_fee_usd,
liquidation_price,
avg_entry_price,
})
}
/// Get a deposit by key (delegates to deposit_handler).
pub fn get_deposit(
env: Env,
deposit_handler: Address,
key: BytesN<32>,
) -> Option<DepositProps> {
DepositHandlerClient::new(&env, &deposit_handler).get_deposit(&key)
}
/// Get a withdrawal by key (delegates to withdrawal_handler).
pub fn get_withdrawal(
env: Env,
withdrawal_handler: Address,
key: BytesN<32>,
) -> Option<WithdrawalProps> {
WithdrawalHandlerClient::new(&env, &withdrawal_handler).get_withdrawal(&key)
}
// ── Deposit key enumeration (issue #27) ──────────────────────────────────
/// Count of all pending deposit keys in DataStore.
pub fn get_deposit_count(env: Env, data_store: Address) -> u32 {
DataStoreClient::new(&env, &data_store).get_bytes32_set_count(&deposit_list_key(&env))
}
/// Paginated list of all deposit keys (raw BytesN<32>).
pub fn get_deposit_keys(
env: Env,
data_store: Address,
start: u32,
end: u32,
) -> Vec<BytesN<32>> {
DataStoreClient::new(&env, &data_store).get_bytes32_set_at(
&deposit_list_key(&env),
&start,
&end,
)
}
/// Count of pending deposit keys for a specific account.
pub fn get_account_deposit_count(env: Env, data_store: Address, account: Address) -> u32 {
DataStoreClient::new(&env, &data_store)
.get_bytes32_set_count(&account_deposit_list_key(&env, &account))
}
/// Paginated list of deposit keys for a specific account.
pub fn get_account_deposit_keys(
env: Env,
data_store: Address,
account: Address,
start: u32,
end: u32,
) -> Vec<BytesN<32>> {
DataStoreClient::new(&env, &data_store).get_bytes32_set_at(
&account_deposit_list_key(&env, &account),
&start,
&end,
)
}
// ── Withdrawal key enumeration (issue #24) ────────────────────────────────
/// Count of all pending withdrawal keys in DataStore.
pub fn get_withdrawal_count(env: Env, data_store: Address) -> u32 {
DataStoreClient::new(&env, &data_store).get_bytes32_set_count(&withdrawal_list_key(&env))
}
/// Paginated list of all withdrawal keys (raw BytesN<32>).
pub fn get_withdrawal_keys(
env: Env,
data_store: Address,
start: u32,
end: u32,
) -> Vec<BytesN<32>> {
DataStoreClient::new(&env, &data_store).get_bytes32_set_at(
&withdrawal_list_key(&env),
&start,
&end,
)
}
/// Count of pending withdrawal keys for a specific account.
pub fn get_account_withdrawal_count(env: Env, data_store: Address, account: Address) -> u32 {
DataStoreClient::new(&env, &data_store)
.get_bytes32_set_count(&account_withdrawal_list_key(&env, &account))
}
/// Paginated list of withdrawal keys for a specific account.
pub fn get_account_withdrawal_keys(
env: Env,
data_store: Address,
account: Address,
start: u32,
end: u32,
) -> Vec<BytesN<32>> {
DataStoreClient::new(&env, &data_store).get_bytes32_set_at(
&account_withdrawal_list_key(&env, &account),
&start,
&end,
)
}
// ── Order key enumeration (issue #25) ─────────────────────────────────────
/// Count of all pending order keys in DataStore.
pub fn get_order_count(env: Env, data_store: Address) -> u32 {
DataStoreClient::new(&env, &data_store).get_bytes32_set_count(&order_list_key(&env))
}
/// Paginated list of all order keys (raw BytesN<32>).
pub fn get_order_keys(env: Env, data_store: Address, start: u32, end: u32) -> Vec<BytesN<32>> {
DataStoreClient::new(&env, &data_store).get_bytes32_set_at(
&order_list_key(&env),
&start,
&end,
)
}
/// Count of pending order keys for a specific account.
pub fn get_account_order_count(env: Env, data_store: Address, account: Address) -> u32 {
DataStoreClient::new(&env, &data_store)
.get_bytes32_set_count(&account_order_list_key(&env, &account))
}
/// Paginated list of order keys for a specific account.
pub fn get_account_order_keys(
env: Env,
data_store: Address,
account: Address,
start: u32,
end: u32,
) -> Vec<BytesN<32>> {
DataStoreClient::new(&env, &data_store).get_bytes32_set_at(
&account_order_list_key(&env, &account),
&start,
&end,
)
}
/// Return paginated account positions as enriched `PositionInfo` entries.
pub fn get_account_positions(
env: Env,
data_store: Address,
oracle: Address,
order_handler: Address,
account: Address,
page: u32,
page_size: u32,
) -> Vec<PositionInfo> {
let ds = DataStoreClient::new(&env, &data_store);
let set_key = account_position_list_key(&env, &account);
if page == 0 || page_size == 0 {
return Vec::new(&env);
}