ostium-rust-sdk 0.1.0

Rust SDK for interacting with the Ostium trading platform on Arbitrum
Documentation
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
use alloy::network::Network;
use alloy::primitives::{aliases::U192, Address, U256};
use alloy::providers::Provider;
use alloy::sol_types::sol;

use crate::error::{OstiumError, Result};
use crate::types::{OpenOrderType, Trade, UnsignedTransaction, UnsignedTransactionParams};

// Define the Trading contract interface
sol! {
    #[sol(rpc)]
    contract OstiumTrading {
        // Structs
        struct Trade {
            uint256 collateral;
            uint192 openPrice;
            uint192 tp;
            uint192 sl;
            address trader;
            uint32 leverage;
            uint16 pairIndex;
            uint8 index;
            bool buy;
        }

        // Enums
        enum OpenOrderType {
            /// Market order - executed immediately at current market price
            MARKET,
            /// Limit order - executed when price reaches specified level
            LIMIT,
            /// Stop order - executed when price crosses stop level
            STOP
        }

        enum AutomationOrderStatus {
            /// Order executed successfully
            SUCCESS,
            /// Order execution failed
            FAILED
        }

        // Functions
        function openTrade(Trade calldata t, OpenOrderType orderType, uint256 slippageP) external;
        function closeTradeMarket(uint16 pairIndex, uint8 index, uint16 closePercentage) external;
        function cancelOpenLimitOrder(uint16 pairIndex, uint8 index) external;
        function updateTp(uint16 pairIndex, uint8 index, uint192 newTp) external;
        function updateSl(uint16 pairIndex, uint8 index, uint192 newSl) external;
        function updateOpenLimitOrder(uint16 pairIndex, uint8 index, uint192 price, uint192 tp, uint192 sl) external;
        function topUpCollateral(uint16 pairIndex, uint8 index, uint256 topUpAmount) external;
        function removeCollateral(uint16 pairIndex, uint8 index, uint256 removeAmount) external;
        function setDelegate(address delegate) external;
        function removeDelegate() external;
        function delegatedAction(address trader, bytes calldata call_data) external returns (bytes memory);
        function openTradeMarketTimeout(uint256 _order) external;
        function closeTradeMarketTimeout(uint256 _order, bool retry) external;
    }
}

/// Trading contract wrapper
pub struct TradingContract<P: Provider<N>, N: Network = alloy::network::Ethereum> {
    contract: OstiumTrading::OstiumTradingInstance<P, N>,
}

impl<P: Provider<N>, N: Network> TradingContract<P, N> {
    /// Create a new Trading contract instance
    pub fn new(address: Address, provider: P) -> Self {
        let contract = OstiumTrading::new(address, provider);
        Self { contract }
    }

    /// Open a new trade
    pub async fn open_trade(
        &self,
        trade: Trade,
        order_type: OpenOrderType,
        slippage_p: U256,
    ) -> Result<()> {
        let sol_trade = OstiumTrading::Trade {
            collateral: trade.collateral,
            openPrice: U192::from(trade.open_price),
            tp: U192::from(trade.tp),
            sl: U192::from(trade.sl),
            trader: trade.trader,
            leverage: trade.leverage,
            pairIndex: trade.pair_index,
            index: trade.index,
            buy: trade.buy,
        };

        let sol_order_type = match order_type {
            OpenOrderType::Market => OstiumTrading::OpenOrderType::MARKET,
            OpenOrderType::Limit => OstiumTrading::OpenOrderType::LIMIT,
            OpenOrderType::Stop => OstiumTrading::OpenOrderType::STOP,
        };

        let _receipt = self
            .contract
            .openTrade(sol_trade, sol_order_type, slippage_p)
            .send()
            .await
            .map_err(|e| OstiumError::contract(format!("Failed to open trade: {}", e)))?
            .get_receipt()
            .await
            .map_err(|e| OstiumError::contract(format!("Failed to get receipt: {}", e)))?;

        Ok(())
    }

    /// Close a trade at market price
    pub async fn close_trade_market(
        &self,
        pair_index: u16,
        index: u8,
        close_percentage: u16,
    ) -> Result<()> {
        let _receipt = self
            .contract
            .closeTradeMarket(pair_index, index, close_percentage)
            .send()
            .await
            .map_err(|e| OstiumError::contract(format!("Failed to close trade: {}", e)))?
            .get_receipt()
            .await
            .map_err(|e| OstiumError::contract(format!("Failed to get receipt: {}", e)))?;

        Ok(())
    }

    /// Cancel an open limit order
    pub async fn cancel_open_limit_order(&self, pair_index: u16, index: u8) -> Result<()> {
        let _receipt = self
            .contract
            .cancelOpenLimitOrder(pair_index, index)
            .send()
            .await
            .map_err(|e| OstiumError::contract(format!("Failed to cancel order: {}", e)))?
            .get_receipt()
            .await
            .map_err(|e| OstiumError::contract(format!("Failed to get receipt: {}", e)))?;

        Ok(())
    }

    /// Update take profit price
    pub async fn update_tp(&self, pair_index: u16, index: u8, new_tp: U192) -> Result<()> {
        let _receipt = self
            .contract
            .updateTp(pair_index, index, new_tp)
            .send()
            .await
            .map_err(|e| OstiumError::contract(format!("Failed to update TP: {}", e)))?
            .get_receipt()
            .await
            .map_err(|e| OstiumError::contract(format!("Failed to get receipt: {}", e)))?;

        Ok(())
    }

    /// Update stop loss price
    pub async fn update_sl(&self, pair_index: u16, index: u8, new_sl: U192) -> Result<()> {
        let _receipt = self
            .contract
            .updateSl(pair_index, index, new_sl)
            .send()
            .await
            .map_err(|e| OstiumError::contract(format!("Failed to update SL: {}", e)))?
            .get_receipt()
            .await
            .map_err(|e| OstiumError::contract(format!("Failed to get receipt: {}", e)))?;

        Ok(())
    }

    /// Update an open limit order
    pub async fn update_open_limit_order(
        &self,
        pair_index: u16,
        index: u8,
        price: U192,
        tp: U192,
        sl: U192,
    ) -> Result<()> {
        let _receipt = self
            .contract
            .updateOpenLimitOrder(pair_index, index, price, tp, sl)
            .send()
            .await
            .map_err(|e| OstiumError::contract(format!("Failed to update order: {}", e)))?
            .get_receipt()
            .await
            .map_err(|e| OstiumError::contract(format!("Failed to get receipt: {}", e)))?;

        Ok(())
    }

    /// Add collateral to an existing position
    pub async fn top_up_collateral(&self, pair_index: u16, index: u8, amount: U256) -> Result<()> {
        let _receipt = self
            .contract
            .topUpCollateral(pair_index, index, amount)
            .send()
            .await
            .map_err(|e| OstiumError::contract(format!("Failed to add collateral: {}", e)))?
            .get_receipt()
            .await
            .map_err(|e| OstiumError::contract(format!("Failed to get receipt: {}", e)))?;

        Ok(())
    }

    /// Remove collateral from an existing position
    pub async fn remove_collateral(&self, pair_index: u16, index: u8, amount: U256) -> Result<()> {
        let _receipt = self
            .contract
            .removeCollateral(pair_index, index, amount)
            .send()
            .await
            .map_err(|e| OstiumError::contract(format!("Failed to remove collateral: {}", e)))?
            .get_receipt()
            .await
            .map_err(|e| OstiumError::contract(format!("Failed to get receipt: {}", e)))?;

        Ok(())
    }

    /// Set a delegate for trading operations
    pub async fn set_delegate(&self, delegate: Address) -> Result<()> {
        let _receipt = self
            .contract
            .setDelegate(delegate)
            .send()
            .await
            .map_err(|e| OstiumError::contract(format!("Failed to set delegate: {}", e)))?
            .get_receipt()
            .await
            .map_err(|e| OstiumError::contract(format!("Failed to get receipt: {}", e)))?;

        Ok(())
    }

    /// Remove the current delegate
    pub async fn remove_delegate(&self) -> Result<()> {
        let _receipt = self
            .contract
            .removeDelegate()
            .send()
            .await
            .map_err(|e| OstiumError::contract(format!("Failed to remove delegate: {}", e)))?
            .get_receipt()
            .await
            .map_err(|e| OstiumError::contract(format!("Failed to get receipt: {}", e)))?;

        Ok(())
    }

    /// Build unsigned transaction for opening a trade
    pub async fn open_trade_unsigned(
        &self,
        trade: Trade,
        order_type: OpenOrderType,
        slippage_p: U256,
        tx_params: UnsignedTransactionParams,
    ) -> Result<UnsignedTransaction> {
        let sol_trade = OstiumTrading::Trade {
            collateral: trade.collateral,
            openPrice: U192::from(trade.open_price),
            tp: U192::from(trade.tp),
            sl: U192::from(trade.sl),
            trader: trade.trader,
            leverage: trade.leverage,
            pairIndex: trade.pair_index,
            index: trade.index,
            buy: trade.buy,
        };

        let sol_order_type = match order_type {
            OpenOrderType::Market => OstiumTrading::OpenOrderType::MARKET,
            OpenOrderType::Limit => OstiumTrading::OpenOrderType::LIMIT,
            OpenOrderType::Stop => OstiumTrading::OpenOrderType::STOP,
        };

        // Create the function call
        let call = OstiumTrading::openTradeCall {
            t: sol_trade,
            orderType: sol_order_type,
            slippageP: slippage_p,
        };

        self.build_unsigned_transaction_from_call(call, tx_params)
            .await
    }

    /// Build unsigned transaction for closing a trade
    pub async fn close_trade_market_unsigned(
        &self,
        pair_index: u16,
        index: u8,
        close_percentage: u16,
        tx_params: UnsignedTransactionParams,
    ) -> Result<UnsignedTransaction> {
        let call = OstiumTrading::closeTradeMarketCall {
            pairIndex: pair_index,
            index,
            closePercentage: close_percentage,
        };

        self.build_unsigned_transaction_from_call(call, tx_params)
            .await
    }

    /// Build unsigned transaction for canceling a limit order
    pub async fn cancel_open_limit_order_unsigned(
        &self,
        pair_index: u16,
        index: u8,
        tx_params: UnsignedTransactionParams,
    ) -> Result<UnsignedTransaction> {
        let call = OstiumTrading::cancelOpenLimitOrderCall {
            pairIndex: pair_index,
            index,
        };

        self.build_unsigned_transaction_from_call(call, tx_params)
            .await
    }

    /// Build unsigned transaction for updating take profit
    pub async fn update_tp_unsigned(
        &self,
        pair_index: u16,
        index: u8,
        new_tp: U192,
        tx_params: UnsignedTransactionParams,
    ) -> Result<UnsignedTransaction> {
        let call = OstiumTrading::updateTpCall {
            pairIndex: pair_index,
            index,
            newTp: new_tp,
        };

        self.build_unsigned_transaction_from_call(call, tx_params)
            .await
    }

    /// Build unsigned transaction for updating stop loss
    pub async fn update_sl_unsigned(
        &self,
        pair_index: u16,
        index: u8,
        new_sl: U192,
        tx_params: UnsignedTransactionParams,
    ) -> Result<UnsignedTransaction> {
        let call = OstiumTrading::updateSlCall {
            pairIndex: pair_index,
            index,
            newSl: new_sl,
        };

        self.build_unsigned_transaction_from_call(call, tx_params)
            .await
    }

    /// Build unsigned transaction for updating a limit order
    pub async fn update_open_limit_order_unsigned(
        &self,
        pair_index: u16,
        index: u8,
        price: U192,
        tp: U192,
        sl: U192,
        tx_params: UnsignedTransactionParams,
    ) -> Result<UnsignedTransaction> {
        let call = OstiumTrading::updateOpenLimitOrderCall {
            pairIndex: pair_index,
            index,
            price,
            tp,
            sl,
        };

        self.build_unsigned_transaction_from_call(call, tx_params)
            .await
    }

    /// Generic method to build unsigned transactions from sol calls
    async fn build_unsigned_transaction_from_call<C>(
        &self,
        call: C,
        tx_params: UnsignedTransactionParams,
    ) -> Result<UnsignedTransaction>
    where
        C: alloy::sol_types::SolCall,
    {
        // Get the contract address
        let to = *self.contract.address();

        // Get the encoded call data
        let data = call.abi_encode();

        // Get chain ID from provider
        let chain_id = self
            .contract
            .provider()
            .get_chain_id()
            .await
            .map_err(|e| OstiumError::contract(format!("Failed to get chain ID: {}", e)))?;

        // Estimate gas if requested
        let gas_limit = if tx_params.include_gas_estimates {
            // For gas estimation, we can use a simple eth_estimateGas call
            // This is a simplified approach - in production you might want more sophisticated gas estimation
            Some(U256::from(200_000)) // Default gas limit
        } else {
            None
        };

        // Get gas price estimate if requested
        let gas_price = if tx_params.include_gas_estimates {
            match self.contract.provider().get_gas_price().await {
                Ok(price) => Some(U256::from(price)),
                Err(e) => {
                    tracing::warn!("Failed to get gas price: {}", e);
                    None
                }
            }
        } else {
            None
        };

        // Get nonce if requested
        let nonce = if tx_params.include_nonce {
            match self
                .contract
                .provider()
                .get_transaction_count(tx_params.from)
                .await
            {
                Ok(count) => Some(count),
                Err(e) => {
                    tracing::warn!("Failed to get nonce: {}", e);
                    None
                }
            }
        } else {
            None
        };

        Ok(UnsignedTransaction {
            to,
            data,
            value: U256::ZERO, // Contract calls typically don't send ETH
            gas_limit,
            gas_price,
            chain_id,
            nonce,
        })
    }
}