-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathjsonrpc.ts
50 lines (43 loc) · 1.28 KB
/
jsonrpc.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
import {JellyfishClient, JellyfishError, Payload} from '@defichain/jellyfish-core'
import fetch from 'cross-fetch'
import JSONBig from 'json-bigint'
/**
* A JSON-RPC client implementation for connecting to a DeFiChain node.
*/
export class JellyfishJsonRpc extends JellyfishClient {
private readonly url: string
/**
* Construct a Jellyfish client to connect to a DeFiChain node via JSON-RPC.
*
* @param url
*/
constructor(url: string) {
super()
this.url = url
}
async call<T>(method: string, payload: Payload): Promise<T> {
const body = JellyfishJsonRpc.stringify(method, payload)
const response = await fetch(this.url, {
method: 'POST',
body: body,
})
return await JellyfishJsonRpc.parse<T>(response)
}
static async parse<T>(response: Response): Promise<T> {
if (response.status !== 200) {
throw new JellyfishError(response.statusText, response.status)
}
// TODO(fuxingloh): validation?
const text = await response.text()
const data = JSONBig.parse(text)
return data.result
}
static stringify(method: string, payload: Payload): string {
return JSONBig.stringify({
jsonrpc: '1.0',
id: Math.floor(Math.random() * 10000000000000000),
method: method,
params: payload,
})
}
}