perpl-sdk 0.2.2

Rust SDK for the Perpl decentralized perpetuals exchange
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
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
use alloy::primitives::{B256, U256};
use fastnum::{D64, D256, UD64, UD128};

use super::{ContractVersion, FeeSchedule, account, order, perpetual, position};
use crate::{
    abi::dex::Exchange::{OrderRequest, OrderRequestV2},
    types,
};

/// Exchange state processing events.
///
/// This is a subset of [`crate::abi::dex::Exchange::ExchangeEvents`] covering
/// all state mutations and order request error responses handled by SDK,
/// with numeric system conversions applied.
#[derive(Clone, derive_more::Debug)]
pub enum StateEvents {
    /// Account state updated.
    Account(AccountEvent),

    /// Order request processing error.
    Error(OrderError),

    /// Exchange state or configuration updated.
    Exchange(ExchangeEvent),

    /// Order book state updated.
    Order(OrderEvent),

    /// Perpetual contract state or configuration updated.
    Perpetual(PerpetualEvent),

    /// Position state updated.
    Position(PositionEvent),

    /// Trade happened.
    Trade(types::Trade),
}

/// Account state mutation event.
#[derive(Clone, derive_more::Debug)]
pub struct AccountEvent {
    /// ID of the affected account.
    pub account_id: types::AccountId,

    /// ID of the request resulted in this event, if knonw.
    pub request_id: Option<types::RequestId>,

    /// Type of the event with corresponding details.
    pub r#type: AccountEventType,
}

/// Type of account event with corresponding details.
#[derive(Clone, Copy, derive_more::Debug)]
pub enum AccountEventType {
    /// New account created.
    Created(types::AccountId),

    /// Account frozen/unfrozen.
    Frozen(bool),

    /// Account balance updated.
    BalanceUpdated(#[debug("{_0}")] UD128),

    /// Account locked balance updated.
    LockedBalanceUpdated(#[debug("{_0}")] UD128),

    /// Account fee tier updated, taking effect on the account's next fill.
    /// The tier indexes the [`FeeSchedule`] of every contract the account
    /// trades.
    FeeTierUpdated(types::FeeTier),
}

/// Order request processing error with corresponding reason
#[derive(Clone, derive_more::Debug)]
pub struct OrderError {
    /// ID of the perpetual contract of the order.
    pub perpetual_id: types::PerpetualId,

    /// ID of the account issued the order.
    pub account_id: types::AccountId,

    /// ID of the request resulted in this event.
    pub request_id: types::RequestId,

    /// ID of the order the request was targeted at, if known.
    pub order_id: Option<types::OrderId>,

    /// Failure reason with corresponding details.
    pub r#type: OrderErrorType,
}

/// Type of order request failure with corresponding details.
#[derive(Clone, Copy, derive_more::Debug)]
pub enum OrderErrorType {
    /// Account is frozen.
    AccountFrozen,

    /// Required amount exceeds available balance.
    AmountExceedsAvailableBalance(#[debug("{_0}")] UD128, #[debug("{_1}")] UD128),

    /// Existing close orders mismatch the actual position type and
    /// need to be cancelled before issuing new close orders.
    CancelExistingInvalidCloseOrders,

    /// Close orders can not be changed.
    CantChangeCloseOrder,

    /// Provide new expiration to change expired order.
    ChangeExpiredOrderNeedsNewExpiry,

    /// Close order size exceeds position size.
    CloseOrderExceedsPosition,

    /// Close order side mismatches position type.
    CloseOrderPositionMismatch,

    /// Perpetual contract is not operational.
    ContractNotOperational,

    /// Post-only order crosses the book.
    CrossesBook,

    /// Current block exceeds last execution block specified for the order.
    ExceedsLastExecutionBlock,

    /// Immediate-or-cancel order was not completely filled.
    ImmediateOrCancelExecuted,

    /// Available account balance can not cover recycling fee payment.
    InsuficientFundsForRecycleFee,

    /// Current block exceeds expiration block specified for the order.
    InvalidExpiryBlock,

    /// Specified order ID is out of range.
    InvalidOrderId,

    /// Failed to settle maker order.
    MakerOrderSettlementFailed,

    /// Maximum number of matches reached for the taker order.
    MaxMatchesReached,

    /// Account reached limit of orders to post.
    MaximumAccountOrders,

    /// Order does not exist.
    OrderDoesNotExist,

    /// Builder-code order extension failed a recoverable decode check (unknown
    /// envelope version, or a builder field out of range) on a batched or
    /// forwarded V2 request, so this single order was skipped while the rest of
    /// the batch proceeded.
    OrderExtensionRejected,

    /// Order posting failed with status.
    OrderPostFailed(u16),

    /// Settlement of the order will render perpetual contract insolvent.
    OrderSettlementImpliesInsolvent,

    /// Size of close order exceeds remaining position size.
    OrderSizeExceedsAvailableSize,

    /// Order to be posted is under minimum amount.
    PostOrderUnderMinimum,

    /// Specified order price is out of range.
    PriceOutOfRange,

    /// Specified order size is out of range.
    SizeOutOfRange,

    /// Maximum PnL slippage value exceeds maximum of 65535
    ValueExceedsMaximum,

    /// Another account owns the order.
    WrongAccountForOrder,
}

// A `FeeSchedule` carries 16 rates, dwarfing the scalar variants. Boxing it
// would only move an allocation onto a path that is not hot - fee changes are
// rare - at the cost of every consumer's pattern match.
#[allow(clippy::large_enum_variant)]
#[derive(Clone, derive_more::Debug)]
pub enum ExchangeEvent {
    /// Deployed contract version stamped by an upgrade, along with the feature
    /// set it resolves to.
    ContractVersionUpdated(ContractVersion),

    /// A fee schedule in [`super::Exchange::fee_schedules`] was rewritten,
    /// under the key it is registered by ([`FeeSchedule::key`]).
    ///
    /// Every tracked perpetual contract *currently pointing at* that schedule
    /// gets a corresponding [`PerpetualEventType::FeeScheduleUpdated`];
    /// rewriting a schedule never repoints a contract at it, only
    /// `PerpFeeSchedIdSet` does.
    FeeScheduleUpdated(FeeSchedule),

    /// Exchange halted/unhalted.
    Halted(bool),

    /// Minimal posting amount updated.
    MinPostUpdated(#[debug("{_0}")] UD128),

    /// Minimal settlement amount updated.
    MinSettleUpdated(#[debug("{_0}")] UD128),

    /// Recycling fee updated.
    RecycleFeeUpdated(#[debug("{_0}")] UD128),
}

/// Order book state mutation event.
#[derive(Clone, derive_more::Debug)]
pub struct OrderEvent {
    /// ID of the perpetual contract of the order.
    pub perpetual_id: types::PerpetualId,

    /// ID of the account issued the order.
    pub account_id: types::AccountId,

    /// ID of the request resulted in this event, if knonw.
    pub request_id: Option<types::RequestId>,

    /// Client order ID, if knonw.
    pub client_order_id: Option<types::RequestId>,

    /// ID of the order affected, if knonw.
    pub order_id: Option<types::OrderId>,

    /// Builder the order is attributed to, with the fee rate it charges, if
    /// any.
    ///
    /// Available on contract v1.1.7.4+ for orders whose placement was observed
    /// in the event stream or recovered from the initial snapshot.
    pub builder: Option<types::BuilderAttribution>,

    /// Type of the event with corresponding details.
    pub r#type: OrderEventType,
}

/// Type of order event with corresponding details.
#[derive(Clone, Copy, derive_more::Debug)]
pub enum OrderEventType {
    /// Order filled.
    /// For maker orders this event is paired with [`OrderEventType::Updated`]
    /// or [`OrderEventType::Removed`].
    Filled {
        #[debug("{fill_price}")]
        fill_price: UD64,
        #[debug("{fill_size}")]
        fill_size: UD64,
        #[debug("{fee}")]
        fee: UD64, // Precision of SC calculations is limited to 5 decimals.
        /// Portion of `fee` earned by the builder the order is attributed to,
        /// routed entirely to the protocol balance and paid out off-chain.
        ///
        /// Included in `fee`, so consumers must not add it on top. Always zero
        /// on close/decrease and liquidation fills, and on contracts without
        /// builder attribution - a non-zero
        /// [`OrderEvent::builder`] does not imply a non-zero fee here.
        #[debug("{builder_fee}")]
        builder_fee: UD64,
        is_maker: bool,
    },

    /// Order placed to the book.
    Placed {
        r#type: types::OrderType,
        #[debug("{price}")]
        price: UD64,
        #[debug("{size}")]
        size: UD64,
        expiry_block: u64,
        #[debug("{leverage}")]
        leverage: UD64,
        post_only: bool,
        fill_or_kill: bool,
        immediate_or_cancel: bool,
    },

    /// Order removed from the book.
    Removed,

    /// Order in the book updated.
    Updated {
        #[debug("{:?}", price.map(|v| format!("{v}")))]
        price: Option<UD64>,
        #[debug("{:?}", size.map(|v| format!("{v}")))]
        size: Option<UD64>,
        expiry_block: Option<u64>,
    },
}

/// Perpetual contract state or configuration mutation event.
#[derive(Clone, derive_more::Debug)]
pub struct PerpetualEvent {
    /// ID of the affected perpetual contract.
    pub perpetual_id: types::PerpetualId,

    /// Type of the event with corresponding details.
    pub r#type: PerpetualEventType,
}

/// Type of perpetual event with corresponding details.
// See the note on `ExchangeEvent` about the `FeeSchedule` variant's size.
#[allow(clippy::large_enum_variant)]
#[derive(Clone, Copy, derive_more::Debug)]
pub enum PerpetualEventType {
    /// Perpetual contract being added
    Added,

    /// Funding event occured and rate updated.
    FundingEvent {
        #[debug("{rate}")]
        rate: D64,
        #[debug("{payment_per_unit}")]
        payment_per_unit: D256,
    },

    /// Fee schedule of the contract updated, taking effect on its next fill.
    ///
    /// Emitted when the contract's own schedule is rewritten, when it is
    /// repointed at another schedule ([`FeeSchedule::key`] changed), and when
    /// the exchange-wide schedule it points at is rewritten.
    FeeScheduleUpdated(FeeSchedule),

    /// Funding sum scaling exponent updated. The exponent `e` defines the
    /// divider `10^e` applied when interpreting on-chain funding sums and
    /// per-unit funding payments for premium PnL calculations.
    FundingSumScalingExpUpdated(u8),

    /// Initial margin requirement updated.
    InitialMarginFractionUpdated(#[debug("{_0}")] UD64),

    /// Last price updated.
    LastPriceUpdated(#[debug("{_0}")] UD64),

    /// Maintenance margin requirement updated.
    MaintenanceMarginFractionUpdated(#[debug("{_0}")] UD64),

    /// Mark price updated.
    MarkPriceUpdated(#[debug("{_0}")] UD64),

    /// Base (fee tier 0) maker fee updated.
    ///
    /// Deprecated: only replayed from pre-v1.1.7.4 history, where fees were a
    /// single per-contract pair. Current contracts report every fee change as
    /// [`PerpetualEventType::FeeScheduleUpdated`].
    MakerFeeUpdated(#[debug("{_0}")] UD64),

    /// Open interest updated.
    OpenInterestUpdated(#[debug("{_0}")] UD128),

    /// Oracle configuration updated.
    OracleConfigurationUpdated { is_used: bool, feed_id: B256 },

    /// Oracle price updated.
    OraclePriceUpdated(#[debug("{_0}")] UD64),

    /// Perpetual contract paused/unpaused.
    Paused(bool),

    /// Base (fee tier 0) taker fee updated.
    ///
    /// Deprecated, see [`PerpetualEventType::MakerFeeUpdated`].
    TakerFeeUpdated(#[debug("{_0}")] UD64),
}

/// Position state mutation event.
#[derive(Clone, derive_more::Debug)]
pub struct PositionEvent {
    /// ID of the perpetual contract of the position.
    pub perpetual_id: types::PerpetualId,

    /// ID of the account holding the position.
    pub account_id: types::AccountId,

    /// ID of the order request resulted in this event,
    /// if applicable.
    pub request_id: Option<types::RequestId>,

    /// Type of the event with corresponding details.
    pub r#type: PositionEventType,
}

/// Type of position event with corresponding details.
#[derive(Clone, Copy, derive_more::Debug)]
pub enum PositionEventType {
    /// Position closed.
    Closed {
        r#type: position::PositionType,
        #[debug("{entry_price}")]
        entry_price: UD64,
        #[debug("{exit_price}")]
        exit_price: UD64,
        #[debug("{size}")]
        size: UD64,
        #[debug("{delta_pnl}")]
        delta_pnl: D256,
        #[debug("{premium_pnl}")]
        premium_pnl: D256,
    },

    /// Position collateral decreased.
    CollateralDecreased {
        #[debug("{prev_entry_price}")]
        prev_entry_price: UD64,
        #[debug("{new_entry_price}")]
        new_entry_price: UD64,
        #[debug("{deposit}")]
        deposit: UD128,
    },

    /// Position decreased.
    Decreased {
        #[debug("{prev_size}")]
        prev_size: UD64,
        #[debug("{new_size}")]
        new_size: UD64,
        #[debug("{deposit}")]
        deposit: UD128,
        #[debug("{delta_pnl}")]
        delta_pnl: D256,
        #[debug("{premium_pnl}")]
        premium_pnl: D256,
    },

    /// Position deleveraged.
    Deleveraged {
        force_close: bool,
        r#type: position::PositionType,
        #[debug("{entry_price}")]
        entry_price: UD64,
        #[debug("{exit_price}")]
        exit_price: UD64,
        #[debug("{prev_size}")]
        prev_size: UD64,
        #[debug("{new_size}")]
        new_size: UD64,
        #[debug("{deposit}")]
        deposit: UD128,
        #[debug("{delta_pnl}")]
        delta_pnl: D256,
        #[debug("{premium_pnl}")]
        premium_pnl: D256,
    },

    /// Position deposit(collateral) updated.
    DepositUpdated(#[debug("{_0}")] UD128),

    /// Position increased.
    Increased {
        #[debug("{entry_price}")]
        entry_price: UD64,
        #[debug("{prev_size}")]
        prev_size: UD64,
        #[debug("{new_size}")]
        new_size: UD64,
        #[debug("{deposit}")]
        deposit: UD128,
    },

    /// Position inverted.
    Inverted {
        r#type: position::PositionType,
        #[debug("{entry_price}")]
        entry_price: UD64,
        #[debug("{prev_size}")]
        prev_size: UD64,
        #[debug("{new_size}")]
        new_size: UD64,
        #[debug("{deposit}")]
        deposit: UD128,
        #[debug("{delta_pnl}")]
        delta_pnl: D256,
        #[debug("{premium_pnl}")]
        premium_pnl: D256,
    },

    /// Position liquidated.
    Liquidated {
        r#type: position::PositionType,
        #[debug("{entry_price}")]
        entry_price: UD64,
        #[debug("{exit_price}")]
        exit_price: UD64,
        #[debug("{prev_size}")]
        prev_size: UD64,
        #[debug("{liquidated_size}")]
        liquidated_size: UD64,
        #[debug("{new_size}")]
        new_size: UD64,
        #[debug("{deposit}")]
        deposit: UD128,
        #[debug("{delta_pnl}")]
        delta_pnl: D256,
        #[debug("{premium_pnl}")]
        premium_pnl: D256,
    },

    /// Position maintenance margin requirement updated due
    /// to updated maintenane margin fraction.
    MaintenanceMarginUpdated(#[debug("{_0}")] UD128),

    /// Position opened.
    Opened {
        r#type: position::PositionType,
        #[debug("{entry_price}")]
        entry_price: UD64,
        #[debug("{size}")]
        size: UD64,
        #[debug("{deposit}")]
        deposit: UD128,
    },

    /// Position unrealized PnL updated.
    UnrealizedPnLUpdated {
        #[debug("{pnl}")]
        pnl: D256,
        #[debug("{delta_pnl}")]
        delta_pnl: D256,
        #[debug("{premium_pnl}")]
        premium_pnl: D256,
    },

    /// Position unwound.
    Unwound {
        r#type: position::PositionType,
        #[debug("{entry_price}")]
        entry_price: UD64,
        #[debug("{exit_price}")]
        exit_price: UD64,
        #[debug("{size}")]
        size: UD64,
        #[debug("{fair_market_value}")]
        fair_market_value: D256,
        #[debug("{payment}")]
        payment: UD128,
    },
}

impl StateEvents {
    pub fn as_account_event(&self) -> Option<AccountEvent> {
        if let StateEvents::Account(account_event) = self {
            Some(account_event.clone())
        } else {
            None
        }
    }

    pub fn as_error(&self) -> Option<OrderError> {
        if let StateEvents::Error(error_event) = self { Some(error_event.clone()) } else { None }
    }

    pub fn as_order_event(&self) -> Option<OrderEvent> {
        if let StateEvents::Order(order_event) = self { Some(order_event.clone()) } else { None }
    }

    pub fn as_exchange_event(&self) -> Option<ExchangeEvent> {
        if let StateEvents::Exchange(exchange_event) = self {
            Some(exchange_event.clone())
        } else {
            None
        }
    }

    pub fn as_perpetual_event(&self) -> Option<PerpetualEvent> {
        if let StateEvents::Perpetual(perpetual_event) = self {
            Some(perpetual_event.clone())
        } else {
            None
        }
    }

    pub fn as_position_event(&self) -> Option<PositionEvent> {
        if let StateEvents::Position(position_event) = self {
            Some(position_event.clone())
        } else {
            None
        }
    }

    pub fn as_trade(&self) -> Option<types::Trade> {
        if let StateEvents::Trade(trade) = self { Some(trade.clone()) } else { None }
    }

    pub(crate) fn account(
        acc: &account::Account,
        ctx: &Option<OrderContext>,
        r#type: AccountEventType,
    ) -> Self {
        Self::Account(AccountEvent {
            account_id: acc.id(),
            request_id: ctx.as_ref().map(|c| c.request_id),
            r#type,
        })
    }

    pub(crate) fn order(
        perp: &perpetual::Perpetual,
        ord: &order::Order,
        ctx: &Option<OrderContext>,
        r#type: OrderEventType,
    ) -> Self {
        Self::Order(OrderEvent {
            perpetual_id: perp.id(),
            account_id: ord.account_id(),
            request_id: ctx.as_ref().map(|c| c.request_id),
            client_order_id: ord.client_order_id(),
            order_id: Some(ord.order_id()),
            builder: ord.builder(),
            r#type,
        })
    }

    pub(crate) fn order_error(ctx: &OrderContext, r#type: OrderErrorType) -> StateEvents {
        Self::Error(OrderError {
            perpetual_id: ctx.perpetual_id,
            account_id: ctx.account_id,
            request_id: ctx.request_id,
            order_id: ctx.order_id,
            r#type,
        })
    }

    pub(crate) fn affected_order_error(
        ctx: &OrderContext,
        ord: &order::Order,
        r#type: OrderErrorType,
    ) -> StateEvents {
        Self::Error(OrderError {
            perpetual_id: ctx.perpetual_id,
            account_id: ord.account_id(),
            request_id: ctx.request_id,
            order_id: Some(ord.order_id()),
            r#type,
        })
    }

    pub(crate) fn perpetual(
        perp: &perpetual::Perpetual,
        r#type: PerpetualEventType,
    ) -> StateEvents {
        Self::Perpetual(PerpetualEvent { perpetual_id: perp.id(), r#type })
    }

    pub(crate) fn position(
        pos: &position::Position,
        ctx: &Option<OrderContext>,
        r#type: PositionEventType,
    ) -> Self {
        Self::Position(PositionEvent {
            perpetual_id: pos.perpetual_id(),
            account_id: pos.account_id(),
            request_id: ctx.as_ref().map(|c| c.request_id),
            r#type,
        })
    }

    pub(crate) fn trade(ctx: &OrderContext, taker_fee: UD64, taker_builder_fee: UD64) -> Self {
        Self::Trade(types::Trade {
            perpetual_id: ctx.perpetual_id,
            taker_account_id: ctx.account_id,
            taker_request_id: ctx.request_id,
            taker_side: ctx.r#type.try_side().expect("order type with side"),
            taker_fee,
            taker_builder: ctx.builder,
            taker_builder_fee,
            maker_fills: ctx.maker_fills.clone(),
        })
    }
}

/// Order request context.
#[derive(Debug)]
pub(crate) struct OrderContext {
    pub(crate) perpetual_id: types::PerpetualId,
    pub(crate) account_id: types::AccountId,
    pub(crate) request_id: types::RequestId,
    pub(crate) order_id: Option<types::OrderId>,
    pub(crate) r#type: types::RequestType,
    pub(crate) price: U256,
    pub(crate) expiry_block: u64,
    pub(crate) leverage: U256,
    pub(crate) post_only: bool,
    pub(crate) fill_or_kill: bool,
    pub(crate) immediate_or_cancel: bool,
    pub(crate) builder: Option<types::BuilderAttribution>,
    pub(crate) maker_fills: Vec<types::MakerFill>,
    pub(crate) clearing_remaining_order: bool,
    pub(crate) position_closed_at_log_index: Option<u64>,
}

/// Order ID of a request, `None` for trigger order requests - their order IDs
/// might exceed `u16::MAX` and they are not supported by the SDK yet.
fn request_order_id(order_id: U256) -> Option<types::OrderId> {
    if order_id <= U256::from(u16::MAX) {
        std::num::NonZeroU16::new(order_id.to::<u16>())
    } else {
        None
    }
}

impl From<&OrderRequest> for OrderContext {
    fn from(value: &OrderRequest) -> Self {
        Self {
            perpetual_id: value.perpId.to(),
            account_id: value.accountId.to(),
            request_id: value.orderDescId.to(),
            order_id: request_order_id(value.orderId),
            r#type: value.orderType.into(),
            price: value.pricePNS,
            expiry_block: value.expiryBlock.to(),
            leverage: value.leverageHdths,
            post_only: value.postOnly,
            fill_or_kill: value.fillOrKill,
            immediate_or_cancel: value.immediateOrCancel,
            // V1 entrypoints cannot carry builder attribution
            builder: None,
            maker_fills: vec![],
            clearing_remaining_order: false,
            position_closed_at_log_index: None,
        }
    }
}

impl From<&OrderRequestV2> for OrderContext {
    fn from(value: &OrderRequestV2) -> Self {
        Self {
            perpetual_id: value.perpId.to(),
            account_id: value.accountId.to(),
            request_id: value.orderDescId.to(),
            order_id: request_order_id(value.orderId),
            r#type: value.orderType.into(),
            price: value.pricePNS,
            expiry_block: value.expiryBlock.to(),
            leverage: value.leverageHdths,
            post_only: value.postOnly,
            fill_or_kill: value.fillOrKill,
            immediate_or_cancel: value.immediateOrCancel,
            // Attribution is not duplicated as event fields: it is recovered by
            // decoding the raw envelope the request carried. An envelope the
            // contract itself rejected leaves no attribution, and the contract
            // reports the rejection separately - either by reverting or with
            // `OrderExtensionRejected`.
            builder: types::BuilderAttribution::decode(&value.extension)
                .ok()
                .flatten(),
            maker_fills: vec![],
            clearing_remaining_order: false,
            position_closed_at_log_index: None,
        }
    }
}