2020-12-02 20:41:24 +01:00
|
|
|
import { createScaffoldMiddleware, mergeMiddleware } from 'json-rpc-engine'
|
2020-01-09 04:34:58 +01:00
|
|
|
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
|
|
|
|
|
|
|
import { NETWORK_TYPE_TO_ID_MAP } from './enums'
|
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',
|
|
|
|
})
|
2018-10-08 17:55:07 +02:00
|
|
|
const infuraProvider = providerFromMiddleware(infuraMiddleware)
|
2019-05-03 19:32:05 +02:00
|
|
|
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,
|
|
|
|
])
|
|
|
|
return { networkMiddleware, blockTracker }
|
|
|
|
}
|
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]) {
|
|
|
|
throw new Error(`createInfuraClient - unknown network "${network}"`)
|
2018-11-05 20:13:37 +01:00
|
|
|
}
|
|
|
|
|
2020-12-07 20:39:39 +01:00
|
|
|
const { chainId, networkId } = NETWORK_TYPE_TO_ID_MAP[network]
|
|
|
|
|
2018-11-05 20:13:37 +01:00
|
|
|
return createScaffoldMiddleware({
|
|
|
|
eth_chainId: chainId,
|
2020-12-07 20:39:39 +01:00
|
|
|
net_version: networkId,
|
2018-11-05 20:13:37 +01:00
|
|
|
})
|
|
|
|
}
|