-
Notifications
You must be signed in to change notification settings - Fork 782
/
Copy pathprovider.ts
83 lines (79 loc) · 2.2 KB
/
provider.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
type rpcParams = {
method: string
params: (string | string[] | boolean | number)[]
}
/**
* Makes a simple RPC call to a remote Ethereum JSON-RPC provider and passes through the response.
* No parameter or response validation is done.
*
* @param url the URL for the JSON RPC provider
* @param params the parameters for the JSON-RPC method - refer to
* https://ethereum.org/en/developers/docs/apis/json-rpc/ for details on RPC methods
* @returns the `result` field from the JSON-RPC response
* @example
* ```ts
* const provider = 'https://mainnet.infura.io/v3/...'
* const params = {
* method: 'eth_getBlockByNumber',
* params: ['latest', false],
* }
* const block = await fetchFromProvider(provider, params)
* ```
*/
export const fetchFromProvider = async (url: string, params: rpcParams) => {
const data = JSON.stringify({
method: params.method,
params: params.params,
jsonrpc: '2.0',
id: 1,
})
const res = await fetch(url, {
headers: {
'content-type': 'application/json',
},
method: 'POST',
body: data,
})
if (!res.ok) {
throw new Error(
`JSONRPCError: ${JSON.stringify(
{
method: params.method,
status: res.status,
message: await res.text().catch(() => {
return 'Could not parse error message likely because of a network error'
}),
},
null,
2,
)}`,
)
}
const json = await res.json()
// TODO we should check json.error here
return json.result
}
/**
*
* @param provider a URL string or {@link EthersProvider}
* @returns the extracted URL string for the JSON-RPC Provider
*/
export const getProvider = (provider: string | EthersProvider) => {
if (typeof provider === 'string') {
return provider
} else if (typeof provider === 'object' && provider._getConnection !== undefined) {
return provider._getConnection().url
} else {
throw new Error('Must provide valid provider URL or Web3Provider')
}
}
/**
* A partial interface for an `ethers` `JSONRPCProvider`
* We only use the url string since we do raw `fetch` calls to
* retrieve the necessary data
*/
export interface EthersProvider {
_getConnection: () => {
url: string
}
}