-
Notifications
You must be signed in to change notification settings - Fork 13
/
fetchRPC.ts
37 lines (28 loc) · 1.18 KB
/
fetchRPC.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
import invariant from 'tiny-invariant';
import { CHAINS } from '@lido-sdk/constants';
import { fetchWithFallbacks } from './fetchWithFallbacks';
import { getRPCUrls, RPCProvidersKeys } from './providersUrls';
import { RequestInit, Response } from './fetch';
export type FetRPCUrl = (chainId: CHAINS) => string;
export interface FetchRPCOptions extends RequestInit {
providers?: RPCProvidersKeys;
urls?: (string | FetRPCUrl)[];
}
export type FetchRPC = (
chainId: CHAINS,
options: FetchRPCOptions,
) => Promise<Response>;
export type CreateRPCFetcher = (options: FetchRPCOptions) => FetchRPC;
export const fetchRPC: FetchRPC = (chainId, options) => {
const { providers = {}, urls = [], ...init } = options;
const customUrls = urls.map((value) => {
let url = value;
if (typeof value === 'function') url = value(chainId);
invariant(typeof url === 'string', 'URL should be a string');
return url;
});
const providersUrls = getRPCUrls(chainId, providers);
const combinedUrls = [...customUrls, ...providersUrls];
invariant(combinedUrls.length > 0, 'There are no API keys or URLs provided');
return fetchWithFallbacks(combinedUrls, { method: 'POST', ...init });
};