Skip to content

Commit

Permalink
fix(orderbook): age field is set in a proper way (#1851)
Browse files Browse the repository at this point in the history
When orderbook is requested the age field now returns the right age.
  • Loading branch information
rozhkovdmitrii authored and onur-ozkan committed Jun 13, 2023
1 parent e876ee7 commit 609d05a
Showing 1 changed file with 60 additions and 10 deletions.
70 changes: 60 additions & 10 deletions mm2src/mm2_main/src/lp_ordermatch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ use common::executor::{simple_map::AbortableSimpleMap, AbortSettings, AbortableS
SpawnFuture, Timer};
use common::log::{error, warn, LogOnError};
use common::time_cache::TimeCache;
use common::{bits256, log, new_uuid, now_ms, now_sec, now_sec_i64};
use common::{bits256, log, new_uuid, now_ms, now_sec};
use crypto::privkey::SerializableSecp256k1Keypair;
use crypto::{CryptoCtx, CryptoCtxError};
use derive_more::Display;
Expand All @@ -50,6 +50,8 @@ use mm2_number::{construct_detailed, BigDecimal, BigRational, Fraction, MmNumber
use num_traits::identities::Zero;
use parking_lot::Mutex as PaMutex;
use rpc::v1::types::H256 as H256Json;
use serde::ser::SerializeMap;
use serde::Serialize;
use serde_json::{self as json, Value as Json};
use sp_trie::{delta_trie_root, MemoryDB, Trie, TrieConfiguration, TrieDB, TrieDBMut, TrieHash, TrieMut};
use std::collections::hash_map::{Entry, HashMap, RawEntryMut};
Expand Down Expand Up @@ -790,13 +792,33 @@ fn process_get_orderbook_request(ctx: MmArc, base: String, rel: String) -> Resul
Ok(Some(encoded))
}

#[derive(Debug, Deserialize, Serialize)]
enum DeltaOrFullTrie<Key: Eq + std::hash::Hash, Value> {
#[derive(Debug, Deserialize)]
enum DeltaOrFullTrie<Key: Eq + std::hash::Hash + ToString, Value> {
Delta(HashMap<Key, Option<Value>>),
FullTrie(Vec<(Key, Value)>),
}

impl<Key: Eq + std::hash::Hash, V1> DeltaOrFullTrie<Key, V1> {
impl<Key, Value> Serialize for DeltaOrFullTrie<Key, Value>
where
Key: Eq + std::hash::Hash + Serialize + ToString,
Value: Serialize,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
match self {
DeltaOrFullTrie::Delta(delta) => {
let serialized: HashMap<String, Option<&Value>> =
delta.iter().map(|(k, v)| (k.to_string(), v.as_ref())).collect();
serialized.serialize(serializer)
},
DeltaOrFullTrie::FullTrie(full_trie) => full_trie.serialize(serializer),
}
}
}

impl<Key: Eq + std::hash::Hash + ToString, V1> DeltaOrFullTrie<Key, V1> {
pub fn map_to<V2: From<V1>>(self, mut on_each: impl FnMut(&Key, Option<&V1>)) -> DeltaOrFullTrie<Key, V2> {
match self {
DeltaOrFullTrie::Delta(delta) => {
Expand Down Expand Up @@ -858,7 +880,7 @@ where
trie
}

impl<Key: Clone + Eq + std::hash::Hash + TryFromBytes, Value: Clone> DeltaOrFullTrie<Key, Value> {
impl<Key: Clone + Eq + std::hash::Hash + ToString + TryFromBytes, Value: Clone> DeltaOrFullTrie<Key, Value> {
fn from_history(
history: &TrieDiffHistory<Key, Value>,
from_hash: H64,
Expand Down Expand Up @@ -896,11 +918,29 @@ struct SyncPubkeyOrderbookStateRes {
last_signed_pubkey_payload: Vec<u8>,
pair_orders_diff: HashMap<AlbOrderedOrderbookPair, DeltaOrFullTrie<Uuid, OrderbookP2PItem>>,
#[serde(default)]
#[serde(serialize_with = "serialize_map")]
protocol_infos: HashMap<Uuid, BaseRelProtocolInfo>,
#[serde(default)]
#[serde(serialize_with = "serialize_map")]
conf_infos: HashMap<Uuid, OrderConfirmationsSettings>,
}

fn serialize_map<K, V, S>(value: &HashMap<K, V>, serializer: S) -> Result<S::Ok, S::Error>
where
K: ToString + Eq + std::hash::Hash,
V: Serialize,
S: serde::Serializer,
{
let mut map_serializer = serializer.serialize_map(Some(value.len()))?;

for (key, value) in value {
let key_str = key.to_string();
map_serializer.serialize_entry(&key_str, value)?;
}

map_serializer.end()
}

fn process_sync_pubkey_orderbook_state(
ctx: MmArc,
pubkey: String,
Expand Down Expand Up @@ -3956,6 +3996,16 @@ struct OrderbookP2PItem {
created_at: u64,
}

macro_rules! try_get_age_or_default {
($created_at: expr) => {{
let now = now_sec();
now.checked_sub($created_at).unwrap_or_else(|| {
warn!("now - created_at: ({} - {}) caused a u64 underflow", now, $created_at);
Default::default()
})
}};
}

impl OrderbookP2PItem {
fn as_rpc_best_orders_buy(
&self,
Expand Down Expand Up @@ -3985,7 +4035,7 @@ impl OrderbookP2PItem {
min_volume_rat: min_vol_mm.to_ratio(),
min_volume_fraction: min_vol_mm.to_fraction(),
pubkey: self.pubkey.clone(),
age: now_sec_i64(),
age: try_get_age_or_default!(self.created_at),
zcredits: 0,
uuid: self.uuid,
is_mine,
Expand Down Expand Up @@ -4051,7 +4101,7 @@ impl OrderbookP2PItem {
min_volume_rat: min_vol_mm.to_ratio(),
min_volume_fraction: min_vol_mm.to_fraction(),
pubkey: self.pubkey.clone(),
age: now_sec_i64(),
age: try_get_age_or_default!(self.created_at),
zcredits: 0,
uuid: self.uuid,
is_mine,
Expand Down Expand Up @@ -4213,7 +4263,7 @@ impl OrderbookItem {
min_volume_rat: min_vol_mm.to_ratio(),
min_volume_fraction: min_vol_mm.to_fraction(),
pubkey: self.pubkey.clone(),
age: now_sec_i64(),
age: try_get_age_or_default!(self.created_at),
zcredits: 0,
uuid: self.uuid,
is_mine,
Expand Down Expand Up @@ -4249,7 +4299,7 @@ impl OrderbookItem {
min_volume_rat: min_vol_mm.to_ratio(),
min_volume_fraction: min_vol_mm.to_fraction(),
pubkey: self.pubkey.clone(),
age: now_sec_i64(),
age: try_get_age_or_default!(self.created_at),
zcredits: 0,
uuid: self.uuid,
is_mine,
Expand Down Expand Up @@ -5622,7 +5672,7 @@ pub struct RpcOrderbookEntry {
min_volume_rat: BigRational,
min_volume_fraction: Fraction,
pubkey: String,
age: i64,
age: u64,
zcredits: u64,
uuid: Uuid,
is_mine: bool,
Expand Down

0 comments on commit 609d05a

Please sign in to comment.