/
OrderPacket.ts
69 lines (59 loc) 路 1.88 KB
/
OrderPacket.ts
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
import Packet, { PacketDirection, ResponseType } from '../Packet';
import PacketType from '../PacketType';
import { OutgoingOrder } from '../../../orderbook/types';
import * as pb from '../../../proto/xudp2p_pb';
class OrderPacket extends Packet<OutgoingOrder> {
public get type(): PacketType {
return PacketType.Order;
}
public get direction(): PacketDirection {
return PacketDirection.Unilateral;
}
public get responseType(): ResponseType {
return undefined;
}
public static deserialize = (binary: Uint8Array): OrderPacket | pb.OrderPacket.AsObject => {
const obj = pb.OrderPacket.deserializeBinary(binary).toObject();
return OrderPacket.validate(obj) ? OrderPacket.convert(obj) : obj;
}
private static validate = (obj: pb.OrderPacket.AsObject): boolean => {
return !!(obj.id
&& obj.order
&& obj.order.id
&& obj.order.pairId
&& obj.order.price > 0
&& obj.order.quantity > 0
);
}
private static convert = (obj: pb.OrderPacket.AsObject): OrderPacket => {
return new OrderPacket({
header: {
id: obj.id,
},
body: {
id: obj.order!.id,
pairId: obj.order!.pairId,
price: obj.order!.price,
quantity: obj.order!.quantity,
isBuy: obj.order!.isBuy,
replaceOrderId: obj.order!.replaceOrderId || undefined,
},
});
}
public serialize = (): Uint8Array => {
const pbOrder = new pb.Order();
pbOrder.setId(this.body!.id);
pbOrder.setPairId(this.body!.pairId);
pbOrder.setPrice(this.body!.price);
pbOrder.setQuantity(this.body!.quantity);
pbOrder.setIsBuy(this.body!.isBuy);
if (this.body?.replaceOrderId) {
pbOrder.setReplaceOrderId(this.body.replaceOrderId);
}
const msg = new pb.OrderPacket();
msg.setId(this.header.id);
msg.setOrder(pbOrder);
return msg.serializeBinary();
}
}
export default OrderPacket;