-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
websocket-util.ts
293 lines (264 loc) · 8.75 KB
/
websocket-util.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
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
import WebSocket from 'isomorphic-ws';
import {
WsExchangeRequestOperation,
WsInternationalRequestOperation,
} from '../../types/websockets/requests.js';
import { signMessage } from '../webCryptoAPI.js';
/**
* Each websocket URL (domain + endpoint) is represented as a "WS Key". Authentication is handled automatically if required.
*/
export const WS_KEY_MAP = {
/**
* Market Data is the traditional feed that provides updates for both orders and trades.
* Most channels are now available without authentication.
*
* https://docs.cdp.coinbase.com/advanced-trade/docs/ws-overview
*/
advTradeMarketData: 'advTradeMarketData',
/**
* User Order Data provides updates for the orders of the user.
*
* https://docs.cdp.coinbase.com/advanced-trade/docs/ws-overview
*/
advTradeUserData: 'advTradeUserData',
/**
* Coinbase Market Data (part of Coinbase Exchange API) is the traditional feed which is available without authentication.
*
* https://docs.cdp.coinbase.com/exchange/docs/websocket-overview
*/
exchangeMarketData: 'exchangeMarketData',
/**
* Coinbase Direct Market Data has direct access to Coinbase Exchange servers and requires Authentication.
*
* https://docs.cdp.coinbase.com/exchange/docs/websocket-overview
*/
exchangeDirectMarketData: 'exchangeDirectMarketData',
/**
* The INTX WebSocket feed is publicly available and provides real-time market data updates for orders and trades.
* The SDK must authenticate when subscribing to the WebSocket Feed the very first time.
*
* https://docs.cdp.coinbase.com/intx/docs/websocket-overview
*/
internationalMarketData: 'internationalMarketData',
/**
* The Prime WebSocket feed provides real-time market data updates for orders and trades. To begin
* receiving feed messages, you must send a signed subscribe message to the server indicating
* which channels and products to receive. The SDK will handle this automatically.
*
* https://docs.cdp.coinbase.com/prime/docs/websocket-feed
*/
primeMarketData: 'primeMarketData',
} as const;
/** This is used to differentiate between each of the available websocket streams */
export type WsKey = (typeof WS_KEY_MAP)[keyof typeof WS_KEY_MAP];
/**
* Normalised internal format for a request (subscribe/unsubscribe/etc) on a topic, with optional parameters.
*
* - Topic: the topic this event is for
* - Payload: the parameters to include, optional. E.g. auth requires key + sign. Some topics allow configurable parameters.
*/
export interface WsTopicRequest<
TWSTopic extends string = string,
TWSPayload = any,
> {
topic: TWSTopic;
/**
* Any parameters to include with the request. These are automatically merged into the request.
*/
payload?: TWSPayload;
}
/**
* Conveniently allow users to request a topic either as string topics or objects (containing string topic + params)
*/
export type WsTopicRequestOrStringTopic<
TWSTopic extends string,
TWSPayload = any,
> = WsTopicRequest<TWSTopic, TWSPayload> | string;
export interface MessageEventLike {
target: WebSocket;
type: 'message';
data: string;
}
export function isMessageEvent(msg: unknown): msg is MessageEventLike {
if (typeof msg !== 'object' || !msg) {
return false;
}
const message = msg as MessageEventLike;
return message['type'] === 'message' && typeof message['data'] === 'string';
}
/**
* Some exchanges have two livenet environments, some have test environments, some dont. This allows easy flexibility for different exchanges.
* Examples:
* - One livenet and one testnet: NetworkMap<'livenet' | 'testnet'>
* - One livenet, sometimes two, one testnet: NetworkMap<'livenet' | 'testnet', 'livenet2'>
* - Only one livenet, no other networks: NetworkMap<'livenet'>
*/
type NetworkMap<
TRequiredKeys extends string,
TOptionalKeys extends string | undefined = undefined,
> = Record<TRequiredKeys, string> &
(TOptionalKeys extends string
? Record<TOptionalKeys, string | undefined>
: Record<TRequiredKeys, string>);
export const WS_URL_MAP: Record<WsKey, NetworkMap<'livenet' | 'testnet'>> = {
[WS_KEY_MAP.advTradeMarketData]: {
livenet: 'wss://advanced-trade-ws.coinbase.com',
testnet: 'NotAvailable',
},
[WS_KEY_MAP.advTradeUserData]: {
livenet: 'wss://advanced-trade-ws-user.coinbase.com',
testnet: 'NotAvailable',
},
[WS_KEY_MAP.exchangeMarketData]: {
livenet: 'wss://ws-feed.exchange.coinbase.com',
testnet: 'wss://ws-feed-public.sandbox.exchange.coinbase.com',
},
[WS_KEY_MAP.exchangeDirectMarketData]: {
livenet: 'wss://ws-direct.exchange.coinbase.com',
testnet: 'wss://ws-direct.sandbox.exchange.coinbase.com',
},
[WS_KEY_MAP.internationalMarketData]: {
livenet: 'wss://ws-md.international.coinbase.com',
testnet: 'wss://ws-md.n5e2.coinbase.com',
},
[WS_KEY_MAP.primeMarketData]: {
livenet: 'wss://ws-feed.prime.coinbase.com',
testnet: 'NotAvailable',
},
} as const;
/**
* Merge one or more WS Request operations (e.g. subscribe request) for
* CB Exchange into one, allowing them to be sent as one request
*/
export function getMergedCBExchangeWSRequestOperations<
TWSTopic extends string = string,
>(operations: WsExchangeRequestOperation<TWSTopic>[]) {
// The CB Exchange WS supports sending multiple topics in one request.
// Merge all requests into one
return operations.reduce(
(
acc: WsExchangeRequestOperation<TWSTopic>,
evt: WsExchangeRequestOperation<TWSTopic>,
) => {
if (!acc) {
const wsRequestEvent: WsExchangeRequestOperation<TWSTopic> = {
type: evt.type,
channels: [...evt.channels],
};
return wsRequestEvent;
}
const wsRequestEvent: WsExchangeRequestOperation<TWSTopic> = {
type: evt.type,
channels: [...acc.channels, ...evt.channels],
};
return wsRequestEvent;
},
);
}
/**
* Merge one or more WS Request operations (e.g. subscribe request) for
* CB Exchange into one, allowing them to be sent as one request
*/
export function getMergedCBINTXRequestOperations<
TWSTopic extends string = string,
>(operations: WsInternationalRequestOperation<TWSTopic>[]) {
// The CB Exchange WS supports sending multiple topics in one request.
// Merge all requests into one
return operations.reduce(
(
acc: WsInternationalRequestOperation<TWSTopic>,
evt: WsInternationalRequestOperation<TWSTopic>,
) => {
if (!acc) {
const wsRequestEvent: WsInternationalRequestOperation<TWSTopic> = {
type: evt.type,
channels: [...evt.channels],
};
return wsRequestEvent;
}
const wsRequestEvent: WsInternationalRequestOperation<TWSTopic> = {
type: evt.type,
channels: [...acc.channels, ...evt.channels],
};
return wsRequestEvent;
},
);
}
/**
* Return sign used to authenticate CB Exchange WS requests
*/
export async function getCBExchangeWSSign(apiSecret: string): Promise<{
timestampInSeconds: string;
sign: string;
}> {
const timestampInMs = Date.now();
const timestampInSeconds = (timestampInMs / 1000).toFixed(0);
const signPath = '/users/self/verify';
const signRequestMethod = 'GET';
const signInput = `${timestampInSeconds}${signRequestMethod}${signPath}`;
const sign = await signMessage(
signInput,
apiSecret,
'base64',
'SHA-256',
'base64:web',
);
return { sign, timestampInSeconds };
}
/**
* Return sign used to authenticate CB INTX WS requests
*/
export async function getCBInternationalWSSign(
apiKey: string,
apiSecret: string,
apiPassphrase: string,
): Promise<{
timestampInSeconds: string;
sign: string;
}> {
const timestampInMs = Date.now();
const timestampInSeconds = (timestampInMs / 1000).toFixed(0);
const signInput = timestampInSeconds + apiKey + 'CBINTLMD' + apiPassphrase;
const sign = await signMessage(
signInput,
apiSecret,
'base64',
'SHA-256',
'base64:web',
);
return { sign, timestampInSeconds };
}
/**
* Return sign used to authenticate CB Prime WS requests
*/
export async function getCBPrimeWSSign(params: {
channelName: string;
svcAccountId: string;
portfolioId: string;
apiKey: string;
apiSecret: string;
product_ids?: string[];
}): Promise<{
timestampInSeconds: string;
sign: string;
}> {
const timestampInMs = Date.now();
const timestampInSeconds = (timestampInMs / 1000).toFixed(0);
// channelName + accessKey + svcAccountId + timestamp + portfolioId + products
const signInput = [
params.channelName,
params.apiKey,
params.svcAccountId,
timestampInSeconds,
params.portfolioId,
params.product_ids ? params.product_ids.join('') : '',
].join('');
const sign = await signMessage(
signInput,
params.apiSecret,
'base64',
'SHA-256',
'base64:web',
);
return { sign, timestampInSeconds };
}