-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathuseCoinGeckoWebSocket.ts
More file actions
148 lines (122 loc) · 3.72 KB
/
Copy pathuseCoinGeckoWebSocket.ts
File metadata and controls
148 lines (122 loc) · 3.72 KB
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
import { useEffect, useRef, useState } from 'react';
const WS_BASE = `${process.env.NEXT_PUBLIC_COINGECKO_WEBSOCKET_URL}?x_cg_pro_api_key=${process.env.NEXT_PUBLIC_COINGECKO_API_KEY}`;
export function useCoinGeckoWebSocket({
coinId,
poolId,
liveInterval
}: UseCoinGeckoWebSocketProps): UseCoinGeckoWebSocketReturn {
const wsRef = useRef<WebSocket | null>(null);
const subscribed = useRef<Set<string>>(new Set());
const [price, setPrice] = useState<ExtendedPriceData | null>(null);
const [trades, setTrades] = useState<Trade[]>([]);
const [ohlcv, setOhlcv] = useState<OHLCData | null>(null);
const [isWsReady, setIsWsReady] = useState(false);
// WebSocket connection
useEffect(() => {
const ws = new WebSocket(WS_BASE);
wsRef.current = ws;
const send = (payload: Record<string, unknown>) =>
ws.send(JSON.stringify(payload));
const handleMessage = (event: MessageEvent) => {
const msg: WebSocketMessage = JSON.parse(event.data);
if (msg.type === 'ping') {
send({ type: 'pong' });
return;
}
if (msg.type === 'confirm_subscription') {
const { channel } = JSON.parse(msg?.identifier ?? '');
subscribed.current.add(channel);
return;
}
if (msg.c === 'C1') {
setPrice({
usd: msg.p ?? 0,
coin: msg.i,
price: msg.p,
change24h: msg.pp,
marketCap: msg.m,
volume24h: msg.v,
timestamp: msg.t,
});
}
if (msg.c === 'G2') {
const newTrade: Trade = {
price: msg.pu,
value: msg.vo,
timestamp: msg.t ?? 0,
type: msg.ty,
amount: msg.to,
};
setTrades((prev) => [newTrade, ...prev].slice(0, 7));
}
if (msg.ch === 'G3') {
const timestamp = msg.t || 0;
const newCandle: OHLCData = [
timestamp,
Number(msg.o ?? 0),
Number(msg.h ?? 0),
Number(msg.l ?? 0),
Number(msg.c ?? 0),
];
setOhlcv(newCandle);
}
};
ws.onopen = () => setIsWsReady(true);
ws.onmessage = handleMessage;
ws.onclose = () => setIsWsReady(false);
return () => ws.close();
}, []);
// Subscribe on connection ready
useEffect(() => {
if (!isWsReady) return;
const ws = wsRef.current;
if (!ws) return;
const send = (payload: Record<string, unknown>) =>
ws.send(JSON.stringify(payload));
const unsubscribeAll = () => {
subscribed.current.forEach((channel) => {
send({
command: 'unsubscribe',
identifier: JSON.stringify({ channel }),
});
});
subscribed.current.clear();
};
const subscribe = (channel: string, data?: Record<string, unknown>) => {
if (subscribed.current.has(channel)) return;
send({ command: 'subscribe', identifier: JSON.stringify({ channel }) });
if (data) {
send({
command: 'message',
identifier: JSON.stringify({ channel }),
data: JSON.stringify(data),
});
}
};
queueMicrotask(() => {
setPrice(null);
setTrades([]);
setOhlcv(null);
});
unsubscribeAll();
subscribe('CGSimplePrice', { coin_id: [coinId], action: 'set_tokens' });
const poolAddress = poolId.replace('_', ':');
if (poolAddress) {
subscribe('OnchainTrade', {
'network_id:pool_addresses': [poolAddress],
action: 'set_pools',
});
subscribe('OnchainOHLCV', {
'network_id:pool_addresses': [poolAddress],
interval: liveInterval,
action: 'set_pools',
});
}
}, [coinId, poolId, isWsReady, liveInterval]);
return {
price,
trades,
ohlcv,
isConnected: isWsReady,
};
}