-
Notifications
You must be signed in to change notification settings - Fork 18
/
bun.ts
83 lines (63 loc) · 2.05 KB
/
bun.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
// See https://bun.sh/docs for more information
import crypto from "crypto";
import { Buffer } from "buffer";
const hostname = "https://whitebit.com";
const publicKey = "";
const secretKey = "";
/**
* @see https://whitebit-exchange.github.io/api-docs/private/http-auth/#body-data
*/
function getRequestBody<T extends Object>(url: string, extendedBodyData?: T) {
return Object.assign(
{
request: url,
nonce: Date.now(),
nonceWindow: true,
},
extendedBodyData
);
}
/**
* @see https://whitebit-exchange.github.io/api-docs/private/http-auth/#headers
*/
function getRequestParameters(params: ReturnType<typeof getRequestBody>) {
const body = JSON.stringify(params);
const payload = Buffer.from(body).toString("base64");
const hash = crypto.createHmac("sha512", secretKey);
const signature = hash.update(payload).digest("hex");
const headers = {
"Content-Type": "application/json",
"X-TXC-APIKEY": publicKey,
"X-TXC-PAYLOAD": payload,
"X-TXC-SIGNATURE": signature,
};
return { headers, body };
}
type SingleTradeBalance = { available: string; freeze: string };
type TradeBalances = Record<string, SingleTradeBalance>;
function getTradeBalance(ticker: string): Promise<SingleTradeBalance | null>;
function getTradeBalance(): Promise<TradeBalances | null>;
/**
* @see https://whitebit-exchange.github.io/api-docs/private/http-trade-v4/#trading-balance
*/
async function getTradeBalance(ticker?) {
const requestUrl = "/api/v4/trade-account/balance";
const parameters = ticker ? { ticker } : undefined;
const data = getRequestBody(requestUrl, parameters);
const { body, headers } = getRequestParameters(data);
try {
const response = await fetch(new URL(requestUrl, hostname), {
method: "POST",
body,
headers,
});
console.log("Status code:", response.status);
const data = await response.json().catch(() => null);
return data;
} catch (error) {
console.log(error.message);
return null;
}
}
const balance = await getTradeBalance("BTC");
console.log(balance);