forked from Polymarket/rs-clob-client
-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmod.rs
More file actions
532 lines (474 loc) · 14.6 KB
/
mod.rs
File metadata and controls
532 lines (474 loc) · 14.6 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
use std::fmt;
use alloy::core::sol;
use alloy::primitives::{Signature, U256};
use bon::Builder;
use rust_decimal::prelude::ToPrimitive as _;
use rust_decimal_macros::dec;
use serde::ser::{Error as _, SerializeStruct as _};
use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
use serde_json::Value;
use serde_repr::Serialize_repr;
use serde_with::{DisplayFromStr, serde_as};
use strum_macros::Display;
use crate::Result;
use crate::auth::ApiKey;
use crate::clob::order_builder::{LOT_SIZE_SCALE, USDC_DECIMALS};
use crate::error::Error;
use crate::types::Decimal;
pub mod request;
pub mod response;
#[non_exhaustive]
#[derive(
Clone, Copy, Debug, Display, Default, Eq, Ord, PartialEq, PartialOrd, Serialize, Deserialize,
)]
pub enum OrderType {
/// Good 'til Cancelled; If not fully filled, the order rests on the book until it is explicitly
/// cancelled.
#[serde(alias = "gtc")]
GTC,
/// Fill or Kill; Order is attempted to be filled, in full, immediately. If it cannot be fully
/// filled, the entire order is cancelled.
#[default]
#[serde(alias = "fok")]
FOK,
/// Good 'til Date; If not fully filled, the order rests on the book until the specified date.
#[serde(alias = "gtd")]
GTD,
/// Fill and Kill; Order is attempted to be filled, however much is possible, immediately. If
/// the order cannot be fully filled, the remaining quantity is cancelled.
#[serde(alias = "fak")]
FAK,
#[serde(other)]
Unknown,
}
#[non_exhaustive]
#[derive(
Clone, Copy, Debug, Display, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize,
)]
#[serde(rename_all = "UPPERCASE")]
#[strum(serialize_all = "UPPERCASE")]
#[repr(u8)]
pub enum Side {
#[serde(alias = "buy")]
Buy = 0,
#[serde(alias = "sell")]
Sell = 1,
#[serde(other)]
Unknown = 255,
}
impl TryFrom<u8> for Side {
type Error = Error;
fn try_from(value: u8) -> std::result::Result<Self, Self::Error> {
match value {
0 => Ok(Side::Buy),
1 => Ok(Side::Sell),
other => Err(Error::validation(format!(
"Unable to create Side from {other}"
))),
}
}
}
/// Time interval for price history queries.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Display, Eq, PartialEq, Serialize, Deserialize)]
pub enum Interval {
/// 1 minute
#[serde(rename = "1m")]
#[strum(serialize = "1m")]
OneMinute,
/// 1 hour
#[serde(rename = "1h")]
#[strum(serialize = "1h")]
OneHour,
/// 6 hours
#[serde(rename = "6h")]
#[strum(serialize = "6h")]
SixHours,
/// 1 day
#[serde(rename = "1d")]
#[strum(serialize = "1d")]
OneDay,
/// 1 week
#[serde(rename = "1w")]
#[strum(serialize = "1w")]
OneWeek,
/// Maximum available history
#[serde(rename = "max")]
#[strum(serialize = "max")]
Max,
}
/// Time range specification for price history queries.
///
/// The CLOB API requires either an interval or explicit start/end timestamps.
/// This enum enforces that requirement at compile time.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Serialize)]
#[serde(untagged)]
pub enum TimeRange {
/// Use a predefined interval (e.g., last day, last week).
Interval {
/// The time interval.
interval: Interval,
},
/// Use explicit start and end timestamps.
Range {
/// Start timestamp (Unix seconds).
start_ts: i64,
/// End timestamp (Unix seconds).
end_ts: i64,
},
}
impl TimeRange {
/// Create a time range from a predefined interval.
#[must_use]
pub const fn from_interval(interval: Interval) -> Self {
Self::Interval { interval }
}
/// Create a time range from explicit timestamps.
#[must_use]
pub const fn from_range(start_ts: i64, end_ts: i64) -> Self {
Self::Range { start_ts, end_ts }
}
}
impl From<Interval> for TimeRange {
fn from(interval: Interval) -> Self {
Self::from_interval(interval)
}
}
#[derive(Clone, Copy, Debug)]
pub(crate) enum AmountInner {
Usdc(Decimal),
Shares(Decimal),
}
impl AmountInner {
pub fn as_inner(&self) -> Decimal {
match self {
AmountInner::Usdc(d) | AmountInner::Shares(d) => *d,
}
}
}
#[derive(Clone, Copy, Debug)]
pub struct Amount(pub(crate) AmountInner);
impl Amount {
pub fn usdc(value: Decimal) -> Result<Amount> {
let normalized = value.normalize();
if normalized.scale() > USDC_DECIMALS {
return Err(Error::validation(format!(
"Unable to build Amount with {} decimal points, must be <= {USDC_DECIMALS}",
normalized.scale()
)));
}
Ok(Amount(AmountInner::Usdc(normalized)))
}
pub fn shares(value: Decimal) -> Result<Amount> {
let normalized = value.normalize();
if normalized.scale() > LOT_SIZE_SCALE {
return Err(Error::validation(format!(
"Unable to build Amount with {} decimal points, must be <= {LOT_SIZE_SCALE}",
normalized.scale()
)));
}
Ok(Amount(AmountInner::Shares(normalized)))
}
#[must_use]
pub fn as_inner(&self) -> Decimal {
self.0.as_inner()
}
#[must_use]
pub fn is_usdc(&self) -> bool {
matches!(self.0, AmountInner::Usdc(_))
}
#[must_use]
pub fn is_shares(&self) -> bool {
matches!(self.0, AmountInner::Shares(_))
}
}
#[non_exhaustive]
#[derive(
Clone,
Copy,
Display,
Debug,
Default,
Eq,
Ord,
PartialEq,
PartialOrd,
Serialize_repr,
Deserialize,
)]
#[repr(u8)]
pub enum SignatureType {
#[default]
Eoa = 0,
Proxy = 1,
GnosisSafe = 2,
}
#[non_exhaustive]
#[derive(Clone, Copy, Display, Debug, Eq, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
#[strum(serialize_all = "UPPERCASE")]
pub enum OrderStatusType {
#[serde(alias = "live")]
Live,
#[serde(alias = "matched")]
Matched,
#[serde(alias = "canceled")]
Canceled,
#[serde(alias = "delayed")]
Delayed,
#[serde(alias = "unmatched")]
Unmatched,
#[serde(other)]
Unknown,
}
#[non_exhaustive]
#[derive(
Clone, Copy, Debug, Default, Display, Eq, Ord, PartialEq, PartialOrd, Serialize, Deserialize,
)]
#[serde(rename_all = "UPPERCASE")]
#[strum(serialize_all = "UPPERCASE")]
pub enum AssetType {
#[default]
Collateral,
Conditional,
#[serde(other)]
Unknown,
}
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum TraderSide {
Taker,
Maker,
#[serde(other)]
Unknown,
}
/// Represents the maximum number of decimal places for an order's price field
#[non_exhaustive]
#[derive(Debug, Clone, Copy)]
pub enum TickSize {
Tenth,
Hundredth,
Thousandth,
TenThousandth,
}
impl fmt::Display for TickSize {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let name = match self {
TickSize::Tenth => "Tenth",
TickSize::Hundredth => "Hundredth",
TickSize::Thousandth => "Thousandth",
TickSize::TenThousandth => "TenThousandth",
};
write!(f, "{name}({})", self.as_decimal())
}
}
impl TickSize {
#[must_use]
pub fn as_decimal(&self) -> Decimal {
match self {
TickSize::Tenth => dec!(0.1),
TickSize::Hundredth => dec!(0.01),
TickSize::Thousandth => dec!(0.001),
TickSize::TenThousandth => dec!(0.0001),
}
}
}
impl From<TickSize> for Decimal {
fn from(tick_size: TickSize) -> Self {
tick_size.as_decimal()
}
}
impl TryFrom<Decimal> for TickSize {
type Error = Error;
fn try_from(value: Decimal) -> std::result::Result<Self, Self::Error> {
match value {
v if v == dec!(0.1) => Ok(TickSize::Tenth),
v if v == dec!(0.01) => Ok(TickSize::Hundredth),
v if v == dec!(0.001) => Ok(TickSize::Thousandth),
v if v == dec!(0.0001) => Ok(TickSize::TenThousandth),
other => Err(Error::validation(format!(
"Unknown tick size: {other}. Expected one of: 0.1, 0.01, 0.001, 0.0001"
))),
}
}
}
impl PartialEq for TickSize {
fn eq(&self, other: &Self) -> bool {
self.as_decimal() == other.as_decimal()
}
}
impl<'de> Deserialize<'de> for TickSize {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let dec = <Decimal as Deserialize>::deserialize(deserializer)?;
TickSize::try_from(dec).map_err(de::Error::custom)
}
}
sol! {
/// Alloy solidity type representing an order in the context of the Polymarket exchange
///
/// <!-- The CLOB expects all `uint256` types, [`U256`], excluding `salt`, to be presented as a
/// string so we must serialize as Display, which for U256 is lower hex-encoded string.
/// -->
#[non_exhaustive]
#[serde_as]
#[derive(Serialize, Debug, Default, PartialEq)]
struct Order {
#[serde(serialize_with = "ser_salt")]
uint256 salt;
address maker;
address signer;
address taker;
#[serde_as(as = "DisplayFromStr")]
uint256 tokenId;
#[serde_as(as = "DisplayFromStr")]
uint256 makerAmount;
#[serde_as(as = "DisplayFromStr")]
uint256 takerAmount;
#[serde_as(as = "DisplayFromStr")]
uint256 expiration;
#[serde_as(as = "DisplayFromStr")]
uint256 nonce;
#[serde_as(as = "DisplayFromStr")]
uint256 feeRateBps;
uint8 side;
uint8 signatureType;
}
}
// CLOB expects salt as a JSON number. U256 as an integer will not fit as a JSON number. Since
// we generated the salt as a u64 originally (see `salt_generator`), we can be very confident that
// we can invert the conversion to U256 and return a u64 when serializing.
fn ser_salt<S: Serializer>(value: &U256, serializer: S) -> std::result::Result<S::Ok, S::Error> {
let v: u64 = value
.try_into()
.map_err(|e| S::Error::custom(format!("salt does not fit into u64: {e}")))?;
serializer.serialize_u64(v)
}
#[non_exhaustive]
#[derive(Clone, Debug, Default, Serialize, Builder, PartialEq)]
pub struct SignableOrder {
pub order: Order,
pub order_type: OrderType,
}
#[non_exhaustive]
#[derive(Debug, Builder, PartialEq)]
pub struct SignedOrder {
pub order: Order,
pub signature: Signature,
pub order_type: OrderType,
pub owner: ApiKey,
}
// CLOB expects a struct that has the `signature` "folded" into the `order` key
impl Serialize for SignedOrder {
fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
let mut st = serializer.serialize_struct("SignedOrder", 3)?;
let mut order = serde_json::to_value(&self.order).map_err(serde::ser::Error::custom)?;
// inject signature into order object
if let Value::Object(ref mut map) = order {
map.insert(
"signature".to_owned(),
Value::String(self.signature.to_string()),
);
}
// Side has to be serialized as "BUY" or "SELL" when hitting the CLOB, but the actual
// signature for a SignedOrder has to be done on the integer representation.
if let Some(value) = order.get_mut("side")
&& let Some(side_numeric) = value.as_u64()
&& let Some(side_numeric) = side_numeric.to_u8()
&& let Ok(side) = Side::try_from(side_numeric)
{
*value = Value::String(side.to_string());
}
st.serialize_field("order", &order)?;
st.serialize_field("orderType", &self.order_type)?;
st.serialize_field("owner", &self.owner)?;
st.end()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::error::Validation;
#[test]
fn tick_size_decimals_should_succeed() {
assert_eq!(TickSize::Tenth.as_decimal().scale(), 1);
assert_eq!(TickSize::Hundredth.as_decimal().scale(), 2);
assert_eq!(TickSize::Thousandth.as_decimal().scale(), 3);
assert_eq!(TickSize::TenThousandth.as_decimal().scale(), 4);
}
#[test]
fn tick_size_should_display() {
assert_eq!(format!("{}", TickSize::Tenth), "Tenth(0.1)");
assert_eq!(format!("{}", TickSize::Hundredth), "Hundredth(0.01)");
assert_eq!(format!("{}", TickSize::Thousandth), "Thousandth(0.001)");
assert_eq!(
format!("{}", TickSize::TenThousandth),
"TenThousandth(0.0001)"
);
}
#[test]
fn tick_from_decimal_should_succeed() {
assert_eq!(
TickSize::try_from(dec!(0.0001)).unwrap(),
TickSize::TenThousandth
);
assert_eq!(
TickSize::try_from(dec!(0.001)).unwrap(),
TickSize::Thousandth
);
assert_eq!(TickSize::try_from(dec!(0.01)).unwrap(), TickSize::Hundredth);
assert_eq!(TickSize::try_from(dec!(0.1)).unwrap(), TickSize::Tenth);
}
#[test]
fn non_standard_decimal_to_tick_size_should_fail() {
let result = TickSize::try_from(Decimal::ONE);
assert!(result.is_err());
assert!(
result
.unwrap_err()
.to_string()
.contains("Unknown tick size: 1")
);
}
#[test]
fn amount_should_succeed() -> Result<()> {
let usdc = Amount::usdc(Decimal::ONE_HUNDRED)?;
assert!(usdc.is_usdc());
assert_eq!(usdc.as_inner(), Decimal::ONE_HUNDRED);
let shares = Amount::shares(Decimal::ONE_HUNDRED)?;
assert!(shares.is_shares());
assert_eq!(shares.as_inner(), Decimal::ONE_HUNDRED);
Ok(())
}
#[test]
fn improper_shares_lot_size_should_fail() {
let Err(err) = Amount::shares(dec!(0.23400)) else {
panic!()
};
let message = err.downcast_ref::<Validation>().unwrap();
assert_eq!(
message.reason,
format!("Unable to build Amount with 3 decimal points, must be <= {LOT_SIZE_SCALE}")
);
}
#[test]
fn improper_usdc_decimal_size_should_fail() {
let Err(err) = Amount::usdc(dec!(0.2340011)) else {
panic!()
};
let message = err.downcast_ref::<Validation>().unwrap();
assert_eq!(
message.reason,
format!("Unable to build Amount with 7 decimal points, must be <= {USDC_DECIMALS}")
);
}
#[test]
fn side_to_string_should_succeed() {
assert_eq!(Side::Buy.to_string(), "BUY");
assert_eq!(Side::Sell.to_string(), "SELL");
}
}