pcli/dex_utils/replicate/
debug.rs

1use penumbra_sdk_dex::lp::position::Position;
2use penumbra_sdk_dex::DirectedUnitPair;
3use penumbra_sdk_num::fixpoint::U128x128;
4use serde::Serialize;
5
6#[derive(Serialize)]
7pub struct PayoffPositionEntry {
8    #[serde(
9        serialize_with = "serialize_directed_unit_pair_to_canon",
10        rename = "canonical_pair"
11    )]
12    pub pair: DirectedUnitPair,
13    pub payoff: PayoffPosition,
14    pub current_price: f64,
15    pub index: usize,
16    pub alpha: f64,
17    pub total_k: f64,
18}
19
20/// For debugging purposes. We want to be able to serialize a position
21/// to JSON so that we can pipe it into a Julia notebook. The reason why
22/// this is a separate structure from [`position::Position`] is that we
23/// might want to do extra processing, rounding, etc. and we'd rather note
24/// clutter it with serialization methods that are useful for narrow purposes.
25#[derive(Serialize)]
26pub struct PayoffPosition {
27    pub p: f64,
28    pub q: f64,
29    pub k: f64,
30    pub r1: f64,
31    pub r2: f64,
32    pub fee: f64,
33}
34
35impl PayoffPosition {
36    pub fn from_position(pair: DirectedUnitPair, position: Position) -> PayoffPosition {
37        let oriented_phi = position
38            .phi
39            .orient_end(pair.end.id())
40            .expect("end is part of the position");
41        let p = U128x128::ratio(oriented_phi.p.value(), pair.end.unit_amount().value())
42            .expect("p is positive")
43            .into();
44        let q = U128x128::ratio(oriented_phi.q.value(), pair.start.unit_amount().value())
45            .expect("q is positive")
46            .into();
47
48        let r1 = position
49            .reserves_for(pair.start.id())
50            .expect("start is part of the position");
51        let r2 = position
52            .reserves_for(pair.end.id())
53            .expect("end is part of the position");
54        let r1 = U128x128::ratio(r1.value(), pair.start.unit_amount().value())
55            .expect("r1 is positive")
56            .into();
57        let r2 = U128x128::ratio(r2.value(), pair.end.unit_amount().value())
58            .expect("r2 is positive")
59            .into();
60        let k = p * r1 + q * r2;
61        let k = k / p;
62        let fee = position.phi.component.fee as f64;
63        PayoffPosition {
64            fee,
65            p,
66            q,
67            k,
68            r1,
69            r2,
70        }
71    }
72}
73
74fn serialize_directed_unit_pair_to_canon<S>(
75    pair: &DirectedUnitPair,
76    serializer: S,
77) -> Result<S::Ok, S::Error>
78where
79    S: serde::Serializer,
80{
81    serializer.serialize_str(&pair.to_canonical_string())
82}