/
Helpers.ts
85 lines (80 loc) · 2.72 KB
/
Helpers.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
import { TerraPayload } from './WebhookEvents';
import fetch from 'cross-fetch';
import { createHmac } from 'crypto';
function ZeroPad(value: number, minSize: number) {
return '0'.repeat(Math.max(minSize - value.toString().length, 0)) + value.toString();
}
export function DateToTerraDate(d: Date): string {
const month = d.getUTCMonth() + 1; // months from 1-12
const day = d.getUTCDate();
const year = d.getUTCFullYear();
return year + '-' + ZeroPad(month, 2) + '-' + ZeroPad(day, 2);
}
export function RequestWrapper<T>(
endpoint: string,
requestOptions: RequestInit,
requestParams: { [id: string]: any } = {},
): Promise<T> {
checkForServerSideAndWarn();
return new Promise<T>((res, rej) => {
const params = new URLSearchParams();
Object.entries(requestParams).forEach(([k, v]) => params.append(k, v));
const url = 'https://api.tryterra.co/v2/' + endpoint + (params ? '?' + params.toString() : '');
fetch(url, requestOptions)
.then((response) => {
if (response.status === 500 || response.status === 502) {
rej({
status: 'error',
type: 'internal_server_error',
message: response.status.toString(),
} as TerraPayload);
return;
}
// rate limiting from providers end
else if (response.status === 429) {
rej({
status: 'error',
type: 'provider_rate_limit',
message: response.status.toString(),
} as TerraPayload);
return;
}
response
.json()
.then((result) => (response.ok ? res(result as T) : rej(result as TerraPayload)))
.catch((error) =>
rej({
status: 'error',
type: 'unknown',
message: error,
} as TerraPayload),
);
})
.catch((error) =>
rej({
status: 'error',
type: 'unknown',
message: error,
} as TerraPayload),
);
});
}
export function checkForServerSideAndWarn() {
if (typeof process !== 'undefined' && process.release.name.search(/node|io.js/) !== -1) {
// This is good, we are running in node
} else {
// tslint:disable-next-line:no-console
console.warn(
'This script is not running in Node.js which means this is probably running on the client side which means you are exposing your API Key which is very dangerous',
);
}
}
export function CheckTerraSignature(terraSignature: string, payload: string, secret: string): boolean {
const s = terraSignature.split(',');
const t = s[0].split('=')[1];
const v1 = s[1].split('=')[1];
const hmac = createHmac('sha256', secret)
.update(t + '.' + payload)
.digest('hex');
return hmac === v1;
}