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
use std::collections::HashMap;

use anyhow::Result;
use cosmwasm_std::{
    from_json, to_json_binary, wasm_execute, CosmosMsg, Empty, Event, IbcBasicResponse,
    IbcReceiveResponse, Response, SubMsg, WasmMsg,
};
use cw2::ContractVersion;
use serde::de::DeserializeOwned;
use serde::Serialize;

use crate::ibc::{ack_fail, ack_success};
#[cfg(debug_assertions)]
use crate::prelude::*;

/// Helper data type, following builder pattern, for constructing a [Response].
pub struct ResponseBuilder {
    resp: Response,
    event_type: EventType,
    event_type_count: HashMap<String, u32>,
}

enum EventType {
    MuteEvents,
    EmitEvents {
        common_attrs: Vec<(&'static str, String)>,
    },
}

fn standard_event_attributes(
    ContractVersion { contract, version }: ContractVersion,
) -> Vec<(&'static str, String)> {
    vec![
        ("levana_protocol", "perps".to_string()),
        ("contract_version", version),
        ("contract_name", contract),
    ]
}

impl ResponseBuilder {
    /// Initialize a new builder.
    pub fn new(contract_version: ContractVersion) -> Self {
        ResponseBuilder {
            resp: Response::new(),
            event_type: EventType::EmitEvents {
                common_attrs: standard_event_attributes(contract_version),
            },
            event_type_count: HashMap::new(),
        }
    }

    /// Create a response where the event methods are no-ops.
    pub fn new_mute_events() -> Self {
        ResponseBuilder {
            resp: Response::new(),
            event_type: EventType::MuteEvents,
            event_type_count: HashMap::new(),
        }
    }

    /// Finalize the builder and generate the final response.
    pub fn into_response(self) -> Response {
        self.resp
    }

    /// Add a new [CosmosMsg] to the response.
    pub fn add_message(&mut self, msg: impl Into<CosmosMsg<Empty>>) {
        self.resp.messages.push(SubMsg::new(msg.into()));
    }

    /// Add a submessage for instantiating a new contract.
    pub fn add_instantiate_submessage<
        I: Into<u64>,
        A: Into<String>,
        L: Into<String>,
        T: Serialize,
    >(
        &mut self,
        id: I,
        admin: A,
        code_id: u64,
        label: L,
        msg: &T,
    ) -> Result<()> {
        let payload = to_json_binary(msg)?;

        // the common case
        // more fine-grained control via raw submessage
        let msg = WasmMsg::Instantiate {
            admin: Some(admin.into()),
            code_id,
            msg: payload,
            funds: vec![],
            label: label.into(),
        };
        self.add_raw_submessage(
            // the common case
            // more fine-grained control via raw submessage
            SubMsg::reply_on_success(msg, id.into()),
        );

        Ok(())
    }

    /// Add a new one-shot submessage execution.
    pub fn add_execute_submessage_oneshot<C: Into<String>, T: Serialize>(
        &mut self,
        contract: C,
        msg: &T,
    ) -> Result<()> {
        self.add_raw_submessage(
            // the common case
            // more fine-grained control via raw submessage
            SubMsg::new(wasm_execute(
                contract,
                msg,
                // the common case, no coins
                vec![],
            )?),
        );

        Ok(())
    }

    /// Add a raw submsg. Helpful if you need to handle a reply.
    pub fn add_raw_submessage(&mut self, msg: SubMsg<Empty>) {
        self.resp.messages.push(msg);
    }

    /// Add an event to the response.
    pub fn add_event(&mut self, event: impl Into<Event>) {
        let event: Event = event.into();

        #[cfg(debug_assertions)]
        {
            match event.ty.as_ref() {
                "funding-payment" => debug_log!(DebugLog::FundingPaymentEvent, "{:#?}", event),
                "funding-rate-change" => {
                    debug_log!(DebugLog::FundingRateChangeEvent, "{:#?}", event)
                }
                "fee" => {
                    if let Ok(source) = event.string_attr("source") {
                        match source.as_str() {
                            "trading" => debug_log!(DebugLog::TradingFeeEvent, "{:#?}", event),
                            "borrow" => debug_log!(DebugLog::BorrowFeeEvent, "{:#?}", event),
                            "delta-neutrality" => {
                                debug_log!(DebugLog::DeltaNeutralityFeeEvent, "{:#?}", event)
                            }
                            "limit-order" => {
                                debug_log!(DebugLog::LimitOrderFeeEvent, "{:#?}", event)
                            }
                            _ => {}
                        }
                    }
                }
                "delta-neutrality-ratio" => {
                    debug_log!(DebugLog::DeltaNeutralityRatioEvent, "{:#?}", event)
                }
                _ => {}
            }
        }

        match &self.event_type {
            EventType::MuteEvents => (),
            EventType::EmitEvents { common_attrs } => {
                let mut event = event.add_attributes(common_attrs.clone());

                let event_type_count = self.event_type_count.entry(event.ty.clone()).or_default();

                if *event_type_count > 0 {
                    event.ty = format!("{}-{}", event.ty, *event_type_count);
                }

                *event_type_count += 1;

                self.resp.events.push(event)
            }
        }
    }

    /// Set response data
    pub fn set_data(&mut self, data: &impl Serialize) -> Result<()> {
        match self.resp.data {
            None => {
                let data = to_json_binary(data)?;
                self.resp.data = Some(data);
            }
            Some(_) => anyhow::bail!("data already exists, use update_data instead"),
        }

        Ok(())
    }

    /// Get response data
    pub fn get_data<T: DeserializeOwned>(&self) -> Result<Option<T>> {
        match &self.resp.data {
            None => Ok(None),
            Some(data) => Ok(Some(from_json(data)?)),
        }
    }

    /// Remove response data
    pub fn remove_data(&mut self) {
        self.resp.data = None;
    }

    /// Update response data
    pub fn update_data<T: Serialize + DeserializeOwned>(
        &mut self,
        f: impl FnOnce(Option<T>) -> T,
    ) -> Result<()> {
        let data = self.get_data()?;
        let updated = f(data);
        self.resp.data = Some(to_json_binary(&updated)?);

        Ok(())
    }

    /// Turn the accumulated response into an IBC Basic response
    pub fn into_ibc_response(self) -> IbcBasicResponse {
        let mut resp = IbcBasicResponse::default();
        resp.messages = self.resp.messages;
        resp.attributes = self.resp.attributes;
        resp.events = self.resp.events;

        resp
    }

    /// Turn the accumulated response into an IBC Receive success response
    pub fn into_ibc_recv_response_success(self) -> IbcReceiveResponse {
        let mut resp = IbcReceiveResponse::new(ack_success());
        resp.messages = self.resp.messages;
        resp.attributes = self.resp.attributes;
        resp.events = self.resp.events;
        resp
    }

    /// Turn the accumulated response into an IBC Receive fail response
    pub fn into_ibc_recv_response_fail(self, error: anyhow::Error) -> IbcReceiveResponse {
        let mut resp = IbcReceiveResponse::new(ack_fail(error));
        resp.messages = self.resp.messages;
        resp.attributes = self.resp.attributes;
        resp.events = self.resp.events;
        resp
    }
}