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
use crate::errors::{ProtocolError, Result};
use crate::graphql;
use crate::graphql::place_limit_order;
use crate::types::neo::PublicKey as NeoPublicKey;
use crate::types::PublicKey;
use crate::types::{
    Asset, AssetAmount, Blockchain, BuyOrSell, Nonce, OrderCancellationPolicy, OrderRate, Rate,
};
use crate::utils::pad_zeros;
use graphql_client::GraphQLQuery;
use std::convert::TryInto;

use super::super::signer::Signer;
use super::super::{general_canonical_string, RequestPayloadSignature, State};
use super::blockchain::{btc, eth, neo, FillOrder};
use super::types::{LimitOrderConstructor, LimitOrderRequest, PayloadNonces};

use futures::lock::Mutex;
use std::sync::Arc;

type LimitOrderMutation = graphql_client::QueryBody<place_limit_order::Variables>;
type BlockchainSignatures = Vec<Option<place_limit_order::BlockchainSignature>>;

impl LimitOrderRequest {
    // 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 fn make_constructor(&self) -> Result<LimitOrderConstructor> {
        // Amount of order always in asset A in ME
        let amount_of_a = self.market.asset_a.with_amount(&self.amount)?;

        // Price is always in terms of asset B in ME
        let b_per_a: Rate = OrderRate::new(&self.price)?.into();
        let a_per_b = b_per_a.invert_rate(None)?;

        let amount_of_b = amount_of_a.exchange_at(&b_per_a, self.market.asset_b)?;

        let (source, rate, destination) = match self.buy_or_sell {
            BuyOrSell::Buy => {
                // Buying: in SC, source is B, rate is B, and moving to asset A
                (amount_of_b, a_per_b.clone(), self.market.asset_a)
            }
            BuyOrSell::Sell => {
                // Selling: in SC, source is A, rate is A, and moving to asset B
                (amount_of_a.clone(), b_per_a.clone(), self.market.asset_b)
            }
        };

        Ok(LimitOrderConstructor {
            me_amount: amount_of_a,
            me_rate: b_per_a,
            market: self.market,
            buy_or_sell: self.buy_or_sell,
            cancellation_policy: self.cancellation_policy,
            allow_taker: self.allow_taker,
            source,
            destination,
            rate,
        })
    }
}

// If an asset is on another chain, convert it into a crosschain nonce
// FIXME: maybe Nonce should also keep track of asset type to make this easier?
fn map_crosschain(nonce: Nonce, chain: Blockchain, asset: Asset) -> Nonce {
    if asset.blockchain() == chain {
        nonce
    } else {
        Nonce::Crosschain
    }
}

impl LimitOrderConstructor {
    /// Helper to transform a limit order into signed fillorder data on every blockchain
    pub fn make_fill_order(
        &self,
        chain: Blockchain,
        pub_key: &PublicKey,
        nonces: &PayloadNonces,
    ) -> Result<FillOrder> {
        // Rate is in "dest per source", so a higher rate is always beneficial to a user
        // Here we insure the minimum rate is the rate they specified
        let min_order = self.rate.clone();
        let max_order = Rate::MaxOrderRate;
        // Amount is specified in the "source" asset
        let amount = self.source.amount.clone();

        let min_order = min_order
            .subtract_fee(Rate::MaxFeeRate.to_bigdecimal()?)?
            .into();
        let fee_rate = Rate::MinFeeRate; // 0

        match chain {
            Blockchain::Ethereum => Ok(FillOrder::Ethereum(eth::FillOrder::new(
                pub_key.to_address()?.try_into()?,
                self.source.asset.into(),
                self.destination.into(),
                map_crosschain(nonces.nonce_from, chain, self.source.asset.into()),
                map_crosschain(nonces.nonce_to, chain, self.destination.into()),
                amount,
                min_order,
                max_order,
                fee_rate,
                nonces.order_nonce,
            ))),
            Blockchain::Bitcoin => Ok(FillOrder::Bitcoin(btc::FillOrder::new(
                map_crosschain(nonces.nonce_from, chain, self.source.asset.into()),
                map_crosschain(nonces.nonce_to, chain, self.destination.into()),
            ))),
            Blockchain::NEO => {
                // FIXME: this can still be improved...
                let neo_pub_key: NeoPublicKey = pub_key.clone().try_into()?;
                let neo_order = neo::FillOrder::new(
                    neo_pub_key,
                    self.source.asset.into(),
                    self.destination.into(),
                    map_crosschain(nonces.nonce_from, chain, self.source.asset.into()),
                    map_crosschain(nonces.nonce_to, chain, self.destination.into()),
                    amount,
                    min_order,
                    max_order,
                    fee_rate,
                    nonces.order_nonce,
                );
                Ok(FillOrder::NEO(neo_order))
            }
        }
    }

    /// Create a signed blockchain payload in the format expected by GraphQL when
    /// given `nonces` and a `Client` as `signer`. FIXME: handle other chains
    pub fn blockchain_signatures(
        &self,
        signer: &mut Signer,
        nonces: &[PayloadNonces],
    ) -> Result<BlockchainSignatures> {
        let mut order_payloads = Vec::new();
        let blockchains = self.market.blockchains();
        for blockchain in blockchains {
            let pub_key = signer.child_public_key(blockchain)?;
            for nonce_group in nonces {
                let fill_order = self.make_fill_order(blockchain, &pub_key, nonce_group)?;
                order_payloads.push(Some(fill_order.to_blockchain_signature(signer)?))
            }
        }
        Ok(order_payloads)
    }

    /// 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<place_limit_order::Variables> {
        let cancel_at = match self.cancellation_policy {
            OrderCancellationPolicy::GoodTilTime(time) => Some(format!("{:?}", time)),
            _ => None,
        };
        let order_args = place_limit_order::Variables {
            payload: place_limit_order::PlaceLimitOrderParams {
                allow_taker: self.allow_taker,
                buy_or_sell: self.buy_or_sell.into(),
                cancel_at: cancel_at,
                cancellation_policy: self.cancellation_policy.into(),
                market_name: self.market.market_name(),
                amount: self.me_amount.clone().try_into()?,
                // These two nonces are deprecated...
                nonce_from: 1234,
                nonce_to: 1234,
                nonce_order: (current_time as u32) as i64, // 4146194029, // Fixme: what do we validate on this?
                timestamp: current_time,
                limit_price: place_limit_order::CurrencyPriceParams {
                    // This format is confusing, but prices are always in
                    // B for an A/B market, so reverse the normal thing
                    currency_a: self.market.asset_b.asset.name().to_string(),
                    currency_b: self.market.asset_a.asset.name().to_string(),
                    amount: self.me_rate.to_bigdecimal()?.to_string(),
                },
                blockchain_signatures: vec![],
            },
            affiliate,
            signature: RequestPayloadSignature::empty().into(),
        };
        Ok(order_args)
    }

    /// Create a signed GraphQL request with blockchain payloads that can be submitted
    /// to Nash
    pub fn signed_graphql_request(
        &self,
        nonces: Vec<PayloadNonces>,
        current_time: i64,
        affiliate: Option<String>,
        signer: &mut Signer,
    ) -> Result<LimitOrderMutation> {
        let mut request = self.graphql_request(current_time, affiliate)?;
        // compute and add blockchain signatures
        let bc_sigs = self.blockchain_signatures(signer, &nonces)?;
        request.payload.blockchain_signatures = bc_sigs;
        // now compute overall request payload signature
        let canonical_string = limit_order_canonical_string(&request);
        let sig: place_limit_order::Signature =
            signer.sign_canonical_string(&canonical_string).into();
        request.signature = sig;
        Ok(graphql::PlaceLimitOrder::build_query(request))
    }

    // Construct payload nonces with source as `from` asset name and destination as
    // `to` asset name. Nonces will be retrieved from current values in `State`
    pub async fn make_payload_nonces(
        &self,
        state: Arc<Mutex<State>>,
        current_time: i64,
    ) -> Result<Vec<PayloadNonces>> {
        let state = state.lock().await;
        let asset_nonces = &state.asset_nonces;
        let (from, to) = match self.buy_or_sell {
            BuyOrSell::Buy => (
                self.market.asset_b.asset.name(),
                self.market.asset_a.asset.name(),
            ),
            BuyOrSell::Sell => (
                self.market.asset_a.asset.name(),
                self.market.asset_b.asset.name(),
            ),
        };
        let nonce_froms: Vec<Nonce> = asset_nonces
            .get(from)
            .ok_or(ProtocolError("Asset nonce for source does not exist"))?
            .iter()
            .map(|nonce| Nonce::Value(*nonce))
            .collect();
        let nonce_tos: Vec<Nonce> = asset_nonces
            .get(to)
            .ok_or(ProtocolError(
                "Asset nonce for destination a does not exist",
            ))?
            .iter()
            .map(|nonce| Nonce::Value(*nonce))
            .collect();
        let mut nonce_combinations = Vec::new();
        for nonce_from in &nonce_froms {
            for nonce_to in &nonce_tos {
                nonce_combinations.push(PayloadNonces {
                    nonce_from: *nonce_from,
                    nonce_to: *nonce_to,
                    order_nonce: Nonce::Value(current_time as u32),
                })
            }
        }
        Ok(nonce_combinations)
    }
}

pub fn limit_order_canonical_string(variables: &place_limit_order::Variables) -> String {
    let serialized_all = serde_json::to_string(variables).unwrap();
    general_canonical_string(
        "place_limit_order".to_string(),
        serde_json::from_str(&serialized_all).unwrap(),
        vec!["blockchain_signatures".to_string()],
    )
}

impl Into<place_limit_order::OrderBuyOrSell> for BuyOrSell {
    fn into(self) -> place_limit_order::OrderBuyOrSell {
        match self {
            BuyOrSell::Buy => place_limit_order::OrderBuyOrSell::BUY,
            BuyOrSell::Sell => place_limit_order::OrderBuyOrSell::SELL,
        }
    }
}

impl From<RequestPayloadSignature> for place_limit_order::Signature {
    fn from(sig: RequestPayloadSignature) -> Self {
        place_limit_order::Signature {
            signed_digest: sig.signed_digest,
            public_key: sig.public_key,
        }
    }
}

impl From<OrderCancellationPolicy> for place_limit_order::OrderCancellationPolicy {
    fn from(policy: OrderCancellationPolicy) -> Self {
        match policy {
            OrderCancellationPolicy::FillOrKill => {
                place_limit_order::OrderCancellationPolicy::FILL_OR_KILL
            }
            OrderCancellationPolicy::GoodTilCancelled => {
                place_limit_order::OrderCancellationPolicy::GOOD_TIL_CANCELLED
            }
            OrderCancellationPolicy::GoodTilTime(_) => {
                place_limit_order::OrderCancellationPolicy::GOOD_TIL_TIME
            }
            OrderCancellationPolicy::ImmediateOrCancel => {
                place_limit_order::OrderCancellationPolicy::IMMEDIATE_OR_CANCEL
            }
        }
    }
}

impl TryInto<place_limit_order::CurrencyAmountParams> for AssetAmount {
    type Error = ProtocolError;
    fn try_into(self) -> Result<place_limit_order::CurrencyAmountParams> {
        Ok(place_limit_order::CurrencyAmountParams {
            amount: pad_zeros(
                &self.amount.to_bigdecimal().to_string(),
                self.amount.precision,
            )?,
            // FIXME: asset.asset is ugly
            currency: self.asset.asset.name().to_string(),
        })
    }
}