Skip to content

Commit 87c8c0f

Browse files
authored
Merge pull request #2125 from get10101/chore/add-rollover-to-protocols-table
chore(dlc_protocol): Track rollovers in dlc protocol table
2 parents 2c3b1fa + b2b0e3f commit 87c8c0f

File tree

14 files changed

+525
-262
lines changed

14 files changed

+525
-262
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
2+
ALTER TABLE dlc_protocols DROP COLUMN IF EXISTS "protocol_type";
3+
4+
DROP TYPE IF EXISTS "Protocol_Type_Type";
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
2+
CREATE TYPE "Protocol_Type_Type" AS ENUM ('open', 'renew', 'settle', 'close', 'force-close', 'rollover');
3+
4+
ALTER TABLE dlc_protocols ADD COLUMN "protocol_type" "Protocol_Type_Type" NOT NULL DEFAULT 'open';

coordinator/src/db/custom_types.rs

+31-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
use crate::db::channels::ChannelState;
22
use crate::db::dlc_messages::MessageType;
33
use crate::db::dlc_protocols::DlcProtocolState;
4+
use crate::db::dlc_protocols::DlcProtocolType;
45
use crate::db::polls::PollType;
56
use crate::db::positions::ContractSymbol;
67
use crate::db::positions::PositionState;
@@ -11,6 +12,7 @@ use crate::schema::sql_types::MessageTypeType;
1112
use crate::schema::sql_types::PollTypeType;
1213
use crate::schema::sql_types::PositionStateType;
1314
use crate::schema::sql_types::ProtocolStateType;
15+
use crate::schema::sql_types::ProtocolTypeType;
1416
use diesel::deserialize;
1517
use diesel::deserialize::FromSql;
1618
use diesel::pg::Pg;
@@ -199,7 +201,35 @@ impl FromSql<ProtocolStateType, Pg> for DlcProtocolState {
199201
b"Pending" => Ok(DlcProtocolState::Pending),
200202
b"Success" => Ok(DlcProtocolState::Success),
201203
b"Failed" => Ok(DlcProtocolState::Failed),
202-
_ => Err("Unrecognized enum variant for ContractTransactionType".into()),
204+
_ => Err("Unrecognized enum variant for ProtocolStateType".into()),
205+
}
206+
}
207+
}
208+
209+
impl ToSql<ProtocolTypeType, Pg> for DlcProtocolType {
210+
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, Pg>) -> serialize::Result {
211+
match *self {
212+
DlcProtocolType::Open => out.write_all(b"open")?,
213+
DlcProtocolType::Settle => out.write_all(b"settle")?,
214+
DlcProtocolType::Renew => out.write_all(b"renew")?,
215+
DlcProtocolType::Rollover => out.write_all(b"rollover")?,
216+
DlcProtocolType::Close => out.write_all(b"close")?,
217+
DlcProtocolType::ForceClose => out.write_all(b"force-close")?,
218+
}
219+
Ok(IsNull::No)
220+
}
221+
}
222+
223+
impl FromSql<ProtocolTypeType, Pg> for DlcProtocolType {
224+
fn from_sql(bytes: PgValue<'_>) -> deserialize::Result<Self> {
225+
match bytes.as_bytes() {
226+
b"open" => Ok(DlcProtocolType::Open),
227+
b"settle" => Ok(DlcProtocolType::Settle),
228+
b"renew" => Ok(DlcProtocolType::Renew),
229+
b"rollover" => Ok(DlcProtocolType::Rollover),
230+
b"close" => Ok(DlcProtocolType::Close),
231+
b"force-close" => Ok(DlcProtocolType::ForceClose),
232+
_ => Err("Unrecognized enum variant for ProtocolTypeType".into()),
203233
}
204234
}
205235
}

coordinator/src/db/dlc_protocols.rs

+78-19
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
1+
use crate::db;
12
use crate::dlc_protocol;
23
use crate::dlc_protocol::ProtocolId;
34
use crate::schema::dlc_protocols;
45
use crate::schema::sql_types::ProtocolStateType;
6+
use crate::schema::sql_types::ProtocolTypeType;
57
use bitcoin::secp256k1::PublicKey;
68
use diesel::query_builder::QueryId;
79
use diesel::AsExpression;
@@ -37,6 +39,26 @@ impl QueryId for ProtocolStateType {
3739
}
3840
}
3941

42+
#[derive(Debug, Clone, Copy, PartialEq, FromSqlRow, AsExpression, Eq, Hash)]
43+
#[diesel(sql_type = ProtocolTypeType)]
44+
pub(crate) enum DlcProtocolType {
45+
Open,
46+
Renew,
47+
Settle,
48+
Close,
49+
ForceClose,
50+
Rollover,
51+
}
52+
53+
impl QueryId for ProtocolTypeType {
54+
type QueryId = ProtocolTypeType;
55+
const HAS_STATIC_QUERY_ID: bool = false;
56+
57+
fn query_id() -> Option<TypeId> {
58+
None
59+
}
60+
}
61+
4062
#[derive(Queryable, Debug)]
4163
#[diesel(table_name = protocols)]
4264
#[allow(dead_code)] // We have to allow dead code here because diesel needs the fields to be able to derive queryable.
@@ -49,17 +71,52 @@ pub(crate) struct DlcProtocol {
4971
pub protocol_state: DlcProtocolState,
5072
pub trader_pubkey: String,
5173
pub timestamp: OffsetDateTime,
74+
pub protocol_type: DlcProtocolType,
5275
}
5376

5477
pub(crate) fn get_dlc_protocol(
5578
conn: &mut PgConnection,
5679
protocol_id: ProtocolId,
5780
) -> QueryResult<dlc_protocol::DlcProtocol> {
58-
let contract_transaction: DlcProtocol = dlc_protocols::table
81+
let dlc_protocol: DlcProtocol = dlc_protocols::table
5982
.filter(dlc_protocols::protocol_id.eq(protocol_id.to_uuid()))
6083
.first(conn)?;
6184

62-
Ok(dlc_protocol::DlcProtocol::from(contract_transaction))
85+
let protocol_type = match dlc_protocol.protocol_type {
86+
DlcProtocolType::Open => {
87+
let trade_params = db::trade_params::get(conn, protocol_id)?;
88+
dlc_protocol::DlcProtocolType::Open { trade_params }
89+
}
90+
DlcProtocolType::Renew => {
91+
let trade_params = db::trade_params::get(conn, protocol_id)?;
92+
dlc_protocol::DlcProtocolType::Renew { trade_params }
93+
}
94+
DlcProtocolType::Settle => {
95+
let trade_params = db::trade_params::get(conn, protocol_id)?;
96+
dlc_protocol::DlcProtocolType::Settle { trade_params }
97+
}
98+
DlcProtocolType::Close => dlc_protocol::DlcProtocolType::Close {
99+
trader: PublicKey::from_str(&dlc_protocol.trader_pubkey).expect("valid public key"),
100+
},
101+
DlcProtocolType::ForceClose => dlc_protocol::DlcProtocolType::ForceClose {
102+
trader: PublicKey::from_str(&dlc_protocol.trader_pubkey).expect("valid public key"),
103+
},
104+
DlcProtocolType::Rollover => dlc_protocol::DlcProtocolType::Rollover {
105+
trader: PublicKey::from_str(&dlc_protocol.trader_pubkey).expect("valid public key"),
106+
},
107+
};
108+
109+
let protocol = dlc_protocol::DlcProtocol {
110+
id: dlc_protocol.protocol_id.into(),
111+
timestamp: dlc_protocol.timestamp,
112+
channel_id: DlcChannelId::from_hex(&dlc_protocol.channel_id).expect("valid dlc channel id"),
113+
contract_id: ContractId::from_hex(&dlc_protocol.contract_id).expect("valid contract id"),
114+
trader: PublicKey::from_str(&dlc_protocol.trader_pubkey).expect("valid public key"),
115+
protocol_state: dlc_protocol.protocol_state.into(),
116+
protocol_type,
117+
};
118+
119+
Ok(protocol)
63120
}
64121

65122
pub(crate) fn set_dlc_protocol_state_to_failed(
@@ -81,8 +138,8 @@ pub(crate) fn set_dlc_protocol_state_to_failed(
81138
pub(crate) fn set_dlc_protocol_state_to_success(
82139
conn: &mut PgConnection,
83140
protocol_id: ProtocolId,
84-
contract_id: ContractId,
85-
channel_id: DlcChannelId,
141+
contract_id: &ContractId,
142+
channel_id: &DlcChannelId,
86143
) -> QueryResult<()> {
87144
let affected_rows = diesel::update(dlc_protocols::table)
88145
.filter(dlc_protocols::protocol_id.eq(protocol_id.to_uuid()))
@@ -104,8 +161,9 @@ pub(crate) fn create(
104161
conn: &mut PgConnection,
105162
protocol_id: ProtocolId,
106163
previous_protocol_id: Option<ProtocolId>,
107-
contract_id: ContractId,
108-
channel_id: DlcChannelId,
164+
contract_id: &ContractId,
165+
channel_id: &DlcChannelId,
166+
protocol_type: dlc_protocol::DlcProtocolType,
109167
trader: &PublicKey,
110168
) -> QueryResult<()> {
111169
let affected_rows = diesel::insert_into(dlc_protocols::table)
@@ -117,6 +175,7 @@ pub(crate) fn create(
117175
dlc_protocols::protocol_state.eq(DlcProtocolState::Pending),
118176
dlc_protocols::trader_pubkey.eq(trader.to_string()),
119177
dlc_protocols::timestamp.eq(OffsetDateTime::now_utc()),
178+
dlc_protocols::protocol_type.eq(DlcProtocolType::from(protocol_type)),
120179
))
121180
.execute(conn)?;
122181

@@ -127,19 +186,6 @@ pub(crate) fn create(
127186
Ok(())
128187
}
129188

130-
impl From<DlcProtocol> for dlc_protocol::DlcProtocol {
131-
fn from(value: DlcProtocol) -> Self {
132-
dlc_protocol::DlcProtocol {
133-
id: value.protocol_id.into(),
134-
timestamp: value.timestamp,
135-
channel_id: DlcChannelId::from_hex(&value.channel_id).expect("valid dlc channel id"),
136-
contract_id: ContractId::from_hex(&value.contract_id).expect("valid contract id"),
137-
trader: PublicKey::from_str(&value.trader_pubkey).expect("valid public key"),
138-
protocol_state: value.protocol_state.into(),
139-
}
140-
}
141-
}
142-
143189
impl From<dlc_protocol::DlcProtocolState> for DlcProtocolState {
144190
fn from(value: dlc_protocol::DlcProtocolState) -> Self {
145191
match value {
@@ -159,3 +205,16 @@ impl From<DlcProtocolState> for dlc_protocol::DlcProtocolState {
159205
}
160206
}
161207
}
208+
209+
impl From<dlc_protocol::DlcProtocolType> for DlcProtocolType {
210+
fn from(value: dlc_protocol::DlcProtocolType) -> Self {
211+
match value {
212+
dlc_protocol::DlcProtocolType::Open { .. } => DlcProtocolType::Open,
213+
dlc_protocol::DlcProtocolType::Renew { .. } => DlcProtocolType::Renew,
214+
dlc_protocol::DlcProtocolType::Settle { .. } => DlcProtocolType::Settle,
215+
dlc_protocol::DlcProtocolType::Close { .. } => DlcProtocolType::Close,
216+
dlc_protocol::DlcProtocolType::ForceClose { .. } => DlcProtocolType::ForceClose,
217+
dlc_protocol::DlcProtocolType::Rollover { .. } => DlcProtocolType::Rollover,
218+
}
219+
}
220+
}

coordinator/src/db/positions.rs

+3-7
Original file line numberDiff line numberDiff line change
@@ -300,8 +300,8 @@ impl Position {
300300
conn: &mut PgConnection,
301301
trader_pubkey: String,
302302
temporary_contract_id: ContractId,
303-
) -> Result<()> {
304-
let affected_rows = diesel::update(positions::table)
303+
) -> QueryResult<usize> {
304+
diesel::update(positions::table)
305305
.filter(positions::trader_pubkey.eq(trader_pubkey))
306306
.filter(
307307
positions::position_state
@@ -313,11 +313,7 @@ impl Position {
313313
positions::temporary_contract_id.eq(hex::encode(temporary_contract_id)),
314314
positions::update_timestamp.eq(OffsetDateTime::now_utc()),
315315
))
316-
.execute(conn)?;
317-
318-
ensure!(affected_rows > 0, "Could not set position to open");
319-
320-
Ok(())
316+
.execute(conn)
321317
}
322318

323319
pub fn update_unrealized_pnl(conn: &mut PgConnection, id: i32, pnl: i64) -> Result<()> {

coordinator/src/db/trade_params.rs

+3-9
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ use diesel::QueryDsl;
99
use diesel::QueryResult;
1010
use diesel::Queryable;
1111
use diesel::RunQueryDsl;
12-
use rust_decimal::prelude::ToPrimitive;
1312
use std::str::FromStr;
1413
use uuid::Uuid;
1514

@@ -29,21 +28,16 @@ pub(crate) struct TradeParams {
2928
pub(crate) fn insert(
3029
conn: &mut PgConnection,
3130
protocol_id: ProtocolId,
32-
params: &commons::TradeParams,
31+
params: &dlc_protocol::TradeParams,
3332
) -> QueryResult<()> {
34-
let average_price = params
35-
.average_execution_price()
36-
.to_f32()
37-
.expect("to fit into f32");
38-
3933
let affected_rows = diesel::insert_into(trade_params::table)
4034
.values(&(
4135
trade_params::protocol_id.eq(protocol_id.to_uuid()),
4236
trade_params::quantity.eq(params.quantity),
4337
trade_params::leverage.eq(params.leverage),
44-
trade_params::trader_pubkey.eq(params.pubkey.to_string()),
38+
trade_params::trader_pubkey.eq(params.trader.to_string()),
4539
trade_params::direction.eq(Direction::from(params.direction)),
46-
trade_params::average_price.eq(average_price),
40+
trade_params::average_price.eq(params.average_price),
4741
))
4842
.execute(conn)?;
4943

0 commit comments

Comments
 (0)