cow-sdk-app-data 0.1.0-alpha.10

CoW Protocol app-data encoding, validation, and CID compatibility
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
use cow_sdk_core::{Address, ValidationReason};
use serde::de::{Deserializer, Error as _};
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::AppDataError;

/// Typed partner-fee metadata accepted by app-data and trading helpers.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(
    all(target_arch = "wasm32", target_os = "unknown", feature = "ts-bindings"),
    derive(tsify::Tsify)
)]
#[cfg_attr(
    all(target_arch = "wasm32", target_os = "unknown", feature = "ts-bindings"),
    tsify(into_wasm_abi, from_wasm_abi)
)]
#[serde(untagged)]
pub enum PartnerFee {
    /// Single fee policy object.
    Single(PartnerFeePolicy),
    /// Ordered fee policy list.
    Multiple(Vec<PartnerFeePolicy>),
}

impl PartnerFee {
    /// Returns the first supported volume-basis-point fee in this value, if one exists.
    #[must_use]
    pub fn volume_bps(&self) -> Option<u16> {
        match self {
            Self::Single(policy) => policy.volume_bps(),
            Self::Multiple(policies) => policies.iter().find_map(PartnerFeePolicy::volume_bps),
        }
    }

    /// Validates every policy carried by this payload against the published
    /// bounds for the partner-fee schema.
    ///
    /// # Errors
    ///
    /// Returns [`AppDataError::InvalidPartnerFee`] on the first policy whose
    /// basis-point values fall outside the documented `[1..=9999]` range, or
    /// whose recipient address is the zero address.
    pub fn validate(&self) -> Result<(), AppDataError> {
        match self {
            Self::Single(policy) => policy.validate(),
            Self::Multiple(policies) => policies.iter().try_for_each(PartnerFeePolicy::validate),
        }
    }

    /// Serializes this typed partner-fee payload into the app-data metadata shape.
    ///
    /// # Panics
    ///
    /// Panics only if the compile-time partner-fee schema types stop being
    /// serializable to JSON.
    #[must_use]
    pub fn to_value(&self) -> Value {
        // SAFETY: partner-fee schema values are typed serde data owned by this
        // crate; serialization failure would mean the schema type stopped being
        // serializable.
        serde_json::to_value(self).expect("partner-fee schema types must remain serializable")
    }

    /// Parses partner-fee metadata from an app-data metadata value.
    ///
    /// Accepts every in-scope shape — `Volume { volumeBps, recipient }`,
    /// `Surplus { surplusBps, maxVolumeBps, recipient }`,
    /// `PriceImprovement { priceImprovementBps, maxVolumeBps, recipient }`,
    /// arrays of the above — and the legacy `{ bps, recipient }` object which
    /// is promoted to a `Volume` policy for wire parity with the reviewed
    /// services parser.
    ///
    /// # Errors
    ///
    /// Returns [`AppDataError::Serialization`] when the JSON value does not match any
    /// supported partner-fee schema shape. Bounds validation is not performed
    /// here — call [`PartnerFee::validate`] on the parsed value to enforce the
    /// documented basis-point ranges.
    pub fn from_value(value: Value) -> Result<Self, AppDataError> {
        serde_json::from_value(value).map_err(AppDataError::from)
    }
}

impl From<PartnerFeePolicy> for PartnerFee {
    fn from(value: PartnerFeePolicy) -> Self {
        Self::Single(value)
    }
}

impl From<Vec<PartnerFeePolicy>> for PartnerFee {
    fn from(value: Vec<PartnerFeePolicy>) -> Self {
        Self::Multiple(value)
    }
}

/// One typed partner-fee policy object.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(
    all(target_arch = "wasm32", target_os = "unknown", feature = "ts-bindings"),
    derive(tsify::Tsify)
)]
#[cfg_attr(
    all(target_arch = "wasm32", target_os = "unknown", feature = "ts-bindings"),
    tsify(into_wasm_abi, from_wasm_abi)
)]
#[serde(untagged)]
pub enum PartnerFeePolicy {
    /// Fee paid from traded volume.
    Volume {
        /// Fee paid in basis points of volume.
        #[serde(rename = "volumeBps")]
        volume_bps: u16,
        /// Recipient of the partner fee.
        recipient: Address,
    },
    /// Fee paid from surplus, capped by volume.
    Surplus {
        /// Fee paid in basis points of surplus.
        #[serde(rename = "surplusBps")]
        surplus_bps: u16,
        /// Maximum fee paid in basis points of volume.
        #[serde(rename = "maxVolumeBps")]
        max_volume_bps: u16,
        /// Recipient of the partner fee.
        recipient: Address,
    },
    /// Fee paid from price improvement, capped by volume.
    PriceImprovement {
        /// Fee paid in basis points of price improvement.
        #[serde(rename = "priceImprovementBps")]
        price_improvement_bps: u16,
        /// Maximum fee paid in basis points of volume.
        #[serde(rename = "maxVolumeBps")]
        max_volume_bps: u16,
        /// Recipient of the partner fee.
        recipient: Address,
    },
}

impl PartnerFeePolicy {
    /// Creates a volume-based partner-fee policy after validating the
    /// supplied basis-point value and recipient against the published
    /// partner-fee bounds.
    ///
    /// # Errors
    ///
    /// Returns [`AppDataError::InvalidPartnerFee`] when `volume_bps` falls
    /// outside the documented `[1..=9999]` range, or when `recipient` is the
    /// zero address.
    pub fn volume(volume_bps: u16, recipient: Address) -> Result<Self, AppDataError> {
        let policy = Self::Volume {
            volume_bps,
            recipient,
        };
        policy.validate()?;
        Ok(policy)
    }

    /// Creates a surplus-based partner-fee policy after validating the
    /// supplied basis-point values and recipient against the published
    /// partner-fee bounds.
    ///
    /// # Errors
    ///
    /// Returns [`AppDataError::InvalidPartnerFee`] when `surplus_bps` falls
    /// outside `[1..=9999]`, when `max_volume_bps` falls outside `[1..=9999]`,
    /// or when `recipient` is the zero address.
    pub fn surplus(
        surplus_bps: u16,
        max_volume_bps: u16,
        recipient: Address,
    ) -> Result<Self, AppDataError> {
        let policy = Self::Surplus {
            surplus_bps,
            max_volume_bps,
            recipient,
        };
        policy.validate()?;
        Ok(policy)
    }

    /// Creates a price-improvement-based partner-fee policy after validating
    /// the supplied basis-point values and recipient against the published
    /// partner-fee bounds.
    ///
    /// # Errors
    ///
    /// Returns [`AppDataError::InvalidPartnerFee`] when
    /// `price_improvement_bps` falls outside `[1..=9999]`, when
    /// `max_volume_bps` falls outside `[1..=9999]`, or when `recipient` is the
    /// zero address.
    pub fn price_improvement(
        price_improvement_bps: u16,
        max_volume_bps: u16,
        recipient: Address,
    ) -> Result<Self, AppDataError> {
        let policy = Self::PriceImprovement {
            price_improvement_bps,
            max_volume_bps,
            recipient,
        };
        policy.validate()?;
        Ok(policy)
    }

    /// Returns the volume-basis-point fee when this policy uses the volume shape.
    #[must_use]
    pub const fn volume_bps(&self) -> Option<u16> {
        match self {
            Self::Volume { volume_bps, .. } => Some(*volume_bps),
            Self::Surplus { .. } | Self::PriceImprovement { .. } => None,
        }
    }

    /// Validates this policy against the published partner-fee schema bounds.
    ///
    /// The bounds the reviewed schema applies:
    ///
    /// * `volumeBps` — integer in `[1..=9999]`
    /// * `surplusBps` — integer in `[1..=9999]`
    /// * `priceImprovementBps` — integer in `[1..=9999]`
    /// * `maxVolumeBps` — integer in `[1..=9999]`
    /// * `recipient` — non-zero 20-byte address
    ///
    /// # Errors
    ///
    /// Returns [`AppDataError::InvalidPartnerFee`] on the first field that
    /// falls outside the documented bounds, or when `recipient` is the zero
    /// address.
    pub fn validate(&self) -> Result<(), AppDataError> {
        match self {
            Self::Volume {
                volume_bps,
                recipient,
            } => {
                validate_max_volume_bps("partnerFee.volumeBps", *volume_bps)?;
                validate_recipient("partnerFee.recipient", recipient)?;
            }
            Self::Surplus {
                surplus_bps,
                max_volume_bps,
                recipient,
            } => {
                validate_surplus_bps("partnerFee.surplusBps", *surplus_bps)?;
                validate_max_volume_bps("partnerFee.maxVolumeBps", *max_volume_bps)?;
                validate_recipient("partnerFee.recipient", recipient)?;
            }
            Self::PriceImprovement {
                price_improvement_bps,
                max_volume_bps,
                recipient,
            } => {
                validate_surplus_bps("partnerFee.priceImprovementBps", *price_improvement_bps)?;
                validate_max_volume_bps("partnerFee.maxVolumeBps", *max_volume_bps)?;
                validate_recipient("partnerFee.recipient", recipient)?;
            }
        }
        Ok(())
    }
}

impl<'de> Deserialize<'de> for PartnerFeePolicy {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct Fields {
            #[serde(default, rename = "volumeBps")]
            volume_bps: Option<u16>,
            #[serde(default, rename = "surplusBps")]
            surplus_bps: Option<u16>,
            #[serde(default, rename = "priceImprovementBps")]
            price_improvement_bps: Option<u16>,
            #[serde(default, rename = "maxVolumeBps")]
            max_volume_bps: Option<u16>,
            #[serde(default)]
            bps: Option<u16>,
            recipient: Address,
        }

        let fields = Fields::deserialize(deserializer)?;
        match (
            fields.volume_bps,
            fields.surplus_bps,
            fields.price_improvement_bps,
            fields.max_volume_bps,
            fields.bps,
        ) {
            (Some(volume_bps), None, None, None, None) => Ok(Self::Volume {
                volume_bps,
                recipient: fields.recipient,
            }),
            (None, Some(surplus_bps), None, Some(max_volume_bps), None) => Ok(Self::Surplus {
                surplus_bps,
                max_volume_bps,
                recipient: fields.recipient,
            }),
            (None, None, Some(price_improvement_bps), Some(max_volume_bps), None) => {
                Ok(Self::PriceImprovement {
                    price_improvement_bps,
                    max_volume_bps,
                    recipient: fields.recipient,
                })
            }
            (None, None, None, None, Some(bps)) => Ok(Self::Volume {
                volume_bps: bps,
                recipient: fields.recipient,
            }),
            _ => Err(D::Error::custom("unknown partner fee policy format")),
        }
    }
}

// partnerFee schema v1.1.0 raised the volume cap to match the surplus cap. The two
// constants now coincide but stay distinct to mirror upstream's separate `maxVolumeBps`
// and `surplusBps` definitions, so a future divergence is a one-line change here.
const MAX_VOLUME_BPS: u16 = 9_999;
const MAX_SURPLUS_BPS: u16 = 9_999;

const fn validate_max_volume_bps(field: &'static str, value: u16) -> Result<(), AppDataError> {
    if value == 0 || value > MAX_VOLUME_BPS {
        return Err(AppDataError::InvalidPartnerFee {
            field,
            reason: ValidationReason::OutOfRange {
                details: "value must be an integer in the inclusive range [1, 9999]",
            },
        });
    }
    Ok(())
}

const fn validate_surplus_bps(field: &'static str, value: u16) -> Result<(), AppDataError> {
    if value == 0 || value > MAX_SURPLUS_BPS {
        return Err(AppDataError::InvalidPartnerFee {
            field,
            reason: ValidationReason::OutOfRange {
                details: "value must be an integer in the inclusive range [1, 9999]",
            },
        });
    }
    Ok(())
}

fn validate_recipient(field: &'static str, recipient: &Address) -> Result<(), AppDataError> {
    if recipient.is_zero() {
        return Err(AppDataError::InvalidPartnerFee {
            field,
            reason: ValidationReason::Precondition {
                details: "recipient must not be the zero address",
            },
        });
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn partner_fee_roundtrips_single_and_array_shapes_and_exposes_first_volume_fee() {
        let recipient = Address::new("0x1111111111111111111111111111111111111111")
            .expect("test recipient must be valid");
        let fee = PartnerFee::from(vec![
            PartnerFeePolicy::surplus(250, 100, recipient).expect("surplus policy must validate"),
            PartnerFeePolicy::volume(42, recipient).expect("volume policy must validate"),
        ]);

        let value = fee.to_value();
        let reparsed = PartnerFee::from_value(value.clone()).expect("typed partner fee re-parses");

        assert_eq!(
            value,
            serde_json::json!([
                {
                    "surplusBps": 250,
                    "maxVolumeBps": 100,
                    "recipient": recipient.to_hex_string()
                },
                {
                    "volumeBps": 42,
                    "recipient": recipient.to_hex_string()
                }
            ])
        );
        assert_eq!(reparsed, fee);
        assert_eq!(fee.volume_bps(), Some(42));
        assert_eq!(
            PartnerFee::from(
                PartnerFeePolicy::price_improvement(25, 100, recipient)
                    .expect("price-improvement policy must validate")
            )
            .volume_bps(),
            None
        );
    }

    #[test]
    fn native_deserialize_selects_variant_by_field_presence() {
        let recipient = "0x1111111111111111111111111111111111111111";
        // A single object selects `Single` and the right variant from which
        // basis-point fields are present — the shape both wasm distribution lanes send.
        let volume: PartnerFee =
            serde_json::from_value(serde_json::json!({ "volumeBps": 100, "recipient": recipient }))
                .expect("a volume policy object deserializes as Single(Volume)");
        assert!(matches!(volume, PartnerFee::Single(_)));
        assert_eq!(volume.volume_bps(), Some(100));

        let surplus: PartnerFee = serde_json::from_value(serde_json::json!({
            "surplusBps": 100, "maxVolumeBps": 50, "recipient": recipient
        }))
        .expect("a surplus policy object deserializes as Single(Surplus)");
        assert!(matches!(surplus, PartnerFee::Single(_)));
        assert_eq!(surplus.volume_bps(), None);

        // A JSON array deserializes as `Multiple`.
        let many: PartnerFee = serde_json::from_value(serde_json::json!([
            { "volumeBps": 100, "recipient": recipient },
            { "volumeBps": 200, "recipient": recipient }
        ]))
        .expect("an array deserializes as Multiple");
        assert!(matches!(many, PartnerFee::Multiple(ref policies) if policies.len() == 2));
    }

    #[test]
    fn native_deserialize_rejects_ambiguous_and_underspecified_policies() {
        let recipient = "0x1111111111111111111111111111111111111111";
        // Both volume and surplus present is ambiguous.
        assert!(
            serde_json::from_value::<PartnerFee>(serde_json::json!({
                "volumeBps": 10, "surplusBps": 20, "recipient": recipient
            }))
            .is_err()
        );
        // No basis-point field at all.
        assert!(
            serde_json::from_value::<PartnerFee>(serde_json::json!({ "recipient": recipient }))
                .is_err()
        );
        // Surplus without its required max-volume cap.
        assert!(
            serde_json::from_value::<PartnerFee>(serde_json::json!({
                "surplusBps": 100, "recipient": recipient
            }))
            .is_err()
        );
    }
}