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
use crate::errors::Result;
use crate::graphql::place_limit_order;
use crate::graphql::place_market_order;
use super::super::State;
use super::types::{
    LimitOrdersConstructor, LimitOrdersRequest,
    MarketOrdersConstructor, MarketOrdersRequest
};

use tokio::sync::RwLock;
use std::sync::Arc;

use std::collections::HashMap;
use crate::protocol::multi_request::DynamicQueryBody;

impl LimitOrdersRequest {
    // Buy or sell `amount` of `A` in price of `B` for an A/B market. Returns a builder struct
    // of `LimitOrderConstructor` that can be used to create smart contract and graphql payloads
    pub async fn make_constructor(&self, state: Arc<RwLock<State>>) -> Result<LimitOrdersConstructor> {
        let mut constructors = Vec::new();
        for request in &self.requests {
            constructors.push(request.make_constructor(state.clone()).await?);
        }
        Ok(LimitOrdersConstructor { constructors })
    }
}

impl MarketOrdersRequest {
    // Buy or sell `amount` of `A` in price of `B` for an A/B market. Returns a builder struct
    // of `MarketOrderConstructor` that can be used to create smart contract and graphql payloads
    pub async fn make_constructor(&self, state: Arc<RwLock<State>>) -> Result<MarketOrdersConstructor> {
        let mut constructors = Vec::new();
        for request in &self.requests {
            constructors.push(request.make_constructor(state.clone()).await?);
        }
        Ok(MarketOrdersConstructor { constructors })
    }
}

impl LimitOrdersConstructor {
    /// Create a GraphQL request with everything filled in besides blockchain order payloads
    /// and signatures (for both the overall request and blockchain payloads)
    pub fn graphql_request(
        &self,
        current_time: i64,
        affiliate: Option<String>,
    ) -> Result<Vec<place_limit_order::Variables>> {
        let mut variables = Vec::new();
        for (index, variable) in self.constructors.iter().enumerate() {
            variables.push(variable.graphql_request(current_time + index as i64, affiliate.clone())?);
        }
        Ok(variables)
    }

    /// Create a signed GraphQL request with blockchain payloads that can be submitted
    /// to Nash
    pub async fn signed_graphql_request(
        &self,
        current_time: i64,
        affiliate: Option<String>,
        state: Arc<RwLock<State>>,
        order_precision: u32,
        fee_precision: u32
    ) -> Result<DynamicQueryBody> {
        let variables = self.graphql_request(current_time, affiliate)?;
        let mut map = HashMap::new();
        let mut params = String::new();
        let mut calls = String::new();
        for (index, (variable, constructor)) in variables.into_iter().zip(self.constructors.iter()).enumerate() {
            // FIXME: This current_time + index for nonces is replicated in graphql_request. We would benefit to abstract this logic somewhere.
            let nonces = constructor.make_payload_nonces(state.clone(), current_time + index as i64).await?;
            let state = state.read().await;
            let signer = state.signer()?;
            let variable = constructor.sign_graphql_request(variable, nonces, signer, order_precision, fee_precision)?;

            // FIXME: This is also replicated in MarketOrdersConstructor::signed_graphql_request
            let payload = format!("payload{}", index);
            let signature = format!("signature{}", index);
            let affiliate = format!("affiliate{}", index);
            params = if index == 0 { params } else { format!("{}, ", params)};
            params = format!("{}${}: PlaceLimitOrderParams!, ${}: Signature!, ${}: AffiliateDeveloperCode", params, payload, signature, affiliate);
            calls = format!(r#"
                {}
                response{}: placeLimitOrder(payload: ${}, signature: ${}, affiliateDeveloperCode: ${}) {{
                    id
                    status
                    ordersTillSignState,
                    buyOrSell,
                    market {{
                        name
                    }},
                    placedAt,
                    type
                }}
                "#, calls, index, payload, signature, affiliate);
            map.insert(payload, serde_json::to_value(variable.payload).unwrap());
            map.insert(signature, serde_json::to_value(variable.signature).unwrap());
            map.insert(affiliate, serde_json::to_value(variable.affiliate).unwrap());
        }
        Ok(DynamicQueryBody {
            variables: map,
            operation_name: "PlaceLimitOrder",
            query: format!(r#"
                mutation PlaceLimitOrder({}) {{
                    {}
                }}
            "#, params, calls)
        })
    }
}

impl MarketOrdersConstructor {
    /// Create a GraphQL request with everything filled in besides blockchain order payloads
    /// and signatures (for both the overall request and blockchain payloads)
    pub fn graphql_request(
        &self,
        current_time: i64,
        affiliate: Option<String>,
    ) -> Result<Vec<place_market_order::Variables>> {
        let mut variables = Vec::new();
        for (index, variable) in self.constructors.iter().enumerate() {
            variables.push(variable.graphql_request(current_time + index as i64, affiliate.clone())?);
        }
        Ok(variables)
    }

    /// Create a signed GraphQL request with blockchain payloads that can be submitted
    /// to Nash
    pub async fn signed_graphql_request(
        &self,
        current_time: i64,
        affiliate: Option<String>,
        state: Arc<RwLock<State>>,
        order_precision: u32,
        fee_precision: u32
    ) -> Result<DynamicQueryBody> {
        let variables = self.graphql_request(current_time, affiliate)?;
        let mut map = HashMap::new();
        let mut params = String::new();
        let mut calls = String::new();
        for (index, (variable, constructor)) in variables.into_iter().zip(self.constructors.iter()).enumerate() {
            // FIXME: This current_time + index for nonces is replicated in graphql_request. We would benefit to abstract this logic somewhere.
            let nonces = constructor.make_payload_nonces(state.clone(), current_time + index as i64).await?;
            let state = state.read().await;
            let signer = state.signer()?;
            let variable = constructor.sign_graphql_request(variable, nonces, signer, order_precision, fee_precision)?;

            let payload = format!("payload{}", index);
            let signature = format!("signature{}", index);
            let affiliate = format!("affiliate{}", index);
            params = if index == 0 { params } else { format!("{}, ", params)};
            params = format!("{}${}: PlaceMarketOrderParams!, ${}: Signature!, ${}: AffiliateDeveloperCode", params, payload, signature, affiliate);
            calls = format!(r#"
                {}
                response{}: placeMarketOrder(payload: ${}, signature: ${}, affiliateDeveloperCode: ${}) {{
                    id
                    status
                    ordersTillSignState,
                    buyOrSell,
                    market {{
                        name
                    }},
                    placedAt,
                    type
                }}
                "#, calls, index, payload, signature, affiliate);
            map.insert(payload, serde_json::to_value(variable.payload).unwrap());
            map.insert(signature, serde_json::to_value(variable.signature).unwrap());
            map.insert(affiliate, serde_json::to_value(variable.affiliate).unwrap());
        }
        Ok(DynamicQueryBody {
            variables: map,
            operation_name: "PlaceMarketOrder",
            query: format!(r#"
                mutation PlaceMarketOrder({}) {{
                    {}
                }}
            "#, params, calls)
        })
    }
}