Skip to main content

polyoxide_clob/
types.rs

1use std::fmt;
2
3use alloy::primitives::Address;
4use serde::{Deserialize, Serialize};
5use thiserror::Error;
6
7/// Error when parsing a tick size from an invalid value
8#[derive(Error, Debug, Clone, PartialEq)]
9#[error("invalid tick size: {0}. Valid values are 0.1, 0.01, 0.001, or 0.0001")]
10pub struct ParseTickSizeError(String);
11
12/// Side of an order (buy or sell).
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
14#[serde(rename_all = "UPPERCASE")]
15pub enum OrderSide {
16    Buy,
17    Sell,
18}
19
20impl OrderSide {
21    /// Returns the uppercase string representation ("BUY" / "SELL") for API queries.
22    pub fn as_str(&self) -> &'static str {
23        match self {
24            Self::Buy => "BUY",
25            Self::Sell => "SELL",
26        }
27    }
28}
29
30impl Serialize for OrderSide {
31    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
32    where
33        S: serde::Serializer,
34    {
35        match self {
36            Self::Buy => serializer.serialize_str("BUY"),
37            Self::Sell => serializer.serialize_str("SELL"),
38        }
39    }
40}
41
42impl fmt::Display for OrderSide {
43    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44        match self {
45            Self::Buy => write!(f, "0"),
46            Self::Sell => write!(f, "1"),
47        }
48    }
49}
50
51/// Order type/kind
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
53#[serde(rename_all = "UPPERCASE")]
54pub enum OrderKind {
55    /// Good-till-Cancelled
56    Gtc,
57    /// Fill-or-Kill
58    Fok,
59    /// Good-till-Date
60    Gtd,
61    /// Fill-and-Kill
62    Fak,
63}
64
65impl fmt::Display for OrderKind {
66    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67        match self {
68            Self::Gtc => write!(f, "GTC"),
69            Self::Fok => write!(f, "FOK"),
70            Self::Gtd => write!(f, "GTD"),
71            Self::Fak => write!(f, "FAK"),
72        }
73    }
74}
75
76/// Signature type for order signing (EOA, Proxy, or Gnosis Safe).
77#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
78pub enum SignatureType {
79    #[default]
80    Eoa = 0,
81    PolyProxy = 1,
82    PolyGnosisSafe = 2,
83}
84
85impl SignatureType {
86    /// Returns true if the signature type indicates a proxy wallet
87    pub fn is_proxy(&self) -> bool {
88        matches!(self, Self::PolyProxy | Self::PolyGnosisSafe)
89    }
90}
91
92impl Serialize for SignatureType {
93    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
94    where
95        S: serde::Serializer,
96    {
97        serializer.serialize_u8(*self as u8)
98    }
99}
100
101impl<'de> Deserialize<'de> for SignatureType {
102    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
103    where
104        D: serde::Deserializer<'de>,
105    {
106        let v = u8::deserialize(deserializer)?;
107        match v {
108            0 => Ok(Self::Eoa),
109            1 => Ok(Self::PolyProxy),
110            2 => Ok(Self::PolyGnosisSafe),
111            _ => Err(serde::de::Error::custom(format!(
112                "invalid signature type: {}",
113                v
114            ))),
115        }
116    }
117}
118
119impl fmt::Display for SignatureType {
120    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121        match self {
122            Self::Eoa => write!(f, "eoa"),
123            Self::PolyProxy => write!(f, "poly-proxy"),
124            Self::PolyGnosisSafe => write!(f, "poly-gnosis-safe"),
125        }
126    }
127}
128
129/// Tick size (minimum price increment)
130#[derive(Debug, Clone, Copy, PartialEq)]
131pub enum TickSize {
132    /// 0.1
133    Tenth,
134    /// 0.01
135    Hundredth,
136    /// 0.001
137    Thousandth,
138    /// 0.0001
139    TenThousandth,
140}
141
142impl TickSize {
143    /// Returns the tick size as an `f64` value.
144    pub fn as_f64(&self) -> f64 {
145        match self {
146            Self::Tenth => 0.1,
147            Self::Hundredth => 0.01,
148            Self::Thousandth => 0.001,
149            Self::TenThousandth => 0.0001,
150        }
151    }
152
153    /// Returns the number of decimal places for this tick size.
154    pub fn decimals(&self) -> u32 {
155        match self {
156            Self::Tenth => 1,
157            Self::Hundredth => 2,
158            Self::Thousandth => 3,
159            Self::TenThousandth => 4,
160        }
161    }
162}
163
164/// Options for creating an order
165#[derive(Debug, Clone, Copy, Default)]
166pub struct PartialCreateOrderOptions {
167    pub tick_size: Option<TickSize>,
168    pub neg_risk: Option<bool>,
169}
170
171impl TryFrom<&str> for TickSize {
172    type Error = ParseTickSizeError;
173
174    fn try_from(s: &str) -> Result<Self, Self::Error> {
175        match s {
176            "0.1" => Ok(Self::Tenth),
177            "0.01" => Ok(Self::Hundredth),
178            "0.001" => Ok(Self::Thousandth),
179            "0.0001" => Ok(Self::TenThousandth),
180            _ => Err(ParseTickSizeError(s.to_string())),
181        }
182    }
183}
184
185impl TryFrom<f64> for TickSize {
186    type Error = ParseTickSizeError;
187
188    fn try_from(n: f64) -> Result<Self, Self::Error> {
189        const EPSILON: f64 = 1e-10;
190        if (n - 0.1).abs() < EPSILON {
191            Ok(Self::Tenth)
192        } else if (n - 0.01).abs() < EPSILON {
193            Ok(Self::Hundredth)
194        } else if (n - 0.001).abs() < EPSILON {
195            Ok(Self::Thousandth)
196        } else if (n - 0.0001).abs() < EPSILON {
197            Ok(Self::TenThousandth)
198        } else {
199            Err(ParseTickSizeError(n.to_string()))
200        }
201    }
202}
203
204impl std::str::FromStr for TickSize {
205    type Err = ParseTickSizeError;
206
207    fn from_str(s: &str) -> Result<Self, Self::Err> {
208        Self::try_from(s)
209    }
210}
211
212fn serialize_salt<S>(salt: &str, serializer: S) -> Result<S::Ok, S::Error>
213where
214    S: serde::Serializer,
215{
216    // Parse the string as u128 and serialize it as a number
217    let val = salt
218        .parse::<u128>()
219        .map_err(|_| serde::ser::Error::custom("invalid salt"))?;
220    serializer.serialize_u128(val)
221}
222
223/// Unsigned order
224#[derive(Debug, Clone, Serialize, Deserialize)]
225#[serde(rename_all = "camelCase")]
226pub struct Order {
227    #[serde(serialize_with = "serialize_salt")]
228    pub salt: String,
229    pub maker: Address,
230    pub signer: Address,
231    pub taker: Address,
232    pub token_id: String,
233    pub maker_amount: String,
234    pub taker_amount: String,
235    pub expiration: String,
236    pub nonce: String,
237    pub fee_rate_bps: String,
238    pub side: OrderSide,
239    pub signature_type: SignatureType,
240    #[serde(skip)]
241    pub neg_risk: bool,
242}
243
244/// Arguments for creating a market order
245#[derive(Debug, Clone)]
246pub struct MarketOrderArgs {
247    pub token_id: String,
248    /// For BUY: Amount in USDC to spend
249    /// For SELL: Amount of token to sell
250    pub amount: f64,
251    pub side: OrderSide,
252    /// Worst acceptable price to fill at.
253    /// If None, it will be calculated from the orderbook.
254    pub price: Option<f64>,
255    pub fee_rate_bps: Option<u16>,
256    pub nonce: Option<u64>,
257    pub funder: Option<Address>,
258    pub signature_type: Option<SignatureType>,
259    pub order_type: Option<OrderKind>,
260}
261
262/// Signed order
263#[derive(Debug, Clone, Serialize, Deserialize)]
264#[serde(rename_all = "camelCase")]
265pub struct SignedOrder {
266    #[serde(flatten)]
267    pub order: Order,
268    pub signature: String,
269}
270
271#[cfg(test)]
272mod tests {
273    use super::*;
274    use alloy::primitives::Address;
275    use std::str::FromStr;
276
277    #[test]
278    fn test_order_serialization() {
279        let order = Order {
280            salt: "123".to_string(),
281            maker: Address::from_str("0x0000000000000000000000000000000000000001").unwrap(),
282            signer: Address::from_str("0x0000000000000000000000000000000000000002").unwrap(),
283            taker: Address::ZERO,
284            token_id: "456".to_string(),
285            maker_amount: "1000".to_string(),
286            taker_amount: "2000".to_string(),
287            expiration: "0".to_string(),
288            nonce: "789".to_string(),
289            fee_rate_bps: "0".to_string(),
290            side: OrderSide::Buy,
291            signature_type: SignatureType::Eoa,
292            neg_risk: false,
293        };
294
295        let signed_order = SignedOrder {
296            order,
297            signature: "0xabc".to_string(),
298        };
299
300        let json = serde_json::to_value(&signed_order).unwrap();
301
302        // Check camelCase
303        assert!(json.get("makerAmount").is_some());
304        assert!(json.get("takerAmount").is_some());
305        assert!(json.get("tokenId").is_some());
306        assert!(json.get("feeRateBps").is_some());
307        assert!(json.get("signatureType").is_some());
308
309        // Check flattened fields
310        assert!(json.get("signature").is_some());
311        assert!(json.get("salt").is_some());
312
313        // Check values
314        assert_eq!(json["makerAmount"], "1000");
315        assert_eq!(json["side"], "BUY");
316        assert_eq!(json["signatureType"], 0);
317        assert_eq!(json["nonce"], "789");
318    }
319
320    #[test]
321    fn order_side_serde_roundtrip() {
322        let buy: OrderSide = serde_json::from_str("\"BUY\"").unwrap();
323        let sell: OrderSide = serde_json::from_str("\"SELL\"").unwrap();
324        assert_eq!(buy, OrderSide::Buy);
325        assert_eq!(sell, OrderSide::Sell);
326
327        assert_eq!(serde_json::to_string(&OrderSide::Buy).unwrap(), "\"BUY\"");
328        assert_eq!(serde_json::to_string(&OrderSide::Sell).unwrap(), "\"SELL\"");
329    }
330
331    #[test]
332    fn order_side_display_is_numeric() {
333        // Display uses 0/1 for EIP-712 encoding
334        assert_eq!(OrderSide::Buy.to_string(), "0");
335        assert_eq!(OrderSide::Sell.to_string(), "1");
336    }
337
338    #[test]
339    fn order_side_rejects_lowercase() {
340        let result = serde_json::from_str::<OrderSide>("\"buy\"");
341        assert!(result.is_err(), "Should reject lowercase order side");
342    }
343
344    #[test]
345    fn order_kind_serde_roundtrip() {
346        for (variant, expected) in [
347            (OrderKind::Gtc, "GTC"),
348            (OrderKind::Fok, "FOK"),
349            (OrderKind::Gtd, "GTD"),
350            (OrderKind::Fak, "FAK"),
351        ] {
352            let serialized = serde_json::to_string(&variant).unwrap();
353            assert_eq!(serialized, format!("\"{}\"", expected));
354
355            let deserialized: OrderKind = serde_json::from_str(&serialized).unwrap();
356            assert_eq!(deserialized, variant);
357        }
358    }
359
360    #[test]
361    fn order_kind_display() {
362        assert_eq!(OrderKind::Gtc.to_string(), "GTC");
363        assert_eq!(OrderKind::Fok.to_string(), "FOK");
364        assert_eq!(OrderKind::Gtd.to_string(), "GTD");
365        assert_eq!(OrderKind::Fak.to_string(), "FAK");
366    }
367
368    #[test]
369    fn signature_type_serde_as_u8() {
370        assert_eq!(serde_json::to_string(&SignatureType::Eoa).unwrap(), "0");
371        assert_eq!(
372            serde_json::to_string(&SignatureType::PolyProxy).unwrap(),
373            "1"
374        );
375        assert_eq!(
376            serde_json::to_string(&SignatureType::PolyGnosisSafe).unwrap(),
377            "2"
378        );
379
380        let eoa: SignatureType = serde_json::from_str("0").unwrap();
381        assert_eq!(eoa, SignatureType::Eoa);
382        let proxy: SignatureType = serde_json::from_str("1").unwrap();
383        assert_eq!(proxy, SignatureType::PolyProxy);
384        let gnosis: SignatureType = serde_json::from_str("2").unwrap();
385        assert_eq!(gnosis, SignatureType::PolyGnosisSafe);
386    }
387
388    #[test]
389    fn signature_type_rejects_invalid_u8() {
390        let result = serde_json::from_str::<SignatureType>("3");
391        assert!(result.is_err(), "Should reject invalid signature type 3");
392
393        let result = serde_json::from_str::<SignatureType>("255");
394        assert!(result.is_err(), "Should reject invalid signature type 255");
395    }
396
397    #[test]
398    fn signature_type_display() {
399        assert_eq!(SignatureType::Eoa.to_string(), "eoa");
400        assert_eq!(SignatureType::PolyProxy.to_string(), "poly-proxy");
401        assert_eq!(
402            SignatureType::PolyGnosisSafe.to_string(),
403            "poly-gnosis-safe"
404        );
405    }
406
407    #[test]
408    fn signature_type_default_is_eoa() {
409        assert_eq!(SignatureType::default(), SignatureType::Eoa);
410    }
411
412    #[test]
413    fn signature_type_is_proxy() {
414        assert!(!SignatureType::Eoa.is_proxy());
415        assert!(SignatureType::PolyProxy.is_proxy());
416        assert!(SignatureType::PolyGnosisSafe.is_proxy());
417    }
418
419    #[test]
420    fn tick_size_from_str() {
421        assert_eq!(TickSize::try_from("0.1").unwrap(), TickSize::Tenth);
422        assert_eq!(TickSize::try_from("0.01").unwrap(), TickSize::Hundredth);
423        assert_eq!(TickSize::try_from("0.001").unwrap(), TickSize::Thousandth);
424        assert_eq!(
425            TickSize::try_from("0.0001").unwrap(),
426            TickSize::TenThousandth
427        );
428    }
429
430    #[test]
431    fn tick_size_from_str_rejects_invalid() {
432        assert!(TickSize::try_from("0.5").is_err());
433        assert!(TickSize::try_from("1.0").is_err());
434        assert!(TickSize::try_from("abc").is_err());
435        assert!(TickSize::try_from("0.00001").is_err());
436    }
437
438    #[test]
439    fn tick_size_from_f64() {
440        assert_eq!(TickSize::try_from(0.1).unwrap(), TickSize::Tenth);
441        assert_eq!(TickSize::try_from(0.01).unwrap(), TickSize::Hundredth);
442        assert_eq!(TickSize::try_from(0.001).unwrap(), TickSize::Thousandth);
443        assert_eq!(TickSize::try_from(0.0001).unwrap(), TickSize::TenThousandth);
444    }
445
446    #[test]
447    fn tick_size_from_f64_rejects_invalid() {
448        assert!(TickSize::try_from(0.5).is_err());
449        assert!(TickSize::try_from(0.0).is_err());
450        assert!(TickSize::try_from(1.0).is_err());
451    }
452
453    #[test]
454    fn tick_size_as_f64() {
455        assert!((TickSize::Tenth.as_f64() - 0.1).abs() < f64::EPSILON);
456        assert!((TickSize::Hundredth.as_f64() - 0.01).abs() < f64::EPSILON);
457        assert!((TickSize::Thousandth.as_f64() - 0.001).abs() < f64::EPSILON);
458        assert!((TickSize::TenThousandth.as_f64() - 0.0001).abs() < f64::EPSILON);
459    }
460
461    #[test]
462    fn tick_size_decimals() {
463        assert_eq!(TickSize::Tenth.decimals(), 1);
464        assert_eq!(TickSize::Hundredth.decimals(), 2);
465        assert_eq!(TickSize::Thousandth.decimals(), 3);
466        assert_eq!(TickSize::TenThousandth.decimals(), 4);
467    }
468
469    #[test]
470    fn tick_size_from_str_trait() {
471        let ts: TickSize = "0.01".parse().unwrap();
472        assert_eq!(ts, TickSize::Hundredth);
473    }
474
475    #[test]
476    fn parse_tick_size_error_display() {
477        let err = TickSize::try_from("bad").unwrap_err();
478        let msg = err.to_string();
479        assert!(
480            msg.contains("bad"),
481            "Error should contain invalid value: {}",
482            msg
483        );
484        assert!(
485            msg.contains("0.1"),
486            "Error should list valid values: {}",
487            msg
488        );
489    }
490
491    #[test]
492    fn order_neg_risk_skipped_in_serialization() {
493        let order = Order {
494            salt: "1".to_string(),
495            maker: Address::ZERO,
496            signer: Address::ZERO,
497            taker: Address::ZERO,
498            token_id: "1".to_string(),
499            maker_amount: "1".to_string(),
500            taker_amount: "1".to_string(),
501            expiration: "0".to_string(),
502            nonce: "0".to_string(),
503            fee_rate_bps: "0".to_string(),
504            side: OrderSide::Buy,
505            signature_type: SignatureType::Eoa,
506            neg_risk: true,
507        };
508        let json = serde_json::to_value(&order).unwrap();
509        assert!(
510            json.get("neg_risk").is_none() && json.get("negRisk").is_none(),
511            "neg_risk should be skipped in serialization: {}",
512            json
513        );
514    }
515
516    #[test]
517    fn salt_serialized_as_number() {
518        let order = Order {
519            salt: "12345678901234567890".to_string(),
520            maker: Address::ZERO,
521            signer: Address::ZERO,
522            taker: Address::ZERO,
523            token_id: "1".to_string(),
524            maker_amount: "1".to_string(),
525            taker_amount: "1".to_string(),
526            expiration: "0".to_string(),
527            nonce: "0".to_string(),
528            fee_rate_bps: "0".to_string(),
529            side: OrderSide::Buy,
530            signature_type: SignatureType::Eoa,
531            neg_risk: false,
532        };
533        let json = serde_json::to_value(&order).unwrap();
534        // Salt should be serialized as a number, not a string
535        assert!(
536            json["salt"].is_number(),
537            "Salt should be a number: {:?}",
538            json["salt"]
539        );
540    }
541}