strike-sdk 0.2.14

Rust SDK for Strike prediction markets on BNB Chain
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
460
461
//! Order placement, cancellation, and replacement on the OrderBook contract.

use alloy::primitives::{Address, Bytes, U256};
use alloy::providers::DynProvider;
use alloy::rpc::types::TransactionRequest;
use alloy::sol_types::{SolCall, SolEvent};
use std::sync::Arc;
use tokio::sync::Mutex;
use tracing::info;

use crate::chain::send_tx;
use crate::config::StrikeConfig;
use crate::contracts::OrderBook;
use crate::error::{Result, StrikeError};
use crate::indexer::types::Market as IndexerMarket;
use crate::nonce::NonceSender;
use crate::types::{AmendOrderParam, OrderParam, PlacedOrder, Side};

/// Client for order operations on the OrderBook contract.
pub struct OrdersClient<'a> {
    provider: &'a DynProvider,
    signer_addr: Option<Address>,
    config: &'a StrikeConfig,
    nonce_sender: Option<Arc<Mutex<NonceSender>>>,
}

impl<'a> OrdersClient<'a> {
    pub(crate) fn new(
        provider: &'a DynProvider,
        signer_addr: Option<Address>,
        config: &'a StrikeConfig,
        nonce_sender: Option<Arc<Mutex<NonceSender>>>,
    ) -> Self {
        Self {
            provider,
            signer_addr,
            config,
            nonce_sender,
        }
    }

    fn require_wallet(&self) -> Result<Address> {
        self.signer_addr.ok_or(StrikeError::NoWallet)
    }

    /// Place one or more orders on a market in a single transaction.
    ///
    /// Uses `placeOrders(orderbookMarketId, OrderParam[])`. Returns placed orders with
    /// their assigned on-chain IDs (parsed from `OrderPlaced` events in the receipt).
    pub async fn place(
        &self,
        orderbook_market_id: u64,
        params: &[OrderParam],
    ) -> Result<Vec<PlacedOrder>> {
        self.require_wallet()?;

        let contract_params: Vec<OrderBook::OrderParam> =
            params.iter().map(|p| p.to_contract_param()).collect();

        let calldata = OrderBook::placeOrdersCall {
            marketId: U256::from(orderbook_market_id),
            params: contract_params,
        }
        .abi_encode();

        let order_count = params.len();
        let gas_limit = gas_limit_place_orders(order_count);
        let mut tx = TransactionRequest::default()
            .to(self.config.addresses.order_book)
            .input(Bytes::from(calldata).into());
        tx.gas = Some(gas_limit);

        let pending = send_tx(self.provider, &self.nonce_sender, tx).await?;

        let tx_hash = *pending.tx_hash();
        info!(orderbook_market_id, order_count, gas_limit, tx = %tx_hash, "placeOrders tx sent");

        let receipt = pending
            .get_receipt()
            .await
            .map_err(|e| StrikeError::Contract(e.to_string()))?;

        if !receipt.status() {
            return Err(StrikeError::Contract(format!(
                "placeOrders reverted (orderbook_market_id={orderbook_market_id}, tx={tx_hash}, gas_used={})",
                receipt.gas_used
            )));
        }

        let placed = parse_placed_orders(&receipt, orderbook_market_id);
        info!(
            orderbook_market_id,
            tx = %tx_hash,
            gas_limit,
            gas_used = receipt.gas_used,
            gas_utilization_pct = %format_gas_utilization_pct(receipt.gas_used, gas_limit),
            placed = placed.len(),
            "placeOrders confirmed"
        );

        Ok(placed)
    }

    /// Place one or more orders using an indexer market object.
    ///
    /// This resolves the tradable `orderbook_market_id` and fails closed if the
    /// indexer response only exposed the legacy factory ID.
    pub async fn place_market(
        &self,
        market: &IndexerMarket,
        params: &[OrderParam],
    ) -> Result<Vec<PlacedOrder>> {
        self.place(market.tradable_market_id()?, params).await
    }

    /// Atomically cancel existing orders and place new ones via `replaceOrders`.
    ///
    /// Single transaction: cancels happen first, then placements, with net USDT
    /// settlement. Zero empty-book time.
    pub async fn replace(
        &self,
        cancel_ids: &[U256],
        orderbook_market_id: u64,
        params: &[OrderParam],
    ) -> Result<Vec<PlacedOrder>> {
        self.require_wallet()?;

        let contract_params: Vec<OrderBook::OrderParam> =
            params.iter().map(|p| p.to_contract_param()).collect();

        let calldata = OrderBook::replaceOrdersCall {
            cancelIds: cancel_ids.to_vec(),
            marketId: U256::from(orderbook_market_id),
            params: contract_params,
        }
        .abi_encode();

        let gas_limit = gas_limit_replace_orders(cancel_ids.len(), params.len());
        let mut tx = TransactionRequest::default()
            .to(self.config.addresses.order_book)
            .input(Bytes::from(calldata).into());
        tx.gas = Some(gas_limit);

        let pending = send_tx(self.provider, &self.nonce_sender, tx).await?;

        let tx_hash = *pending.tx_hash();
        info!(
            orderbook_market_id,
            cancels = cancel_ids.len(),
            places = params.len(),
            gas_limit,
            tx = %tx_hash,
            "replaceOrders tx sent"
        );

        let receipt = pending
            .get_receipt()
            .await
            .map_err(|e| StrikeError::Contract(e.to_string()))?;

        if !receipt.status() {
            return Err(StrikeError::Contract(format!(
                "replaceOrders reverted (orderbook_market_id={orderbook_market_id}, tx={tx_hash}, gas_used={})",
                receipt.gas_used
            )));
        }

        let placed = parse_placed_orders(&receipt, orderbook_market_id);
        info!(
            orderbook_market_id,
            tx = %tx_hash,
            gas_limit,
            gas_used = receipt.gas_used,
            gas_utilization_pct = %format_gas_utilization_pct(receipt.gas_used, gas_limit),
            cancelled = cancel_ids.len(),
            placed = placed.len(),
            "replaceOrders confirmed"
        );

        Ok(placed)
    }

    /// Replace one or more orders using an indexer market object.
    ///
    /// This resolves the tradable `orderbook_market_id` and fails closed if the
    /// indexer response only exposed the legacy factory ID.
    pub async fn replace_market(
        &self,
        cancel_ids: &[U256],
        market: &IndexerMarket,
        params: &[OrderParam],
    ) -> Result<Vec<PlacedOrder>> {
        self.replace(cancel_ids, market.tradable_market_id()?, params)
            .await
    }

    /// Amend one or more live GTC buy-side orders in place via `amendOrders`.
    ///
    /// Order IDs are preserved on success. Contract-side restrictions still apply:
    /// only live GTC bid/ask orders can be amended, and active orders cannot be
    /// amended into resting orders.
    pub async fn amend(&self, orderbook_market_id: u64, params: &[AmendOrderParam]) -> Result<()> {
        self.require_wallet()?;

        if params.is_empty() {
            return Ok(());
        }

        let contract_params: Vec<OrderBook::AmendOrderParam> =
            params.iter().map(|p| p.to_contract_param()).collect();

        let calldata = OrderBook::amendOrdersCall {
            marketId: U256::from(orderbook_market_id),
            params: contract_params,
        }
        .abi_encode();

        let gas_limit = gas_limit_amend_orders(params.len());
        let mut tx = TransactionRequest::default()
            .to(self.config.addresses.order_book)
            .input(Bytes::from(calldata).into());
        tx.gas = Some(gas_limit);

        let pending = send_tx(self.provider, &self.nonce_sender, tx).await?;

        let tx_hash = *pending.tx_hash();
        info!(
            orderbook_market_id,
            amendments = params.len(),
            gas_limit,
            tx = %tx_hash,
            "amendOrders tx sent"
        );

        let receipt = pending
            .get_receipt()
            .await
            .map_err(|e| StrikeError::Contract(e.to_string()))?;

        if !receipt.status() {
            return Err(StrikeError::Contract(format!(
                "amendOrders reverted (orderbook_market_id={orderbook_market_id}, tx={tx_hash}, gas_used={})",
                receipt.gas_used
            )));
        }

        let amended = parse_amended_order_ids(&receipt, orderbook_market_id);
        info!(
            orderbook_market_id,
            tx = %tx_hash,
            gas_limit,
            gas_used = receipt.gas_used,
            gas_utilization_pct = %format_gas_utilization_pct(receipt.gas_used, gas_limit),
            amended = amended.len(),
            "amendOrders confirmed"
        );

        Ok(())
    }

    /// Amend one or more live orders using an indexer market object.
    pub async fn amend_market(
        &self,
        market: &IndexerMarket,
        params: &[AmendOrderParam],
    ) -> Result<()> {
        self.amend(market.tradable_market_id()?, params).await
    }

    /// Cancel one or more orders in a single transaction via `cancelOrders`.
    ///
    /// Skips already-cancelled orders on-chain (no revert).
    pub async fn cancel(&self, order_ids: &[U256]) -> Result<()> {
        self.require_wallet()?;

        if order_ids.is_empty() {
            return Ok(());
        }

        let calldata = OrderBook::cancelOrdersCall {
            orderIds: order_ids.to_vec(),
        }
        .abi_encode();

        let gas_limit = gas_limit_cancel_orders(order_ids.len());
        let mut tx = TransactionRequest::default()
            .to(self.config.addresses.order_book)
            .input(Bytes::from(calldata).into());
        tx.gas = Some(gas_limit);

        let pending = send_tx(self.provider, &self.nonce_sender, tx).await?;

        let tx_hash = *pending.tx_hash();
        info!(count = order_ids.len(), gas_limit, tx = %tx_hash, "cancelOrders tx sent");

        let receipt = pending
            .get_receipt()
            .await
            .map_err(|e| StrikeError::Contract(e.to_string()))?;

        info!(
            tx = %tx_hash,
            gas_limit,
            gas_used = receipt.gas_used,
            gas_utilization_pct = %format_gas_utilization_pct(receipt.gas_used, gas_limit),
            count = order_ids.len(),
            "cancelOrders confirmed"
        );
        Ok(())
    }

    /// Cancel a single order via `cancelOrder`.
    pub async fn cancel_one(&self, order_id: U256) -> Result<()> {
        self.require_wallet()?;

        let calldata = OrderBook::cancelOrderCall { orderId: order_id }.abi_encode();
        let gas_limit = gas_limit_cancel_order();
        let mut tx = TransactionRequest::default()
            .to(self.config.addresses.order_book)
            .input(Bytes::from(calldata).into());
        tx.gas = Some(gas_limit);

        let pending = send_tx(self.provider, &self.nonce_sender, tx).await?;

        let tx_hash = *pending.tx_hash();
        info!(order_id = %order_id, gas_limit, tx = %tx_hash, "cancelOrder tx sent");
        let receipt = pending
            .get_receipt()
            .await
            .map_err(|e| StrikeError::Contract(e.to_string()))?;

        info!(
            order_id = %order_id,
            tx = %tx_hash,
            gas_limit,
            gas_used = receipt.gas_used,
            gas_utilization_pct = %format_gas_utilization_pct(receipt.gas_used, gas_limit),
            "cancelOrder confirmed"
        );
        Ok(())
    }
}

fn gas_limit_place_orders(order_count: usize) -> u64 {
    800_000 + 250_000 * (order_count.saturating_sub(1) as u64)
}

fn gas_limit_amend_orders(order_count: usize) -> u64 {
    300_000 + 140_000 * order_count as u64
}

fn gas_limit_replace_orders(cancel_count: usize, place_count: usize) -> u64 {
    300_000 + 120_000 * cancel_count as u64 + 180_000 * place_count as u64
}

fn gas_limit_cancel_orders(order_count: usize) -> u64 {
    120_000 + 70_000 * order_count as u64
}

fn gas_limit_cancel_order() -> u64 {
    250_000
}

fn format_gas_utilization_pct(gas_used: u64, gas_limit: u64) -> String {
    if gas_limit == 0 {
        return "0.0".to_string();
    }

    format!("{:.1}", gas_used as f64 / gas_limit as f64 * 100.0)
}

/// Parse `OrderPlaced` and `OrderResting` events from a transaction receipt.
/// Resting orders are placed far from the clearing price and emit `OrderResting`
/// instead of `OrderPlaced`, but they're still live orders that need tracking.
fn parse_placed_orders(
    receipt: &alloy::rpc::types::TransactionReceipt,
    orderbook_market_id: u64,
) -> Vec<PlacedOrder> {
    let mut placed = Vec::new();
    for log in receipt.inner.logs() {
        if let Ok(event) = OrderBook::OrderPlaced::decode_log(&log.inner) {
            placed.push(PlacedOrder {
                order_id: event.orderId,
                side: Side::try_from(event.side).unwrap_or(Side::Bid),
                market_id: orderbook_market_id,
                orderbook_market_id,
            });
        } else if let Ok(event) = OrderBook::OrderResting::decode_log(&log.inner) {
            // OrderResting doesn't include side — read from on-chain order storage.
            // Use Bid as fallback; the quoter cancels all tracked IDs regardless of side.
            placed.push(PlacedOrder {
                order_id: event.orderId,
                side: Side::Bid,
                market_id: orderbook_market_id,
                orderbook_market_id,
            });
        }
    }
    placed
}

/// Parse `OrderAmended` events from a transaction receipt.
fn parse_amended_order_ids(
    receipt: &alloy::rpc::types::TransactionReceipt,
    orderbook_market_id: u64,
) -> Vec<U256> {
    let mut amended = Vec::new();
    for log in receipt.inner.logs() {
        if let Ok(event) = OrderBook::OrderAmended::decode_log(&log.inner) {
            if event.marketId == U256::from(orderbook_market_id) {
                amended.push(event.orderId);
            }
        }
    }
    amended
}

#[cfg(test)]
mod tests {
    use super::{
        gas_limit_amend_orders, gas_limit_cancel_order, gas_limit_cancel_orders,
        gas_limit_place_orders, gas_limit_replace_orders,
    };

    #[test]
    fn gas_limit_place_orders_formula() {
        assert_eq!(gas_limit_place_orders(0), 800_000);
        assert_eq!(gas_limit_place_orders(1), 800_000);
        assert_eq!(gas_limit_place_orders(2), 1_050_000);
        assert_eq!(gas_limit_place_orders(3), 1_300_000);
        assert_eq!(gas_limit_place_orders(4), 1_550_000);
    }

    #[test]
    fn gas_limit_replace_orders_formula() {
        assert_eq!(gas_limit_replace_orders(0, 0), 300_000);
        assert_eq!(gas_limit_replace_orders(1, 0), 420_000);
        assert_eq!(gas_limit_replace_orders(0, 1), 480_000);
        assert_eq!(gas_limit_replace_orders(2, 3), 1_080_000);
    }

    #[test]
    fn gas_limit_amend_orders_formula() {
        assert_eq!(gas_limit_amend_orders(0), 300_000);
        assert_eq!(gas_limit_amend_orders(1), 440_000);
        assert_eq!(gas_limit_amend_orders(2), 580_000);
        assert_eq!(gas_limit_amend_orders(4), 860_000);
    }

    #[test]
    fn gas_limit_cancel_orders_formula() {
        assert_eq!(gas_limit_cancel_orders(0), 120_000);
        assert_eq!(gas_limit_cancel_orders(1), 190_000);
        assert_eq!(gas_limit_cancel_orders(3), 330_000);
    }

    #[test]
    fn gas_limit_cancel_order_formula() {
        assert_eq!(gas_limit_cancel_order(), 250_000);
    }
}