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
1316 lines (1160 loc) · 51 KB
/
Copy pathlib.rs
File metadata and controls
1316 lines (1160 loc) · 51 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
//! Withdrawal Handler — create, execute, and cancel LP token withdrawals.
//!
//! Mirrors GMX's WithdrawalHandler.sol + ExecuteWithdrawalUtils.sol:
//!
//! Flow:
//! 1. User approves LP tokens to withdrawal_handler.
//! 2. User calls `create_withdrawal` → LP tokens pulled to withdrawal_vault.
//! 3. Keeper sets oracle prices, then calls `execute_withdrawal`:
//! - Splits the withdrawal by the pool's current USD-value weight between
//! long/short (issue #255), using prices fresh for this ledger.
//! - Burns LP tokens from vault.
//! - Transfers pool tokens from market_token contract → receiver.
//! - Updates pool amounts.
//! 4. On cancel: LP tokens refunded from vault.
#![no_std]
#![allow(dependency_on_unit_never_type_fallback)]
use gmx_keys::{
account_withdrawal_list_key, is_market_paused_key, market_index_token_key,
market_long_token_key, market_short_token_key, roles, withdrawal_key, withdrawal_list_key,
};
use gmx_market_utils::{apply_delta_to_pool_amount, get_pool_amount};
use gmx_math::{mul_div_wide, TOKEN_PRECISION};
pub use gmx_types::CreateWithdrawalParams;
use gmx_types::{MarketProps, WithdrawalProps};
use soroban_sdk::{
contract, contracterror, contractimpl, contracttype, panic_with_error, symbol_short, token,
Address, BytesN, Env,
};
// ─── Errors ───────────────────────────────────────────────────────────────────
#[contracterror]
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
#[repr(u32)]
pub enum Error {
AlreadyInitialized = 1,
NotInitialized = 2,
Unauthorized = 3,
WithdrawalNotFound = 4,
InsufficientLongOut = 5,
InsufficientShortOut = 6,
ZeroWithdrawal = 7,
InvalidMarket = 8,
InvalidReceiver = 9,
/// Issue #370: execution_fee is below the configured global minimum.
InsufficientExecutionFee = 10,
/// Issue #366: market is paused due to oracle circuit breaker.
MarketPaused = 11,
}
// ─── Storage ──────────────────────────────────────────────────────────────────
#[contracttype]
enum InstanceKey {
Initialized,
Admin,
RoleStore,
DataStore,
Oracle,
WithdrawalVault,
}
#[contracttype]
enum LocalKey {
Withdrawal(BytesN<32>),
}
// WithdrawalProps 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 (withdrawal_list_key, account_withdrawal_list_key)
// for enumeration. This matches the deposit and order handler patterns (issue #24).
// ─── Cross-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_bool(env: Env, key: BytesN<32>) -> bool;
fn get_u128(env: Env, key: BytesN<32>) -> u128;
fn set_u128(env: Env, caller: Address, key: BytesN<32>, value: u128) -> u128;
fn get_i128(env: Env, key: BytesN<32>) -> i128;
fn set_i128(env: Env, caller: Address, key: BytesN<32>, value: i128) -> i128;
fn apply_delta_to_u128(env: Env, caller: Address, key: BytesN<32>, delta: i128) -> u128;
fn apply_delta_to_i128(env: Env, caller: Address, key: BytesN<32>, delta: i128) -> i128;
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 increment_nonce(env: Env, caller: Address) -> u64;
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) -> gmx_types::PriceProps;
fn require_price_fresh(env: Env, token: Address, expected_ledger_seq: u32) -> gmx_types::PriceProps;
}
#[allow(dead_code)]
#[soroban_sdk::contractclient(name = "WithdrawalVaultClient")]
trait IWithdrawalVault {
fn transfer_out(env: Env, caller: Address, token: Address, receiver: Address, amount: i128);
}
#[allow(dead_code)]
#[soroban_sdk::contractclient(name = "MarketTokenClient")]
trait IMarketToken {
fn burn(env: Env, from: Address, amount: i128);
fn total_supply(env: Env) -> i128;
fn withdraw_from_pool(
env: Env,
caller: Address,
pool_token: Address,
receiver: Address,
amount: i128,
);
}
// ─── Contract ─────────────────────────────────────────────────────────────────
#[contract]
pub struct WithdrawalHandler;
#[contractimpl]
impl WithdrawalHandler {
// ── Init ─────────────────────────────────────────────────────────────────
pub fn initialize(
env: Env,
admin: Address,
role_store: Address,
data_store: Address,
oracle: Address,
withdrawal_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::WithdrawalVault, &withdrawal_vault);
}
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);
}
// ── Create withdrawal ─────────────────────────────────────────────────────
/// Pull LP tokens from caller into the withdrawal_vault and record the withdrawal.
pub fn create_withdrawal(
env: Env,
caller: Address,
params: CreateWithdrawalParams,
) -> BytesN<32> {
caller.require_auth();
// ── Input validation (issue #39) ──────────────────────────────────────
if params.market_token_amount <= 0 {
panic_with_error!(&env, Error::ZeroWithdrawal);
}
// Receiver must not be the zero/contract address — use the contract itself
// as a sentinel: a real receiver must differ from the handler.
if params.receiver == env.current_contract_address() {
panic_with_error!(&env, Error::InvalidReceiver);
}
let data_store: Address = env
.storage()
.instance()
.get(&InstanceKey::DataStore)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
let withdrawal_vault: Address = env
.storage()
.instance()
.get(&InstanceKey::WithdrawalVault)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
let handler = env.current_contract_address();
let ds = DataStoreClient::new(&env, &data_store);
// Validate that the market token is a known market (index token must exist)
if ds
.get_address(&gmx_keys::market_index_token_key(&env, ¶ms.market))
.is_none()
{
panic_with_error!(&env, Error::InvalidMarket);
}
// Issue #366: reject withdrawals when the market is paused (oracle circuit breaker)
if ds.get_bool(&is_market_paused_key(&env, ¶ms.market)) {
panic_with_error!(&env, Error::MarketPaused);
}
// Issue #370: validate execution_fee against the global minimum before
// any tokens move. execution_fee is collected in the market (LP) token; 0
// means no fee required.
let exec_fee = params.execution_fee;
if exec_fee < 0 {
panic_with_error!(&env, Error::InsufficientExecutionFee);
}
let min_fee = ds.get_min_execution_fee();
if min_fee > 0 && (exec_fee as u128) < min_fee {
panic_with_error!(&env, Error::InsufficientExecutionFee);
}
// Pull LP tokens from caller → withdrawal_vault
let market_addr = params.market.clone();
token::Client::new(&env, ¶ms.market).transfer(
&caller,
&withdrawal_vault,
¶ms.market_token_amount,
);
// Issue #370: collect execution_fee in the market (LP) token.
if exec_fee > 0 {
token::Client::new(&env, ¶ms.market).transfer(
&caller,
&withdrawal_vault,
&exec_fee,
);
}
// Allocate withdrawal key from nonce
let nonce = ds.increment_nonce(&handler);
let key = withdrawal_key(&env, nonce);
let withdrawal = WithdrawalProps {
account: caller.clone(),
receiver: params.receiver,
market: params.market,
market_token_amount: params.market_token_amount,
min_long_token_amount: params.min_long_token_amount,
min_short_token_amount: params.min_short_token_amount,
execution_fee: params.execution_fee,
updated_at_time: env.ledger().timestamp(),
};
env.storage()
.persistent()
.set(&LocalKey::Withdrawal(key.clone()), &withdrawal);
ds.add_bytes32_to_set(&handler, &withdrawal_list_key(&env), &key);
ds.add_bytes32_to_set(&handler, &account_withdrawal_list_key(&env, &caller), &key);
// Issue #442: include the market-token amount being redeemed so pending
// withdrawals can be displayed from the creation event without an extra
// RPC round-trip.
env.events().publish(
(symbol_short!("wth_crt"),),
(key.clone(), caller, market_addr, withdrawal.market_token_amount),
);
key
}
// ── Execute withdrawal ────────────────────────────────────────────────────
/// Keeper executes a pending withdrawal: burns LP tokens, returns pool tokens.
pub fn execute_withdrawal(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 withdrawal_vault: Address = env
.storage()
.instance()
.get(&InstanceKey::WithdrawalVault)
.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();
let withdrawal: WithdrawalProps = env
.storage()
.persistent()
.get(&LocalKey::Withdrawal(key.clone()))
.unwrap_or_else(|| panic_with_error!(&env, Error::WithdrawalNotFound));
let market = load_market_props(&env, &data_store, &withdrawal.market);
// Issue #366: reject execution when the market is paused (oracle circuit breaker)
let ds = DataStoreClient::new(&env, &data_store);
if ds.get_bool(&is_market_paused_key(&env, &withdrawal.market)) {
panic_with_error!(&env, Error::MarketPaused);
}
let mt_client = MarketTokenClient::new(&env, &market.market_token);
let total_supply = mt_client.total_supply();
let lp_amount = withdrawal.market_token_amount;
// Issue #255: split the withdrawal by the pool's CURRENT USD-value weight
// between long/short, not a fixed 50/50 or amount-only split. Prices must
// be fresh for this ledger (mirrors deposit_handler's #253 fix) so the
// weight reflects the keeper's just-submitted price.
let oracle_client = OracleClient::new(&env, &oracle);
let current_seq = env.ledger().sequence();
let long_price = oracle_client
.require_price_fresh(&market.long_token, ¤t_seq)
.mid_price();
let short_price = oracle_client
.require_price_fresh(&market.short_token, ¤t_seq)
.mid_price();
let long_pool = get_pool_amount(&env, &data_store, &market, &market.long_token) as i128;
let short_pool = get_pool_amount(&env, &data_store, &market, &market.short_token) as i128;
let long_pool_usd = mul_div_wide(&env, long_pool, long_price, TOKEN_PRECISION);
let short_pool_usd = mul_div_wide(&env, short_pool, short_price, TOKEN_PRECISION);
let total_pool_usd = long_pool_usd + short_pool_usd;
let (long_out, short_out) = if total_pool_usd == 0 {
(0, 0)
} else {
// USD value of the LP tokens being burned, at the pool's current total value.
let withdrawal_value_usd = mul_div_wide(&env, total_pool_usd, lp_amount, total_supply);
// Split by each side's USD weight (long_pool_usd / total_pool_usd), as a
// single fused division rather than normalizing the weight to a separate
// FLOAT_PRECISION fraction first and re-applying it: chaining two roundings
// can leave 1-unit dust behind even on a full (100%) withdrawal, where this
// fused form is exact.
let long_out_usd = mul_div_wide(&env, withdrawal_value_usd, long_pool_usd, total_pool_usd);
let short_out_usd = mul_div_wide(&env, withdrawal_value_usd, short_pool_usd, total_pool_usd);
let long_out = if long_price > 0 {
mul_div_wide(&env, long_out_usd, TOKEN_PRECISION, long_price)
} else {
0
};
let short_out = if short_price > 0 {
mul_div_wide(&env, short_out_usd, TOKEN_PRECISION, short_price)
} else {
0
};
(long_out, short_out)
};
// Slippage guard checked AFTER the weight-adjusted amounts are computed.
if long_out < withdrawal.min_long_token_amount {
panic_with_error!(&env, Error::InsufficientLongOut);
}
if short_out < withdrawal.min_short_token_amount {
panic_with_error!(&env, Error::InsufficientShortOut);
}
// Burn LP tokens from vault
WithdrawalVaultClient::new(&env, &withdrawal_vault).transfer_out(
&handler,
&market.market_token,
&handler,
&lp_amount,
);
mt_client.burn(&handler, &lp_amount);
// CEI fix (#295): delete the withdrawal record before any pool transfer so that
// a re-entrant callback on the receiving contract cannot replay this execution.
remove_withdrawal(&env, &data_store, &handler, &key, &withdrawal.account);
// Transfer pool tokens from market_token contract → receiver
if long_out > 0 {
apply_delta_to_pool_amount(
&env,
&data_store,
&handler,
&market,
&market.long_token,
-long_out,
);
mt_client.withdraw_from_pool(
&handler,
&market.long_token,
&withdrawal.receiver,
&long_out,
);
}
if short_out > 0 {
apply_delta_to_pool_amount(
&env,
&data_store,
&handler,
&market,
&market.short_token,
-short_out,
);
mt_client.withdraw_from_pool(
&handler,
&market.short_token,
&withdrawal.receiver,
&short_out,
);
}
env.events().publish(
(symbol_short!("wth_exe"),),
(key, withdrawal.receiver, long_out, short_out),
);
}
// ── Cancel withdrawal ─────────────────────────────────────────────────────
pub fn cancel_withdrawal(env: Env, caller: Address, key: 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 withdrawal_vault: Address = env
.storage()
.instance()
.get(&InstanceKey::WithdrawalVault)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
let role_store: Address = env
.storage()
.instance()
.get(&InstanceKey::RoleStore)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
let handler = env.current_contract_address();
let withdrawal: WithdrawalProps = env
.storage()
.persistent()
.get(&LocalKey::Withdrawal(key.clone()))
.unwrap_or_else(|| panic_with_error!(&env, Error::WithdrawalNotFound));
let is_keeper =
RoleStoreClient::new(&env, &role_store).has_role(&caller, &roles::order_keeper(&env));
if caller != withdrawal.account && !is_keeper {
panic_with_error!(&env, Error::Unauthorized);
}
// Refund LP tokens
WithdrawalVaultClient::new(&env, &withdrawal_vault).transfer_out(
&handler,
&withdrawal.market,
&withdrawal.account,
&withdrawal.market_token_amount,
);
// Issue #370: refund execution_fee to the user on cancellation.
// The keeper earns execution_fee only when it actually attempts execution;
// a cancelled withdrawal did no keeper work, so the full fee is refunded.
if withdrawal.execution_fee > 0 {
WithdrawalVaultClient::new(&env, &withdrawal_vault).transfer_out(
&handler,
&withdrawal.market,
&withdrawal.account,
&withdrawal.execution_fee,
);
}
remove_withdrawal(&env, &data_store, &handler, &key, &withdrawal.account);
env.events()
.publish((symbol_short!("wth_can"),), (key, withdrawal.account));
}
// ── Views ─────────────────────────────────────────────────────────────────
pub fn get_withdrawal(env: Env, key: BytesN<32>) -> Option<WithdrawalProps> {
env.storage().persistent().get(&LocalKey::Withdrawal(key))
}
}
// ─── Helpers ──────────────────────────────────────────────────────────────────
fn require_order_keeper(env: &Env, caller: &Address) {
let role_store: Address = env
.storage()
.instance()
.get(&InstanceKey::RoleStore)
.unwrap_or_else(|| panic_with_error!(env, Error::NotInitialized));
if !RoleStoreClient::new(env, &role_store).has_role(caller, &roles::order_keeper(env)) {
panic_with_error!(env, Error::Unauthorized);
}
}
fn load_market_props(env: &Env, data_store: &Address, market_token: &Address) -> MarketProps {
let ds = DataStoreClient::new(env, data_store);
MarketProps {
market_token: market_token.clone(),
index_token: ds
.get_address(&market_index_token_key(env, market_token))
.unwrap_or_else(|| panic_with_error!(env, Error::InvalidMarket)),
long_token: ds
.get_address(&market_long_token_key(env, market_token))
.unwrap_or_else(|| panic_with_error!(env, Error::InvalidMarket)),
short_token: ds
.get_address(&market_short_token_key(env, market_token))
.unwrap_or_else(|| panic_with_error!(env, Error::InvalidMarket)),
}
}
fn remove_withdrawal(
env: &Env,
data_store: &Address,
handler: &Address,
key: &BytesN<32>,
account: &Address,
) {
env.storage()
.persistent()
.remove(&LocalKey::Withdrawal(key.clone()));
let ds = DataStoreClient::new(env, data_store);
ds.remove_bytes32_from_set(handler, &withdrawal_list_key(env), key);
ds.remove_bytes32_from_set(handler, &account_withdrawal_list_key(env, account), key);
}
// ─── Tests ────────────────────────────────────────────────────────────────────
#[cfg(test)]
mod tests {
use super::*;
use data_store::{DataStore, DataStoreClient as DsClient};
use deposit_handler::{CreateDepositParams, DepositHandler, DepositHandlerClient};
use deposit_vault::{DepositVault, DepositVaultClient as DVClient};
use gmx_keys::roles;
use gmx_types::TokenPrice;
use market_token::{MarketToken, MarketTokenClient as MtClient};
use oracle::{Oracle, OracleClient as OClient};
use role_store::{RoleStore, RoleStoreClient as RsClient};
use soroban_sdk::{
testutils::{Address as _, Ledger as _},
token::StellarAssetClient,
Env, Vec,
};
use withdrawal_vault::{WithdrawalVault, WithdrawalVaultClient as WVClient};
struct World {
env: Env,
admin: Address,
keeper: Address,
rs: Address,
ds: Address,
oracle: Address,
dep_vault: Address,
wth_vault: Address,
dep_handler: Address,
wth_handler: Address,
market_tk: Address,
long_tk: Address,
short_tk: Address,
index_tk: Address,
}
fn setup() -> World {
let env = Env::default();
env.mock_all_auths();
let admin = Address::generate(&env);
let keeper = Address::generate(&env);
let rs = env.register(RoleStore, ());
RsClient::new(&env, &rs).initialize(&admin);
let rs_c = RsClient::new(&env, &rs);
rs_c.grant_role(&admin, &admin, &roles::controller(&env));
rs_c.grant_role(&admin, &keeper, &roles::order_keeper(&env));
let ds = env.register(DataStore, ());
DsClient::new(&env, &ds).initialize(&admin, &rs);
let oracle_addr = env.register(Oracle, ());
let passphrase = soroban_sdk::Bytes::from_slice(&env, b"Test SDF Network ; September 2015");
OClient::new(&env, &oracle_addr).initialize(&admin, &rs, &ds, &passphrase);
let dep_vault = env.register(DepositVault, ());
DVClient::new(&env, &dep_vault).initialize(&admin, &rs);
let wth_vault = env.register(WithdrawalVault, ());
WVClient::new(&env, &wth_vault).initialize(&admin, &rs);
let market_tk = env.register(MarketToken, ());
MtClient::new(&env, &market_tk).initialize(
&admin,
&rs,
&7u32,
&soroban_sdk::String::from_str(&env, "GMX Market Token"),
&soroban_sdk::String::from_str(&env, "GM"),
);
let dep_handler = env.register(DepositHandler, ());
DepositHandlerClient::new(&env, &dep_handler).initialize(
&admin,
&rs,
&ds,
&oracle_addr,
&dep_vault,
);
let wth_handler = env.register(WithdrawalHandler, ());
WithdrawalHandlerClient::new(&env, &wth_handler).initialize(
&admin,
&rs,
&ds,
&oracle_addr,
&wth_vault,
);
rs_c.grant_role(&admin, &dep_handler, &roles::controller(&env));
rs_c.grant_role(&admin, &wth_handler, &roles::controller(&env));
let long_tk = env
.register_stellar_asset_contract_v2(admin.clone())
.address();
let short_tk = env
.register_stellar_asset_contract_v2(admin.clone())
.address();
let index_tk = Address::generate(&env);
let ds_c = DsClient::new(&env, &ds);
ds_c.set_address(
&dep_handler,
&gmx_keys::market_index_token_key(&env, &market_tk),
&index_tk,
);
ds_c.set_address(
&dep_handler,
&gmx_keys::market_long_token_key(&env, &market_tk),
&long_tk,
);
ds_c.set_address(
&dep_handler,
&gmx_keys::market_short_token_key(&env, &market_tk),
&short_tk,
);
World {
env,
admin,
keeper,
rs,
ds,
oracle: oracle_addr,
dep_vault,
wth_vault,
dep_handler,
wth_handler,
market_tk,
long_tk,
short_tk,
index_tk,
}
}
fn set_prices(w: &World) {
let fp = gmx_math::FLOAT_PRECISION;
OClient::new(&w.env, &w.oracle).set_prices_simple(
&w.keeper,
&Vec::from_array(
&w.env,
[
TokenPrice {
token: w.long_tk.clone(),
min: 2000 * fp,
max: 2000 * fp,
},
TokenPrice {
token: w.short_tk.clone(),
min: fp,
max: fp,
},
TokenPrice {
token: w.index_tk.clone(),
min: 2000 * fp,
max: 2000 * fp,
},
],
),
);
}
/// Helper: deposit long+short tokens and return the minted LP balance.
fn do_deposit(w: &World, user: &Address, long_amount: i128, short_amount: i128) -> i128 {
let dep_key = DepositHandlerClient::new(&w.env, &w.dep_handler).create_deposit(
user,
&CreateDepositParams {
receiver: user.clone(),
market: w.market_tk.clone(),
initial_long_token: w.long_tk.clone(),
initial_short_token: w.short_tk.clone(),
long_token_amount: long_amount,
short_token_amount: short_amount,
min_market_tokens: 1,
execution_fee: 0,
},
);
DepositHandlerClient::new(&w.env, &w.dep_handler).execute_deposit(&w.keeper, &dep_key);
MtClient::new(&w.env, &w.market_tk).balance(user)
}
// ── Issue #39: withdrawal input validation ────────────────────────────────
/// Zero LP amount must revert before any token movement.
#[test]
#[should_panic]
fn create_withdrawal_zero_lp_amount_reverts() {
let w = setup();
let user = Address::generate(&w.env);
WithdrawalHandlerClient::new(&w.env, &w.wth_handler).create_withdrawal(
&user,
&CreateWithdrawalParams {
receiver: user.clone(),
market: w.market_tk.clone(),
market_token_amount: 0,
min_long_token_amount: 0,
min_short_token_amount: 0,
execution_fee: 0,
},
);
}
/// Unknown market (not registered in data_store) must revert.
#[test]
#[should_panic]
fn create_withdrawal_unknown_market_reverts() {
let w = setup();
let user = Address::generate(&w.env);
let fake_market = Address::generate(&w.env);
WithdrawalHandlerClient::new(&w.env, &w.wth_handler).create_withdrawal(
&user,
&CreateWithdrawalParams {
receiver: user.clone(),
market: fake_market,
market_token_amount: 1_000,
min_long_token_amount: 0,
min_short_token_amount: 0,
execution_fee: 0,
},
);
}
/// Receiver set to the handler contract itself must revert.
#[test]
#[should_panic]
fn create_withdrawal_invalid_receiver_reverts() {
let w = setup();
let user = Address::generate(&w.env);
// Use the handler address as receiver — should be rejected
let bad_receiver = w.wth_handler.clone();
WithdrawalHandlerClient::new(&w.env, &w.wth_handler).create_withdrawal(
&user,
&CreateWithdrawalParams {
receiver: bad_receiver,
market: w.market_tk.clone(),
market_token_amount: 1_000,
min_long_token_amount: 0,
min_short_token_amount: 0,
execution_fee: 0,
},
);
}
// ── Issue #41: min output enforcement ────────────────────────────────────
/// Withdrawal where long output falls below min_long_token_amount must revert
/// and leave state unchanged (no tokens moved, no LP burned).
#[test]
#[should_panic]
fn execute_withdrawal_below_min_long_reverts() {
let w = setup();
let env = &w.env;
let user = Address::generate(env);
StellarAssetClient::new(env, &w.long_tk).mint(&user, &1_000_0000i128);
set_prices(&w);
let lp = do_deposit(&w, &user, 1_000_0000, 0);
set_prices(&w);
let wth_key = WithdrawalHandlerClient::new(env, &w.wth_handler).create_withdrawal(
&user,
&CreateWithdrawalParams {
receiver: user.clone(),
market: w.market_tk.clone(),
market_token_amount: lp,
// demand more long tokens than the pool can provide
min_long_token_amount: i128::MAX,
min_short_token_amount: 0,
execution_fee: 0,
},
);
WithdrawalHandlerClient::new(env, &w.wth_handler).execute_withdrawal(&w.keeper, &wth_key);
}
/// Withdrawal where short output falls below min_short_token_amount must revert.
#[test]
#[should_panic]
fn execute_withdrawal_below_min_short_reverts() {
let w = setup();
let env = &w.env;
let user = Address::generate(env);
StellarAssetClient::new(env, &w.short_tk).mint(&user, &500_0000i128);
set_prices(&w);
let lp = do_deposit(&w, &user, 0, 500_0000);
set_prices(&w);
let wth_key = WithdrawalHandlerClient::new(env, &w.wth_handler).create_withdrawal(
&user,
&CreateWithdrawalParams {
receiver: user.clone(),
market: w.market_tk.clone(),
market_token_amount: lp,
min_long_token_amount: 0,
// demand more short tokens than the pool can provide
min_short_token_amount: i128::MAX,
execution_fee: 0,
},
);
WithdrawalHandlerClient::new(env, &w.wth_handler).execute_withdrawal(&w.keeper, &wth_key);
}
/// Partial pool state: only long tokens in pool, short pool is empty.
/// min_short_token_amount = 0 should succeed; min_short > 0 should revert.
#[test]
#[should_panic]
fn execute_withdrawal_partial_pool_short_empty_reverts_when_min_short_nonzero() {
let w = setup();
let env = &w.env;
let user = Address::generate(env);
// Deposit only long tokens → short pool stays empty
StellarAssetClient::new(env, &w.long_tk).mint(&user, &1_000_0000i128);
set_prices(&w);
let lp = do_deposit(&w, &user, 1_000_0000, 0);
set_prices(&w);
let wth_key = WithdrawalHandlerClient::new(env, &w.wth_handler).create_withdrawal(
&user,
&CreateWithdrawalParams {
receiver: user.clone(),
market: w.market_tk.clone(),
market_token_amount: lp,
min_long_token_amount: 0,
min_short_token_amount: 1, // short pool is empty → must revert
execution_fee: 0,
},
);
WithdrawalHandlerClient::new(env, &w.wth_handler).execute_withdrawal(&w.keeper, &wth_key);
}
/// Partial pool state: only long tokens, min_short = 0 → succeeds.
#[test]
fn execute_withdrawal_partial_pool_long_only_succeeds() {
let w = setup();
let env = &w.env;
let user = Address::generate(env);
StellarAssetClient::new(env, &w.long_tk).mint(&user, &1_000_0000i128);
set_prices(&w);
let lp = do_deposit(&w, &user, 1_000_0000, 0);
set_prices(&w);
let wth_key = WithdrawalHandlerClient::new(env, &w.wth_handler).create_withdrawal(
&user,
&CreateWithdrawalParams {
receiver: user.clone(),
market: w.market_tk.clone(),
market_token_amount: lp,
min_long_token_amount: 0,
min_short_token_amount: 0,
execution_fee: 0,
},
);
WithdrawalHandlerClient::new(env, &w.wth_handler).execute_withdrawal(&w.keeper, &wth_key);
let long_back = StellarAssetClient::new(env, &w.long_tk).balance(&user);
assert!(long_back > 0, "should receive long tokens back");
assert_eq!(MtClient::new(env, &w.market_tk).balance(&user), 0);
}
// ── Issue #32: storage cleanup ────────────────────────────────────────────
/// After cancel_withdrawal, the record must be gone from local storage AND
/// from both the global and per-account withdrawal lists in data_store.
#[test]
fn cancel_withdrawal_cleans_up_storage_and_lists() {
let w = setup();
let env = &w.env;
let user = Address::generate(env);
StellarAssetClient::new(env, &w.long_tk).mint(&user, &1_000_0000i128);
set_prices(&w);
let lp = do_deposit(&w, &user, 1_000_0000, 0);
assert!(lp > 0);
let wth_key = WithdrawalHandlerClient::new(env, &w.wth_handler).create_withdrawal(
&user,
&CreateWithdrawalParams {
receiver: user.clone(),
market: w.market_tk.clone(),
market_token_amount: lp,
min_long_token_amount: 0,
min_short_token_amount: 0,
execution_fee: 0,
},
);
let ds_c = DsClient::new(env, &w.ds);
assert!(WithdrawalHandlerClient::new(env, &w.wth_handler)
.get_withdrawal(&wth_key)
.is_some());
assert!(ds_c.contains_bytes32(&gmx_keys::withdrawal_list_key(env), &wth_key));
assert!(ds_c.contains_bytes32(&gmx_keys::account_withdrawal_list_key(env, &user), &wth_key));
WithdrawalHandlerClient::new(env, &w.wth_handler).cancel_withdrawal(&user, &wth_key);
assert!(
WithdrawalHandlerClient::new(env, &w.wth_handler)
.get_withdrawal(&wth_key)
.is_none(),
"record must be removed after cancel"
);
assert!(
!ds_c.contains_bytes32(&gmx_keys::withdrawal_list_key(env), &wth_key),
"global withdrawal list must not contain key after cancel"
);
assert!(
!ds_c.contains_bytes32(&gmx_keys::account_withdrawal_list_key(env, &user), &wth_key),
"account withdrawal list must not contain key after cancel"
);
}
/// After execute_withdrawal, the record must be gone from local storage AND
/// from both the global and per-account withdrawal lists in data_store.
#[test]
fn execute_withdrawal_cleans_up_storage_and_lists() {
let w = setup();
let env = &w.env;
let user = Address::generate(env);
StellarAssetClient::new(env, &w.long_tk).mint(&user, &1_000_0000i128);
set_prices(&w);
let lp = do_deposit(&w, &user, 1_000_0000, 0);
assert!(lp > 0);
set_prices(&w);
let wth_key = WithdrawalHandlerClient::new(env, &w.wth_handler).create_withdrawal(
&user,
&CreateWithdrawalParams {
receiver: user.clone(),
market: w.market_tk.clone(),
market_token_amount: lp,
min_long_token_amount: 0,
min_short_token_amount: 0,
execution_fee: 0,
},
);
let ds_c = DsClient::new(env, &w.ds);
assert!(WithdrawalHandlerClient::new(env, &w.wth_handler)
.get_withdrawal(&wth_key)
.is_some());
assert!(ds_c.contains_bytes32(&gmx_keys::withdrawal_list_key(env), &wth_key));
assert!(ds_c.contains_bytes32(&gmx_keys::account_withdrawal_list_key(env, &user), &wth_key));
WithdrawalHandlerClient::new(env, &w.wth_handler).execute_withdrawal(&w.keeper, &wth_key);