1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-11-23 18:41:38 +01:00
metamask-extension/app/scripts/controllers/network/createInfuraClient.js

50 lines
1.6 KiB
JavaScript
Raw Normal View History

import { createScaffoldMiddleware, mergeMiddleware } from 'json-rpc-engine';
import {
createBlockRefMiddleware,
createRetryOnEmptyMiddleware,
createBlockCacheMiddleware,
createInflightCacheMiddleware,
createBlockTrackerInspectorMiddleware,
providerFromMiddleware,
} from 'eth-json-rpc-middleware';
import createInfuraMiddleware from 'eth-json-rpc-infura';
2021-03-26 18:03:44 +01:00
import { PollingBlockTracker } from 'eth-block-tracker';
2020-12-07 20:39:39 +01:00
import { NETWORK_TYPE_TO_ID_MAP } from '../../../../shared/constants/network';
2020-11-03 00:41:28 +01:00
export default function createInfuraClient({ network, projectId }) {
const infuraMiddleware = createInfuraMiddleware({
network,
projectId,
maxAttempts: 5,
source: 'metamask',
});
const infuraProvider = providerFromMiddleware(infuraMiddleware);
2021-03-26 18:03:44 +01:00
const blockTracker = new PollingBlockTracker({ provider: infuraProvider });
const networkMiddleware = mergeMiddleware([
createNetworkAndChainIdMiddleware({ network }),
createBlockCacheMiddleware({ blockTracker }),
createInflightCacheMiddleware(),
createBlockRefMiddleware({ blockTracker, provider: infuraProvider }),
createRetryOnEmptyMiddleware({ blockTracker, provider: infuraProvider }),
createBlockTrackerInspectorMiddleware({ blockTracker }),
infuraMiddleware,
]);
return { networkMiddleware, blockTracker };
}
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]) {
throw new Error(`createInfuraClient - unknown network "${network}"`);
}
const { chainId, networkId } = NETWORK_TYPE_TO_ID_MAP[network];
2020-12-07 20:39:39 +01:00
return createScaffoldMiddleware({
eth_chainId: chainId,
2020-12-07 20:39:39 +01:00
net_version: networkId,
});
}