2021-02-04 19:15:23 +01:00
|
|
|
import { createScaffoldMiddleware, mergeMiddleware } from 'json-rpc-engine';
|
|
|
|
import createBlockReRefMiddleware from 'eth-json-rpc-middleware/block-ref';
|
|
|
|
import createRetryOnEmptyMiddleware from 'eth-json-rpc-middleware/retryOnEmpty';
|
|
|
|
import createBlockCacheMiddleware from 'eth-json-rpc-middleware/block-cache';
|
|
|
|
import createInflightMiddleware from 'eth-json-rpc-middleware/inflight-cache';
|
|
|
|
import createBlockTrackerInspectorMiddleware from 'eth-json-rpc-middleware/block-tracker-inspector';
|
|
|
|
import providerFromMiddleware from 'eth-json-rpc-middleware/providerFromMiddleware';
|
|
|
|
import createInfuraMiddleware from 'eth-json-rpc-infura';
|
|
|
|
import BlockTracker from 'eth-block-tracker';
|
2020-12-07 20:39:39 +01:00
|
|
|
|
2021-02-04 19:15:23 +01:00
|
|
|
import { NETWORK_TYPE_TO_ID_MAP } from '../../../../shared/constants/network';
|
2018-05-17 05:46:34 +02:00
|
|
|
|
2020-11-03 00:41:28 +01:00
|
|
|
export default function createInfuraClient({ network, projectId }) {
|
2020-09-10 18:16:00 +02:00
|
|
|
const infuraMiddleware = createInfuraMiddleware({
|
|
|
|
network,
|
|
|
|
projectId,
|
|
|
|
maxAttempts: 5,
|
|
|
|
source: 'metamask',
|
2021-02-04 19:15:23 +01:00
|
|
|
});
|
|
|
|
const infuraProvider = providerFromMiddleware(infuraMiddleware);
|
|
|
|
const blockTracker = new BlockTracker({ provider: infuraProvider });
|
2018-05-17 05:46:34 +02:00
|
|
|
|
|
|
|
const networkMiddleware = mergeMiddleware([
|
2018-11-05 20:13:37 +01:00
|
|
|
createNetworkAndChainIdMiddleware({ network }),
|
2018-05-17 05:46:34 +02:00
|
|
|
createBlockCacheMiddleware({ blockTracker }),
|
|
|
|
createInflightMiddleware(),
|
2018-10-08 17:55:07 +02:00
|
|
|
createBlockReRefMiddleware({ blockTracker, provider: infuraProvider }),
|
|
|
|
createRetryOnEmptyMiddleware({ blockTracker, provider: infuraProvider }),
|
2018-05-17 05:46:34 +02:00
|
|
|
createBlockTrackerInspectorMiddleware({ blockTracker }),
|
|
|
|
infuraMiddleware,
|
2021-02-04 19:15:23 +01:00
|
|
|
]);
|
|
|
|
return { networkMiddleware, blockTracker };
|
2018-05-17 05:46:34 +02:00
|
|
|
}
|
2018-11-05 20:13:37 +01:00
|
|
|
|
2020-11-03 00:41:28 +01:00
|
|
|
function createNetworkAndChainIdMiddleware({ network }) {
|
2020-12-07 20:39:39 +01:00
|
|
|
if (!NETWORK_TYPE_TO_ID_MAP[network]) {
|
2021-02-04 19:15:23 +01:00
|
|
|
throw new Error(`createInfuraClient - unknown network "${network}"`);
|
2018-11-05 20:13:37 +01:00
|
|
|
}
|
|
|
|
|
2021-02-04 19:15:23 +01:00
|
|
|
const { chainId, networkId } = NETWORK_TYPE_TO_ID_MAP[network];
|
2020-12-07 20:39:39 +01:00
|
|
|
|
2018-11-05 20:13:37 +01:00
|
|
|
return createScaffoldMiddleware({
|
|
|
|
eth_chainId: chainId,
|
2020-12-07 20:39:39 +01:00
|
|
|
net_version: networkId,
|
2021-02-04 19:15:23 +01:00
|
|
|
});
|
2018-11-05 20:13:37 +01:00
|
|
|
}
|