2021-02-04 19:15:23 +01:00
|
|
|
import { createScaffoldMiddleware, mergeMiddleware } from 'json-rpc-engine';
|
2021-11-11 21:26:49 +01:00
|
|
|
import {
|
|
|
|
createBlockRefMiddleware,
|
|
|
|
createRetryOnEmptyMiddleware,
|
|
|
|
createBlockCacheMiddleware,
|
|
|
|
createInflightCacheMiddleware,
|
|
|
|
createBlockTrackerInspectorMiddleware,
|
|
|
|
providerFromMiddleware,
|
2023-02-27 17:49:08 +01:00
|
|
|
} from '@metamask/eth-json-rpc-middleware';
|
2021-11-11 21:26:49 +01:00
|
|
|
|
2022-09-15 19:11:18 +02:00
|
|
|
import { createInfuraMiddleware } from '@metamask/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
|
|
|
|
2022-09-14 16:55:31 +02:00
|
|
|
import { BUILT_IN_NETWORKS } 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);
|
2021-03-26 18:03:44 +01:00
|
|
|
const blockTracker = new PollingBlockTracker({ 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 }),
|
2021-07-06 19:53:35 +02:00
|
|
|
createInflightCacheMiddleware(),
|
|
|
|
createBlockRefMiddleware({ blockTracker, provider: infuraProvider }),
|
2018-10-08 17:55:07 +02:00
|
|
|
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 }) {
|
2022-09-14 16:55:31 +02:00
|
|
|
if (!BUILT_IN_NETWORKS[network]) {
|
2021-02-04 19:15:23 +01:00
|
|
|
throw new Error(`createInfuraClient - unknown network "${network}"`);
|
2018-11-05 20:13:37 +01:00
|
|
|
}
|
|
|
|
|
2022-09-14 16:55:31 +02:00
|
|
|
const { chainId, networkId } = BUILT_IN_NETWORKS[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
|
|
|
}
|