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
use super::super::asset_nonces::AssetNoncesRequest;
use super::super::dh_fill_pool::DhFillPoolRequest;
use super::super::list_markets::ListMarketsRequest;
use super::super::sign_all_states::SignAllStates;
use super::super::{
    serializable_to_json, try_response_from_json, NashProtocol, ResponseOrError, State,
};
use super::super::{NashProtocolRequest, ProtocolHook};
use crate::errors::Result;
use crate::graphql::place_limit_order;
use crate::graphql::place_market_order;
use crate::types::{
    AssetAmount, AssetofPrecision, Blockchain, BuyOrSell, Market, Nonce, OrderCancellationPolicy,
    OrderStatus, OrderType, Rate,
};
use crate::utils::current_time_as_i64;
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use tokio::sync::RwLock;
use std::sync::Arc;
use tracing::trace;

/// Request to place limit orders on Nash exchange. On an A/B market
/// price amount will always be in terms of A and price in terms of B.
#[derive(Clone, Debug)]
pub struct LimitOrderRequest {
    pub market: String,
    pub buy_or_sell: BuyOrSell,
    pub amount: String,
    pub price: String,
    pub cancellation_policy: OrderCancellationPolicy,
    pub allow_taker: bool,
}

#[derive(Clone, Debug)]
pub struct MarketOrderRequest {
    pub market: String,
    pub amount: String
}

impl LimitOrderRequest {
    pub fn new(
        market: String,
        buy_or_sell: BuyOrSell,
        amount_a: &str,
        price_b: &str,
        cancellation_policy: OrderCancellationPolicy,
        allow_taker: bool,
    ) -> Result<Self> {
        Ok(Self {
            market,
            buy_or_sell,
            amount: amount_a.to_string(),
            price: price_b.to_string(),
            cancellation_policy,
            allow_taker,
        })
    }
}

impl MarketOrderRequest {
    pub fn new(
        market: String,
        amount_a: &str,
    ) -> Result<Self> {
        Ok(Self {
            market,
            amount: amount_a.to_string(),
        })
    }
}

/// A helper type for constructing blockchain payloads and GraphQL requests
pub struct LimitOrderConstructor {
    // These fields are for GraphQL
    pub buy_or_sell: BuyOrSell,
    pub market: Market,
    pub me_amount: AssetAmount,
    pub me_rate: Rate,
    pub cancellation_policy: OrderCancellationPolicy,
    pub allow_taker: bool,
    // These fields are for the smart contracts
    pub source: AssetAmount,
    pub destination: AssetofPrecision,
    pub rate: Rate,
}

pub struct MarketOrderConstructor {
    // These fields are for GraphQL
    pub market: Market,
    pub me_amount: AssetAmount,
    // These fields are for the smart contracts
    pub source: AssetAmount,
    pub destination: AssetofPrecision,
}

/// Helper type to hold all nonces for payload construction and make
/// passing them as arguments more descriptive.
#[derive(Clone, Debug, Copy)]
pub struct PayloadNonces {
    pub nonce_from: Nonce,
    pub nonce_to: Nonce,
    pub order_nonce: Nonce,
}

/// Response from server once we have placed a limit order
#[derive(Clone, Debug)]
pub struct PlaceOrderResponse {
    pub remaining_orders: u64,
    pub order_id: String,
    pub status: OrderStatus,
    pub placed_at: DateTime<Utc>,
    pub order_type: OrderType,
    pub buy_or_sell: BuyOrSell,
    pub market_name: String,
}

fn get_required_hooks(state: &State) -> Result<Vec<ProtocolHook>> {
    let mut hooks = Vec::new();
    // If we need assets or markets list, pull them
    match (&state.assets, &state.markets) {
        (None, _) | (_, None) => {
            hooks.push(ProtocolHook::Protocol(NashProtocolRequest::ListMarkets(
                ListMarketsRequest,
            )));
        }
        _ => {}
    }
    // If have run out of r values, get more before running this pipeline
    for chain in Blockchain::all() {
        // 10 here is too much, but we can use multiple r-values in a single request
        if state.signer()?.remaining_r_vals(chain) <= 10 {
            trace!("Triggering FillPool (place_order) for {:?}", chain);
            hooks.push(ProtocolHook::Protocol(NashProtocolRequest::DhFill(
                DhFillPoolRequest::new(chain)?,
            )));
        }
    }
    // Retrieve asset nonces if we don't have them or an error triggered need to refresh
    match (state.asset_nonces.as_ref(), state.assets_nonces_refresh) {
        (None, _) | (_, true) => {
            hooks.push(ProtocolHook::Protocol(NashProtocolRequest::AssetNonces(
                AssetNoncesRequest::new(),
            )));
        }
        _ => {}
    }
    // If we are about to run out of orders...
    if !state.dont_sign_states && state.remaining_orders < 20 {
        // Need to sign states
        hooks.push(ProtocolHook::SignAllState(SignAllStates::new()));
        // After signing states, need to update nonces again
        hooks.push(ProtocolHook::Protocol(NashProtocolRequest::AssetNonces(
            AssetNoncesRequest::new(),
        )));
    }
    Ok(hooks)
}

#[async_trait]
impl NashProtocol for LimitOrderRequest {
    type Response = PlaceOrderResponse;

    async fn get_semaphore(&self, state: Arc<RwLock<State>>) -> Option<Arc<tokio::sync::Semaphore>> {
        Some(state.read().await.place_order_semaphore.clone())
    }

    async fn graphql(&self, state: Arc<RwLock<State>>) -> Result<serde_json::Value> {
        let builder = self.make_constructor(state.clone()).await?;
        let time = current_time_as_i64();
        let nonces = builder.make_payload_nonces(state.clone(), time).await?;
        let mut state = state.write().await;
        // TODO: move this to process response, and incorporate error into process response
        // would be much cleaner
        if state.remaining_orders > 0 {
            state.remaining_orders -= 1;
        }
        let affiliate = state.affiliate_code.clone();
        let signer = state.signer_mut()?;
        let query = builder.signed_graphql_request(nonces, time, affiliate, signer)?;
        serializable_to_json(&query)
    }

    async fn response_from_json(
        &self,
        response: serde_json::Value,
        _state: Arc<RwLock<State>>
    ) -> Result<ResponseOrError<Self::Response>> {
        try_response_from_json::<PlaceOrderResponse, place_limit_order::ResponseData>(response)
    }
    /// Update the number of orders remaining before state sync
    async fn process_response(
        &self,
        response: &Self::Response,
        state: Arc<RwLock<State>>,
    ) -> Result<()> {
        let mut state = state.write().await;
        state.remaining_orders = response.remaining_orders;
        Ok(())
    }
    /// Potentially get more r values or sign states before placing an order
    async fn run_before(&self, state: Arc<RwLock<State>>) -> Result<Option<Vec<ProtocolHook>>> {
        let state = state.read().await;
        get_required_hooks(&state).map(Some)
    }
}


#[async_trait]
impl NashProtocol for MarketOrderRequest {
    type Response = PlaceOrderResponse;

    async fn get_semaphore(&self, state: Arc<RwLock<State>>) -> Option<Arc<tokio::sync::Semaphore>> {
        Some(state.read().await.place_order_semaphore.clone())
    }

    async fn graphql(&self, state: Arc<RwLock<State>>) -> Result<serde_json::Value> {
        let builder = self.make_constructor(state.clone()).await?;
        let time = current_time_as_i64();
        let nonces = builder.make_payload_nonces(state.clone(), time).await?;
        let mut state = state.write().await;
        // TODO: move this to process response, and incorporate error into process response
        // would be much cleaner
        if state.remaining_orders > 0 {
            state.remaining_orders -= 1;
        }
        let affiliate = state.affiliate_code.clone();
        let signer = state.signer_mut()?;
        let query = builder.signed_graphql_request(nonces, time, affiliate, signer)?;
        serializable_to_json(&query)
    }

    async fn response_from_json(
        &self,
        response: serde_json::Value,
        _state: Arc<RwLock<State>>
    ) -> Result<ResponseOrError<Self::Response>> {
        try_response_from_json::<PlaceOrderResponse, place_market_order::ResponseData>(response)
    }
    /// Update the number of orders remaining before state sync
    async fn process_response(
        &self,
        response: &Self::Response,
        state: Arc<RwLock<State>>,
    ) -> Result<()> {
        let mut state = state.write().await;
        state.remaining_orders = response.remaining_orders;
        Ok(())
    }
    /// Potentially get more r values or sign states before placing an order
    async fn run_before(&self, state: Arc<RwLock<State>>) -> Result<Option<Vec<ProtocolHook>>> {
        let state = state.read().await;
        get_required_hooks(&state).map(Some)
    }
}