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
4217 lines (3840 loc) · 165 KB
/
Copy pathlib.rs
File metadata and controls
4217 lines (3840 loc) · 165 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
//! Order handler — create, execute, cancel, update, and freeze orders.
//! Mirrors GMX's OrderHandler.sol.
//!
//! Supported order types (OrderType enum in gmx_types):
//! MarketSwap, LimitSwap → routed to swap_utils
//! MarketIncrease, LimitIncrease → routed to increase_position_utils
//! MarketDecrease, LimitDecrease,
//! StopLossDecrease, Liquidation → routed to decrease_position_utils
//!
//! Two-step lifecycle (same as deposit/withdrawal):
//! create_order → pulls collateral into order_vault, stores OrderProps
//! execute_order → keeper calls with fresh oracle prices, dispatches by type
//! cancel_order → refunds collateral from order_vault to account
//! update_order → modify trigger_price / acceptable_price / size before execution
//! freeze_order → mark order as frozen (keeper-side circuit breaker)
#![no_std]
#![allow(dependency_on_unit_never_type_fallback)]
use gmx_decrease_position_utils::{decrease_position, DecreasePositionParams};
use gmx_increase_position_utils::{increase_position, IncreasePositionParams};
use gmx_keys::{
account_order_list_key, keeper_heartbeat_timeout_key, last_keeper_activity_key,
liquidation_execution_fee_key, min_execution_fee_key,
market_index_token_key, market_long_token_key, market_short_token_key,
max_leverage_key, max_swap_path_length_key, order_key, order_list_key,
position_fee_factor_key, position_key,
open_interest_key,
saved_funding_factor_per_second_key,
fee_tier_position_fee_factor_key, fee_tier_volume_threshold_key,
trader_volume_key, trader_volume_window_start_key,
roles, DEFAULT_KEEPER_HEARTBEAT_TIMEOUT, is_market_paused_key,
};
use gmx_math::{mul_div_wide, FLOAT_PRECISION};
use gmx_swap_utils::{swap_with_path, MAX_SWAP_PATH_LENGTH};
pub use gmx_types::CreateOrderParams;
use gmx_types::PositionProps;
use gmx_types::{MarketProps, OrderProps, OrderType, PriceProps};
use soroban_sdk::{
contract, contracterror, contractevent, contractimpl, contracttype, panic_with_error,
symbol_short, Address, BytesN, Env,
};
// ─── TTL constants (#297) ─────────────────────────────────────────────────────
//
// Lazy bump: extend_ttl only fires when the remaining TTL falls below
// MIN_BUMP_THRESHOLD. Both values are in ledger sequences; at 5 s/ledger:
// PERSISTENT_BUMP_TARGET ≈ 30 days (518 400 ledgers)
// MIN_BUMP_THRESHOLD ≈ 15 days (259 200 ledgers)
//
// Only extend when current TTL < MIN_BUMP_THRESHOLD; target PERSISTENT_BUMP_TARGET.
// This halves unnecessary rent payments on busy markets (issue #297).
const PERSISTENT_BUMP_TARGET: u32 = 518_400;
const MIN_BUMP_THRESHOLD: u32 = 259_200;
// ─── Storage keys ─────────────────────────────────────────────────────────────
#[contracttype]
enum InstanceKey {
Initialized,
Admin,
RoleStore,
DataStore,
Oracle,
OrderVault,
ReferralStorage,
}
// ─── Errors ───────────────────────────────────────────────────────────────────
#[contracterror]
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
#[repr(u32)]
pub enum Error {
AlreadyInitialized = 1,
NotInitialized = 2,
Unauthorized = 3,
OrderNotFound = 4,
InvalidOrderType = 5,
UnsatisfiedTrigger = 6,
PriceTooHigh = 7,
PriceTooLow = 8,
OrderFrozen = 9,
/// Increase/swap orders require collateral to have been transferred to
/// order_vault (via exchange_router SendTokens) before calling create_order.
/// record_transfer_in returned zero, meaning no collateral arrived.
ZeroCollateral = 10,
UnauthorizedPositionManager = 11,
/// `flag_stale_keeper` was called but the role's last activity is still
/// within the configured heartbeat timeout (issue #249).
KeeperNotStale = 12,
/// Position size/collateral ratio exceeds configured maximum leverage.
MaxLeverageExceeded = 13,
/// `create_orders` received more than 5 orders in a single batch.
BatchSizeLimitExceeded = 14,
/// The target market is paused due to circuit breaker (issue #203).
MarketPaused = 15,
/// swap_path contains a repeated market address — would corrupt pool accounting (issue #232).
CyclicSwapPath = 16,
/// swap_path exceeds the maximum allowed number of hops (issue #300).
SwapPathTooLong = 17,
/// execution_fee is below the configured global minimum (issue #294).
InsufficientExecutionFee = 18,
/// create_order called with size_delta_usd = 0 on a position order (issue #269).
ZeroSizeDelta = 19,
/// execute_order called after the order's user-set expiry_ledger (issue #272).
/// The order is auto-cancelled and any collateral refunded to the user.
OrderExpired = 20,
/// create_orders batch contains more than one increase/swap leg funded in the
/// same collateral token (issue #454) — record_transfer_in's shared per-token
/// balance delta can only unambiguously attribute one leg per token per batch.
DuplicateCollateralTokenInBatch = 21,
/// execute_adl called while the market/side's PnL-to-pool-value ratio does
/// not exceed the configured ADL threshold (issue #417). Re-validated here,
/// not just in the adl_handler wrapper, so the real mutating entry point
/// can't be forced by a caller who bypasses adl_handler entirely.
AdlRequirementNotMet = 22,
/// execute_adl called against a position that is not currently profitable
/// (issue #417) — ADL may only partially close profitable positions.
AdlPositionNotProfitable = 23,
/// Position increase would push the market/side's open interest above the
/// configured `max_open_interest` cap (issue #450).
MaxOpenInterestExceeded = 24,
}
// ─── Position events (issue #205) ────────────────────────────────────────────
#[contracttype]
pub struct PositionOpenedEvent {
pub key: BytesN<32>,
pub account: Address,
pub market: Address,
pub size_in_usd: i128,
pub collateral_amount: i128,
pub is_long: bool,
pub avg_entry_price: i128,
}
#[contracttype]
pub struct PositionIncreasedEvent {
pub key: BytesN<32>,
pub account: Address,
pub market: Address,
pub delta_size_usd: i128,
pub delta_collateral: i128,
pub new_size_usd: i128,
pub avg_entry_price: i128,
}
#[contracttype]
pub struct PositionDecreasedEvent {
pub key: BytesN<32>,
pub account: Address,
pub market: Address,
pub delta_size_usd: i128,
pub pnl_usd: i128,
pub execution_price: i128,
}
#[contracttype]
pub struct PositionClosedEvent {
pub key: BytesN<32>,
pub account: Address,
pub market: Address,
pub pnl_usd: i128,
pub execution_price: i128,
}
#[contracttype]
pub struct PositionLiquidatedEvent {
pub key: BytesN<32>,
pub account: Address,
pub market: Address,
pub execution_price: i128,
pub remaining_collateral: i128,
/// Collateral paid to the liquidation keeper as its execution fee (issue #437).
pub keeper_execution_fee: i128,
/// Realised PnL of the closed position (issue #437).
pub pnl_usd: i128,
}
/// Result of `liquidate_position` returned to `liquidation_handler` (issue #437).
/// A named struct (ScMap-encoded, keyed by field name) rather than a positional
/// tuple, so a future reorder of the fields on either side fails to decode
/// instead of silently swapping values across the two independently-deployed
/// contracts.
#[contracttype]
pub struct LiquidatePositionResult {
pub execution_price: i128,
pub keeper_execution_fee: i128,
pub pnl_usd: i128,
}
// ─── Funding rate snapshot event (issue #286) ─────────────────────────────────
//
// Historical funding rates are not stored on-chain to avoid Soroban storage
// costs. Instead, a FundingRateSnapshot is emitted after every position order
// execution. Query history via a Soroban event indexer filtering on topic
// "fund_snap" and the market address in the event payload.
#[contracttype]
pub struct FundingRateSnapshot {
pub market: Address,
pub funding_factor_per_second: i128,
pub long_open_interest: u128,
pub short_open_interest: u128,
pub timestamp: u64,
}
// ─── External contract clients ────────────────────────────────────────────────
#[allow(dead_code)]
#[soroban_sdk::contractclient(name = "RoleStoreClient")]
trait IRoleStore {
fn has_role(env: Env, account: Address, role: BytesN<32>) -> bool;
}
#[allow(dead_code)]
#[soroban_sdk::contractclient(name = "DataStoreClient")]
trait IDataStore {
fn get_u128(env: Env, key: BytesN<32>) -> u128;
/// Cache-first read for rarely-changing market config (issue #299).
fn get_u128_cached(env: Env, key: BytesN<32>) -> u128;
fn 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;
fn get_i128(env: Env, key: BytesN<32>) -> i128;
fn get_position_manager(env: Env, owner: Address, market: Address) -> Option<Address>;
fn increment_nonce(env: Env, caller: Address) -> u64;
fn get_address(env: Env, key: BytesN<32>) -> Option<Address>;
fn add_bytes32_to_set(env: Env, caller: Address, set_key: BytesN<32>, value: BytesN<32>);
fn remove_bytes32_from_set(env: Env, caller: Address, set_key: BytesN<32>, value: BytesN<32>);
fn contains_bytes32(env: Env, set_key: BytesN<32>, value: BytesN<32>) -> bool;
fn set_address(env: Env, caller: Address, key: BytesN<32>, value: Address) -> Address;
fn get_bool(env: Env, key: BytesN<32>) -> bool;
fn get_min_execution_fee(env: Env) -> u128;
}
#[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 = "OrderVaultClient")]
trait IOrderVault {
fn record_transfer_in(env: Env, token: Address) -> i128;
fn transfer_out(env: Env, caller: Address, token: Address, receiver: Address, amount: i128);
}
#[allow(dead_code)]
#[soroban_sdk::contractclient(name = "MarketTokenClient")]
trait IMarketToken {
fn withdraw_from_pool(
env: Env,
caller: Address,
pool_token: Address,
receiver: Address,
amount: i128,
);
}
#[allow(dead_code)]
#[soroban_sdk::contractclient(name = "ReferralStorageClient")]
trait IReferralStorage {
fn get_trader_referrer(env: Env, trader: Address) -> Option<Address>;
fn increment_referrer_volume(env: Env, caller: Address, referrer: Address, volume_usd: u128);
}
// ─── Position storage key (must match increase/decrease position utils) ───────
/// Positions are stored in this contract's persistent storage under this key.
/// The #[contracttype] XDR encoding must match the one in increase/decrease_position_utils.
#[contracttype]
pub enum PositionStorageKey {
Position(BytesN<32>),
}
// ─── Order-frozen flag (stored alongside OrderProps) ──────────────────────────
#[contracttype]
pub enum OrderStorageKey {
Order(BytesN<32>),
OrderFrozen(BytesN<32>),
/// Per-order ledger-sequence expiry set by the user at creation time (issue #272).
OrderExpiry(BytesN<32>),
}
// OrderProps are stored in this contract's own persistent storage (not DataStore)
// because DataStore supports only primitive/set types, not arbitrary structs.
// DataStore holds only the index sets (order_list_key, account_order_list_key)
// for enumeration. This matches the deposit and withdrawal handler patterns (issue #25).
// ─── Events ───────────────────────────────────────────────────────────────────
/// Emitted when a keeper role is found stale (issue #249): the gap between the
/// current ledger and the role's last recorded activity has exceeded the
/// configured heartbeat timeout. Signals the admin that the keeper has gone
/// silent and its role can be revoked.
#[contractevent(topics = ["kpr_stale"])]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct KeeperHeartbeatMissed {
pub role: BytesN<32>,
pub keeper: Address,
pub last_ledger: u64,
pub current_ledger: u64,
}
// ─── Contract ─────────────────────────────────────────────────────────────────
#[contract]
pub struct OrderHandler;
#[contractimpl]
impl OrderHandler {
/// One-time setup.
pub fn initialize(
env: Env,
admin: Address,
role_store: Address,
data_store: Address,
oracle: Address,
order_vault: Address,
) {
admin.require_auth();
if env.storage().instance().has(&InstanceKey::Initialized) {
panic_with_error!(&env, Error::AlreadyInitialized);
}
env.storage()
.instance()
.set(&InstanceKey::Initialized, &true);
env.storage().instance().set(&InstanceKey::Admin, &admin);
env.storage()
.instance()
.set(&InstanceKey::RoleStore, &role_store);
env.storage()
.instance()
.set(&InstanceKey::DataStore, &data_store);
env.storage().instance().set(&InstanceKey::Oracle, &oracle);
env.storage()
.instance()
.set(&InstanceKey::OrderVault, &order_vault);
}
/// Upgrade the contract wasm. Only the stored admin may call this.
///
/// Storage layout (InstanceKey and PositionStorageKey / OrderStorageKey) must not
/// change between versions — existing persistent entries remain readable after upgrade.
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);
}
pub fn update_oracle(env: Env, caller: Address, new_oracle: Address) {
caller.require_auth();
let admin: Address = env
.storage()
.instance()
.get(&InstanceKey::Admin)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
if caller != admin {
panic_with_error!(&env, Error::Unauthorized);
}
env.storage().instance().set(&InstanceKey::Oracle, &new_oracle);
}
/// Admin-configurable heartbeat timeout for a keeper `role`, in ledgers
/// (issue #249). When the gap since the role's last activity exceeds this,
/// the keeper is considered stale. Unset roles use
/// `DEFAULT_KEEPER_HEARTBEAT_TIMEOUT` (2880 ledgers, ~4h).
pub fn set_keeper_heartbeat_timeout(
env: Env,
caller: Address,
role: BytesN<32>,
timeout_ledgers: u64,
) {
caller.require_auth();
let admin: Address = env
.storage()
.instance()
.get(&InstanceKey::Admin)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
if caller != admin {
panic_with_error!(&env, Error::Unauthorized);
}
let data_store: Address = env
.storage()
.instance()
.get(&InstanceKey::DataStore)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
let handler = env.current_contract_address();
DataStoreClient::new(&env, &data_store).set_u128(
&handler,
&keeper_heartbeat_timeout_key(&env, &role),
&(timeout_ledgers as u128),
);
}
/// Read a keeper role's liveness status from data_store (issue #249).
///
/// View-only. Returns the last-active ledger, the gap since then, and whether
/// that gap has exceeded the configured heartbeat timeout. A role that has
/// never recorded activity reports `last_active_ledger = 0` and is treated as
/// stale (its full lifetime exceeds any timeout).
pub fn check_keeper_heartbeat(
env: Env,
data_store: Address,
role: BytesN<32>,
) -> gmx_types::KeeperHeartbeatStatus {
let last_active_ledger = DataStoreClient::new(&env, &data_store)
.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 timeout = keeper_heartbeat_timeout(&env, &data_store, &role);
let is_stale = ledgers_since_last_activity > timeout;
gmx_types::KeeperHeartbeatStatus {
last_active_ledger,
ledgers_since_last_activity,
is_stale,
}
}
/// Flag a keeper as stale (issue #249). Admin-gated.
///
/// Verifies the `role`'s heartbeat has lapsed and emits `KeeperHeartbeatMissed`
/// so the staleness is recorded on-chain. The admin can then revoke the
/// keeper's role via `role_store::revoke_role` — which has no timelock, so the
/// replacement can be wired immediately. Panics with `KeeperNotStale` if the
/// role is still within its heartbeat window, preventing premature flagging.
pub fn flag_stale_keeper(env: Env, caller: Address, keeper: Address, role: BytesN<32>) {
caller.require_auth();
let admin: Address = env
.storage()
.instance()
.get(&InstanceKey::Admin)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
if caller != admin {
panic_with_error!(&env, Error::Unauthorized);
}
let data_store: Address = env
.storage()
.instance()
.get(&InstanceKey::DataStore)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
let status = Self::check_keeper_heartbeat(env.clone(), data_store.clone(), role.clone());
if !status.is_stale {
panic_with_error!(&env, Error::KeeperNotStale);
}
env.events().publish_event(&KeeperHeartbeatMissed {
role,
keeper,
last_ledger: status.last_active_ledger,
current_ledger: env.ledger().sequence() as u64,
});
}
/// Register the referral_storage contract address (admin only — issue #217).
/// Once set, execute_order calls increment_referrer_volume after each trade.
pub fn set_referral_storage(env: Env, caller: Address, referral_storage: Address) {
caller.require_auth();
let admin: Address = env
.storage()
.instance()
.get(&InstanceKey::Admin)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
if caller != admin {
panic_with_error!(&env, Error::Unauthorized);
}
env.storage()
.instance()
.set(&InstanceKey::ReferralStorage, &referral_storage);
}
/// Bump the TTL of a stored position by rewriting it to persistent storage.
/// Allows reader/view contracts to extend the lifetime of positions they access.
pub fn bump_position_ttl(env: Env, caller: Address, key: BytesN<32>) -> bool {
caller.require_auth();
let pos_key = PositionStorageKey::Position(key.clone());
match env.storage().persistent().get::<PositionStorageKey, PositionProps>(&pos_key) {
Some(p) => {
env.storage().persistent().set(&pos_key, &p);
true
}
None => false,
}
}
/// Create up to 5 orders atomically in a single call (issue #219).
///
/// All orders are created or none are (Soroban atomicity). For increase/swap orders,
/// the caller must pre-fund the order_vault via SendTokens before calling this.
/// `record_transfer_in` is called per increase/swap order to snapshot the delta.
///
/// At most one increase/swap leg per distinct `initial_collateral_token` is
/// supported per batch (issue #454): `record_transfer_in`'s balance delta is a
/// single running counter per token, so two legs sharing a token cannot be
/// unambiguously attributed. A batch violating this reverts up front with
/// `DuplicateCollateralTokenInBatch` instead of a confusing `ZeroCollateral`
/// panic partway through processing.
///
/// Returns the list of created order keys in the same order as `requests`.
pub fn create_orders(
env: Env,
caller: Address,
requests: soroban_sdk::Vec<CreateOrderParams>,
) -> soroban_sdk::Vec<BytesN<32>> {
caller.require_auth();
if requests.len() > 5 {
panic_with_error!(&env, Error::BatchSizeLimitExceeded);
}
let data_store: Address = env
.storage()
.instance()
.get(&InstanceKey::DataStore)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
let order_vault: Address = env
.storage()
.instance()
.get(&InstanceKey::OrderVault)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
let handler = env.current_contract_address();
let ds = DataStoreClient::new(&env, &data_store);
let vault_client = OrderVaultClient::new(&env, &order_vault);
let mut keys: soroban_sdk::Vec<BytesN<32>> = soroban_sdk::Vec::new(&env);
let len = requests.len();
// Issue #454: at most one increase/swap leg per distinct collateral token is
// supported per batch — record_transfer_in's shared per-token balance delta
// cannot unambiguously attribute funds across two legs using the same token,
// and the second such leg would otherwise see a non-positive delta and panic
// with a confusing ZeroCollateral rather than a clear, dedicated error.
{
let mut seen_tokens: soroban_sdk::Vec<Address> = soroban_sdk::Vec::new(&env);
let mut j = 0u32;
while j < len {
let p = requests.get_unchecked(j);
let is_incr_or_swap = matches!(
p.order_type,
OrderType::MarketIncrease
| OrderType::LimitIncrease
| OrderType::StopIncrease
| OrderType::MarketSwap
| OrderType::LimitSwap
);
if is_incr_or_swap {
if seen_tokens.contains(&p.initial_collateral_token) {
panic_with_error!(&env, Error::DuplicateCollateralTokenInBatch);
}
seen_tokens.push_back(p.initial_collateral_token.clone());
}
j += 1;
}
}
// Issue #300: read max path length once for the entire batch.
let raw_max = ds.get_u128(&gmx_keys::max_swap_path_length_key(&env)) as usize;
let max_swap_len = if raw_max == 0 { MAX_SWAP_PATH_LENGTH } else { raw_max };
let mut i = 0u32;
while i < len {
let params = requests.get_unchecked(i);
// Issue #300: enforce max path length at creation time.
if params.swap_path.len() as usize > max_swap_len {
panic_with_error!(&env, Error::SwapPathTooLong);
}
let is_increase_or_swap = matches!(
params.order_type,
OrderType::MarketIncrease
| OrderType::LimitIncrease
| OrderType::StopIncrease
| OrderType::MarketSwap
| OrderType::LimitSwap
);
let collateral_delta_amount = if is_increase_or_swap {
let received = vault_client.record_transfer_in(¶ms.initial_collateral_token);
if received <= 0 {
panic_with_error!(&env, Error::ZeroCollateral);
}
received
} else {
params.collateral_delta_amount
};
let nonce = ds.increment_nonce(&handler);
let key = order_key(&env, nonce);
let order = OrderProps {
account: caller.clone(),
receiver: params.receiver.clone(),
market: params.market.clone(),
initial_collateral_token: params.initial_collateral_token.clone(),
swap_path: params.swap_path.clone(),
size_delta_usd: params.size_delta_usd,
collateral_delta_amount,
trigger_price: params.trigger_price,
acceptable_price: params.acceptable_price,
execution_fee: params.execution_fee,
min_output_amount: params.min_output_amount,
order_type: params.order_type.clone(),
is_long: params.is_long,
updated_at_time: env.ledger().timestamp(),
};
env.storage()
.persistent()
.set(&OrderStorageKey::Order(key.clone()), &order);
ds.add_bytes32_to_set(&handler, &order_list_key(&env), &key);
ds.add_bytes32_to_set(&handler, &account_order_list_key(&env, &caller), &key);
// Issue #442: include size/collateral/order_type so pending orders can
// be displayed from the creation event without an extra RPC round-trip.
env.events().publish(
(symbol_short!("ord_crt"),),
(
key.clone(),
caller.clone(),
params.market.clone(),
params.size_delta_usd,
collateral_delta_amount,
params.order_type.clone(),
),
);
keys.push_back(key);
i += 1;
}
keys
}
/// Create a new order and record collateral in the order vault.
///
/// # Collateral model (canonical — issue #47)
///
/// **Chosen path:** the exchange_router is responsible for transferring
/// collateral from the caller to order_vault BEFORE invoking create_order.
/// order_handler then calls `record_transfer_in` to snapshot the delta.
///
/// **Why this model:**
/// - The router owns the auth context for the caller's token approval.
/// - Keeping the pull inside the router makes the vault a passive custodian
/// with no token-approval dependencies of its own.
/// - Handlers never hold approvals, so they cannot silently double-pull.
///
/// **Invariant enforced here:**
/// - For increase/swap orders: `record_transfer_in` delta MUST be > 0.
/// A zero delta means tokens were not pre-sent; the transaction reverts
/// with `ZeroCollateral` before any state is written.
/// - For decrease/stop-loss/liquidation orders: no collateral is deposited;
/// `collateral_delta_amount` comes from params (typically the existing position size).
///
/// **Multicall sequence the router enforces for increase/swap orders:**
/// ```text
/// multicall([
/// SendTokens { token, receiver: order_vault, amount }, // 1. push collateral
/// CreateOrder { params }, // 2. snapshot + store order
/// ])
/// ```
///
/// Returns the order key.
pub fn create_order(env: Env, caller: Address, params: CreateOrderParams) -> BytesN<32> {
caller.require_auth();
let data_store: Address = env
.storage()
.instance()
.get(&InstanceKey::DataStore)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
let order_vault: Address = env
.storage()
.instance()
.get(&InstanceKey::OrderVault)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
let handler = env.current_contract_address();
let ds = DataStoreClient::new(&env, &data_store);
if ds.get_bool(&is_market_paused_key(&env, ¶ms.market)) {
panic_with_error!(&env, Error::MarketPaused);
}
// Issue #232: reject cyclic swap paths at creation time; any repeated market
// would double-mutate pool state and corrupt price-impact accounting.
{
let path = ¶ms.swap_path;
let path_len = path.len();
// Issue #300: enforce max path length at creation time.
let raw_max = ds.get_u128(&gmx_keys::max_swap_path_length_key(&env)) as usize;
let max_len = if raw_max == 0 { MAX_SWAP_PATH_LENGTH } else { raw_max };
if path_len as usize > max_len {
panic_with_error!(&env, Error::SwapPathTooLong);
}
let mut i = 0u32;
while i < path_len {
let mut j = i + 1;
while j < path_len {
if path.get(i).unwrap() == path.get(j).unwrap() {
panic_with_error!(&env, Error::CyclicSwapPath);
}
j += 1;
}
i += 1;
}
}
// Issue #294: reject orders that underpay the execution fee.
// Validation happens here (at creation) so underpaid orders never enter the queue.
// execution_fee is i128; reject negative values and those below the configured minimum.
{
let min_fee = ds.get_min_execution_fee();
if params.execution_fee < 0 || (params.execution_fee as u128) < min_fee {
panic_with_error!(&env, Error::InsufficientExecutionFee);
}
}
// Determine whether this order type requires upfront collateral in the vault.
// Increase and swap orders pull from the vault; decrease orders do not deposit.
let is_increase_or_swap = matches!(
params.order_type,
OrderType::MarketIncrease
| OrderType::LimitIncrease
| OrderType::StopIncrease
| OrderType::MarketSwap
| OrderType::LimitSwap
);
// Determine if this is a position order (increase/decrease)
let is_position_order = matches!(
params.order_type,
OrderType::MarketIncrease | OrderType::LimitIncrease | OrderType::StopIncrease |
OrderType::MarketDecrease | OrderType::LimitDecrease | OrderType::StopLossDecrease
);
// Issue #269: position orders must carry a non-zero size.
if is_position_order && params.size_delta_usd == 0 {
panic_with_error!(&env, Error::ZeroSizeDelta);
}
// Position manager authorization:
// For position orders, verify caller is either the owner OR an authorized manager for this market.
// If caller is a manager, receiver must be the owner (cannot redirect funds).
//
// ISSUE #385: This logic is currently REVERSED and needs fixing.
// Current code incorrectly calls get_position_manager(&caller, market) which looks up
// "who is the manager FOR caller" — but we need to check "is caller a manager FOR the owner".
//
// REQUIRED FIX: Add on_behalf_of: Option<Address> field to CreateOrderParams.
// Then verify: if on_behalf_of is present, check get_position_manager(&on_behalf_of, market) == Some(caller).
// When absent, caller must be the owner.
//
// For now, this preserves existing behavior but the logic is inverted and needs the refactor above.
let (actual_owner, actual_receiver) = if is_position_order {
// TODO(#385): This logic is reversed. See comment above for required fix.
match ds.get_position_manager(&caller, ¶ms.market) {
Some(owner) => {
// Caller is a manager; position owner is stored in data_store
// Receiver must be the owner (cannot redirect)
(owner.clone(), owner)
}
None => {
// Caller is not a manager; must be the owner
(caller.clone(), params.receiver)
}
}
} else {
// For swap orders, no position manager check needed
(caller.clone(), params.receiver)
};
// Snapshot vault balance and derive received amount (canonical model — issue #47).
// Reverts with ZeroCollateral if caller skipped the SendTokens pre-step.
let collateral_delta_amount = if is_increase_or_swap {
let received = OrderVaultClient::new(&env, &order_vault)
.record_transfer_in(¶ms.initial_collateral_token);
if received <= 0 {
panic_with_error!(&env, Error::ZeroCollateral);
}
received
} else {
// Decrease/liquidation orders: no collateral deposit required.
params.collateral_delta_amount
};
// Generate unique key
let nonce = ds.increment_nonce(&handler);
let key = order_key(&env, nonce);
let order = OrderProps {
account: actual_owner.clone(),
receiver: actual_receiver,
market: params.market.clone(),
initial_collateral_token: params.initial_collateral_token,
swap_path: params.swap_path,
size_delta_usd: params.size_delta_usd,
collateral_delta_amount,
trigger_price: params.trigger_price,
acceptable_price: params.acceptable_price,
execution_fee: params.execution_fee,
min_output_amount: params.min_output_amount,
order_type: params.order_type,
is_long: params.is_long,
updated_at_time: env.ledger().timestamp(),
};
env.storage().persistent().set(&OrderStorageKey::Order(key.clone()), &order);
env.storage().persistent().extend_ttl(
&OrderStorageKey::Order(key.clone()),
MIN_BUMP_THRESHOLD,
PERSISTENT_BUMP_TARGET,
);
env.storage()
.persistent()
.set(&OrderStorageKey::Order(key.clone()), &order);
ds.add_bytes32_to_set(&handler, &order_list_key(&env), &key);
ds.add_bytes32_to_set(&handler, &account_order_list_key(&env, &actual_owner), &key);
// Issue #272: persist per-order expiry if the user supplied one.
if let Some(exp) = params.expiry_ledger {
env.storage()
.persistent()
.set(&OrderStorageKey::OrderExpiry(key.clone()), &exp);
env.storage().persistent().extend_ttl(
&OrderStorageKey::OrderExpiry(key.clone()),
MIN_BUMP_THRESHOLD,
PERSISTENT_BUMP_TARGET,
);
}
// Issue #442: include size/collateral/order_type so pending orders can
// be displayed from the creation event without an extra RPC round-trip.
env.events().publish(
(symbol_short!("ord_crt"),),
(
key.clone(),
actual_owner,
order.market.clone(),
order.size_delta_usd,
order.collateral_delta_amount,
order.order_type.clone(),
),
);
key
}
/// Execute a pending order (called by keeper).
pub fn execute_order(env: Env, keeper: Address, key: BytesN<32>) {
keeper.require_auth();
require_order_keeper(&env, &keeper);
let data_store: Address = env
.storage()
.instance()
.get(&InstanceKey::DataStore)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
let order_vault: Address = env
.storage()
.instance()
.get(&InstanceKey::OrderVault)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
let oracle: Address = env
.storage()
.instance()
.get(&InstanceKey::Oracle)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
let handler = env.current_contract_address();
// Load order
let order: OrderProps = env
.storage()
.persistent()
.get(&OrderStorageKey::Order(key.clone()))
.unwrap_or_else(|| panic_with_error!(&env, Error::OrderNotFound));
// Issue #272: auto-cancel if the order's user-set expiry has passed.
if let Some(expiry) = env
.storage()
.persistent()
.get::<OrderStorageKey, u64>(&OrderStorageKey::OrderExpiry(key.clone()))
{
if u64::from(env.ledger().sequence()) > expiry {
// Refund collateral for increase/swap orders that deposited into the vault.
let order_vault_addr: Address = env
.storage()
.instance()
.get(&InstanceKey::OrderVault)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
let is_increase_or_swap = matches!(
order.order_type,
OrderType::MarketIncrease
| OrderType::LimitIncrease
| OrderType::StopIncrease
| OrderType::MarketSwap
| OrderType::LimitSwap
);
if is_increase_or_swap && order.collateral_delta_amount > 0 {
OrderVaultClient::new(&env, &order_vault_addr).transfer_out(
&env.current_contract_address(),
&order.initial_collateral_token,
&order.receiver,
&order.collateral_delta_amount,
);
}
// Clean up storage
env.storage()
.persistent()
.remove(&OrderStorageKey::Order(key.clone()));
env.storage()
.persistent()
.remove(&OrderStorageKey::OrderExpiry(key.clone()));
let handler2 = env.current_contract_address();
let ds2 = DataStoreClient::new(&env, &data_store);
ds2.remove_bytes32_from_set(
&handler2,
&order_list_key(&env),
&key,
);
ds2.remove_bytes32_from_set(
&handler2,
&account_order_list_key(&env, &order.account),
&key,
);
// Match the 4-field payload published by cleanup_expired_order so
// subscribers to this topic can rely on one stable schema; there is
// no permissionless caller or incentive on this auto-cancel path.
env.events().publish(
(symbol_short!("ord_exp"),),
(key.clone(), order.account.clone(), keeper.clone(), 0i128),
);
panic_with_error!(&env, Error::OrderExpired);
}
}
// Check frozen
let is_frozen: bool = env
.storage()
.persistent()
.get(&OrderStorageKey::OrderFrozen(key.clone()))
.unwrap_or(false);
if is_frozen {
panic_with_error!(&env, Error::OrderFrozen);
}
let ds = DataStoreClient::new(&env, &data_store);
if ds.get_bool(&is_market_paused_key(&env, &order.market)) {
panic_with_error!(&env, Error::MarketPaused);
}
// Load market props
let market = load_market_props(&env, &data_store, &order.market);
// Fetch oracle prices
let oracle_client = OracleClient::new(&env, &oracle);
let index_price = oracle_client.get_primary_price(&market.index_token);
let collateral_price = oracle_client
.get_primary_price(&order.initial_collateral_token)
.mid_price();
// Trigger price checks for non-market orders
match order.order_type {
OrderType::LimitIncrease if index_price.min > order.trigger_price => {
panic_with_error!(&env, Error::UnsatisfiedTrigger);
}
// StopIncrease fires when price rises to or above the trigger (buy-stop).
// Reject execution while the index price is still below the trigger.
OrderType::StopIncrease if index_price.min < order.trigger_price => {
panic_with_error!(&env, Error::UnsatisfiedTrigger);
}
OrderType::LimitDecrease => {
if order.is_long && index_price.max < order.trigger_price {
panic_with_error!(&env, Error::UnsatisfiedTrigger);
}
if !order.is_long && index_price.max > order.trigger_price {
panic_with_error!(&env, Error::UnsatisfiedTrigger);
}
}
OrderType::StopLossDecrease => {
if order.is_long && index_price.min > order.trigger_price {
panic_with_error!(&env, Error::UnsatisfiedTrigger);
}
if !order.is_long && index_price.min < order.trigger_price {
panic_with_error!(&env, Error::UnsatisfiedTrigger);
}
}
// LimitSwap: execute only when the index price is at or below trigger_price.