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
//! [`ConditionalOrderFactory`] — instantiate conditional orders from on-chain params.
use std::fmt;
use cow_errors::CowError;
use super::{
gat::{GatOrder, decode_gat_static_input},
stop_loss::{STOP_LOSS_HANDLER_ADDRESS, StopLossOrder, decode_stop_loss_static_input},
twap::{TwapOrder, decode_twap_static_input},
types::{ConditionalOrderParams, TWAP_HANDLER_ADDRESS},
};
/// A conditional order decoded from on-chain [`ConditionalOrderParams`].
#[derive(Debug, Clone)]
pub enum ConditionalOrderKind {
/// A `TWAP` (Time-Weighted Average Price) order.
Twap(TwapOrder),
/// A stop-loss order that triggers when the price falls below a strike price.
StopLoss(StopLossOrder),
/// A `GoodAfterTime` order that becomes valid only after a given timestamp.
GoodAfterTime(GatOrder),
/// An order whose handler is not recognised by this factory.
Unknown(ConditionalOrderParams),
}
impl ConditionalOrderKind {
/// Returns a short string label for the order kind.
///
/// # Returns
///
/// A `&'static str` identifying the variant: `"twap"`, `"stop-loss"`,
/// `"good-after-time"`, or `"unknown"`.
#[must_use]
pub const fn as_str(&self) -> &'static str {
match self {
Self::Twap(_) => "twap",
Self::StopLoss(_) => "stop-loss",
Self::GoodAfterTime(_) => "good-after-time",
Self::Unknown(_) => "unknown",
}
}
/// Returns `true` if this is a `TWAP` conditional order.
///
/// ```
/// use alloy_primitives::B256;
/// use cow_composable::{ConditionalOrderFactory, ConditionalOrderParams, TWAP_HANDLER_ADDRESS};
///
/// let params = ConditionalOrderParams {
/// handler: TWAP_HANDLER_ADDRESS,
/// salt: B256::ZERO,
/// static_input: vec![],
/// };
/// // An unknown handler resolves to Unknown, not Twap.
/// use alloy_primitives::Address;
/// let unknown = cow_composable::ConditionalOrderKind::Unknown(ConditionalOrderParams {
/// handler: Address::ZERO,
/// salt: B256::ZERO,
/// static_input: vec![],
/// });
/// assert!(!unknown.is_twap());
/// assert!(unknown.is_unknown());
/// ```
#[must_use]
pub const fn is_twap(&self) -> bool {
matches!(self, Self::Twap(_))
}
/// Returns `true` if this is a stop-loss conditional order.
///
/// ```
/// use alloy_primitives::{Address, B256};
/// use cow_composable::{ConditionalOrderKind, ConditionalOrderParams};
///
/// let unknown = ConditionalOrderKind::Unknown(ConditionalOrderParams {
/// handler: Address::ZERO,
/// salt: B256::ZERO,
/// static_input: vec![],
/// });
/// assert!(!unknown.is_stop_loss());
/// ```
#[must_use]
pub const fn is_stop_loss(&self) -> bool {
matches!(self, Self::StopLoss(_))
}
/// Returns `true` if this is a `GoodAfterTime` conditional order.
///
/// ```
/// use alloy_primitives::{Address, B256};
/// use cow_composable::{ConditionalOrderKind, ConditionalOrderParams};
///
/// let unknown = ConditionalOrderKind::Unknown(ConditionalOrderParams {
/// handler: Address::ZERO,
/// salt: B256::ZERO,
/// static_input: vec![],
/// });
/// assert!(!unknown.is_good_after_time());
/// ```
#[must_use]
pub const fn is_good_after_time(&self) -> bool {
matches!(self, Self::GoodAfterTime(_))
}
/// Returns `true` if this order's handler is not recognised by the factory.
///
/// # Returns
///
/// `true` when the variant is [`ConditionalOrderKind::Unknown`], meaning the
/// handler address did not match any known conditional order type.
#[must_use]
pub const fn is_unknown(&self) -> bool {
matches!(self, Self::Unknown(_))
}
}
impl fmt::Display for ConditionalOrderKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Twap(order) => write!(f, "twap({order})"),
Self::StopLoss(_) => f.write_str("stop-loss"),
Self::GoodAfterTime(_) => f.write_str("good-after-time"),
Self::Unknown(params) => write!(f, "unknown({:#x})", params.handler),
}
}
}
/// Instantiates conditional orders from [`ConditionalOrderParams`].
///
/// Mirrors `ConditionalOrderFactory` from the `TypeScript` SDK.
/// Extend by matching additional handler addresses in [`from_params`].
///
/// [`from_params`]: ConditionalOrderFactory::from_params
#[derive(Debug, Clone, Default)]
pub struct ConditionalOrderFactory;
impl ConditionalOrderFactory {
/// Create a new factory.
///
/// # Returns
///
/// A zero-sized [`ConditionalOrderFactory`] instance that can decode
/// [`ConditionalOrderParams`] via [`from_params`](Self::from_params).
#[must_use]
pub const fn new() -> Self {
Self
}
/// Decode [`ConditionalOrderParams`] into a typed [`ConditionalOrderKind`].
///
/// Handler addresses are matched exactly. Unknown handlers return
/// [`ConditionalOrderKind::Unknown`] rather than an error.
///
/// Recognised handlers:
/// - [`TWAP_HANDLER_ADDRESS`] → [`ConditionalOrderKind::Twap`]
/// - [`STOP_LOSS_HANDLER_ADDRESS`] → [`ConditionalOrderKind::StopLoss`]
///
/// Note: the `GoodAfterTime` handler (`GAT_HANDLER_ADDRESS`) shares the
/// same on-chain address as the `TWAP` handler, so `TWAP` decoding takes
/// priority for that address.
///
/// # Errors
///
/// Returns [`CowError::AppData`] only if a known handler's static input
/// fails ABI decoding.
pub fn from_params(
&self,
params: ConditionalOrderParams,
) -> Result<ConditionalOrderKind, CowError> {
if params.handler == TWAP_HANDLER_ADDRESS {
// Try TWAP decoding first (TWAP and GAT share the same address).
// If the input is TWAP-sized (320 bytes), decode as TWAP.
// If it is GAT-sized (448 bytes), decode as GAT.
if params.static_input.len() == 14 * 32 {
let data = decode_gat_static_input(¶ms.static_input)?;
return Ok(ConditionalOrderKind::GoodAfterTime(GatOrder::with_salt(
data,
params.salt,
)));
}
let data = decode_twap_static_input(¶ms.static_input)?;
return Ok(ConditionalOrderKind::Twap(TwapOrder::with_salt(data, params.salt)));
}
if params.handler == STOP_LOSS_HANDLER_ADDRESS {
let data = decode_stop_loss_static_input(¶ms.static_input)?;
return Ok(ConditionalOrderKind::StopLoss(StopLossOrder::with_salt(data, params.salt)));
}
Ok(ConditionalOrderKind::Unknown(params))
}
}
impl fmt::Display for ConditionalOrderFactory {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("conditional-order-factory")
}
}
#[cfg(test)]
mod tests {
use alloy_primitives::{Address, B256};
use super::*;
#[test]
fn factory_new() {
let factory = ConditionalOrderFactory::new();
assert_eq!(factory.to_string(), "conditional-order-factory");
}
#[test]
fn factory_unknown_handler() {
let factory = ConditionalOrderFactory::new();
let params = ConditionalOrderParams {
handler: Address::ZERO,
salt: B256::ZERO,
static_input: vec![],
};
let result = factory.from_params(params).unwrap();
assert!(result.is_unknown());
assert!(!result.is_twap());
assert!(!result.is_stop_loss());
assert!(!result.is_good_after_time());
assert_eq!(result.as_str(), "unknown");
}
#[test]
fn factory_twap_handler_empty_static_input_errors() {
let factory = ConditionalOrderFactory::new();
let params = ConditionalOrderParams {
handler: TWAP_HANDLER_ADDRESS,
salt: B256::ZERO,
static_input: vec![],
};
// Empty static input is not valid for TWAP
assert!(factory.from_params(params).is_err());
}
#[test]
fn factory_stop_loss_handler_empty_static_input_errors() {
let factory = ConditionalOrderFactory::new();
let params = ConditionalOrderParams {
handler: STOP_LOSS_HANDLER_ADDRESS,
salt: B256::ZERO,
static_input: vec![],
};
assert!(factory.from_params(params).is_err());
}
#[test]
fn conditional_order_kind_display_unknown() {
let kind = ConditionalOrderKind::Unknown(ConditionalOrderParams {
handler: Address::ZERO,
salt: B256::ZERO,
static_input: vec![],
});
let s = kind.to_string();
assert!(s.contains("unknown"));
}
#[test]
fn conditional_order_kind_display_stop_loss() {
let kind = ConditionalOrderKind::Unknown(ConditionalOrderParams {
handler: Address::ZERO,
salt: B256::ZERO,
static_input: vec![],
});
// We can't easily construct a StopLoss without valid data,
// so we test the other Display variants through the Unknown variant
assert_eq!(kind.as_str(), "unknown");
}
// ── Display coverage for the typed variants ───────────────────────────
fn sample_twap() -> TwapOrder {
use alloy_primitives::U256;
use crate::types::TwapData;
let data = TwapData::sell(
Address::repeat_byte(0x11),
Address::repeat_byte(0x22),
U256::from(1_000u64),
4,
3_600,
)
.with_buy_amount(U256::from(800u64));
TwapOrder::new(data)
}
fn sample_stop_loss() -> StopLossOrder {
use alloy_primitives::U256;
use crate::stop_loss::StopLossData;
StopLossOrder::new(StopLossData {
sell_token: Address::repeat_byte(0x01),
buy_token: Address::repeat_byte(0x02),
sell_amount: U256::from(1_000u64),
buy_amount: U256::from(900u64),
app_data: B256::ZERO,
receiver: Address::ZERO,
is_sell_order: true,
is_partially_fillable: false,
valid_to: 9_999_999,
strike_price: U256::from(1_000_000_000_000_000_000u64),
sell_token_price_oracle: Address::repeat_byte(0x03),
buy_token_price_oracle: Address::repeat_byte(0x04),
token_amount_in_eth: false,
})
}
fn sample_gat() -> GatOrder {
use alloy_primitives::U256;
use crate::{gat::GatData, types::GpV2OrderStruct};
let order = GpV2OrderStruct {
sell_token: Address::repeat_byte(0x01),
buy_token: Address::repeat_byte(0x02),
receiver: Address::ZERO,
sell_amount: U256::from(1_000u64),
buy_amount: U256::from(900u64),
valid_to: 9_999_999,
app_data: B256::ZERO,
fee_amount: U256::ZERO,
kind: B256::ZERO,
partially_fillable: false,
sell_token_balance: B256::ZERO,
buy_token_balance: B256::ZERO,
};
GatOrder::new(GatData { order, start_time: 1_000_000, tx_deadline: 2_000_000 })
}
#[test]
fn conditional_order_kind_display_typed_variants() {
// Each arm of the Display match must be exercised — previous tests
// only hit the `Unknown` arm.
assert!(ConditionalOrderKind::Twap(sample_twap()).to_string().starts_with("twap("));
assert_eq!(ConditionalOrderKind::StopLoss(sample_stop_loss()).to_string(), "stop-loss");
assert_eq!(
ConditionalOrderKind::GoodAfterTime(sample_gat()).to_string(),
"good-after-time",
);
}
}