Example #1
0
function createInfuraMiddleware(opts = {}) {
  const network = opts.network || 'mainnet'
  const maxAttempts = opts.maxAttempts || 5
  // validate options
  if (!maxAttempts) throw new Error(`Invalid value for 'maxAttempts': "${maxAttempts}" (${typeof maxAttempts})`)

  return createAsyncMiddleware(async (req, res, next) => {
    // retry MAX_ATTEMPTS times, if error matches filter
    for (let attempt = 1; attempt <= maxAttempts; attempt++) {
      try {
        // attempt request
        await performFetch(network, req, res)
        // request was succesful
        break
      } catch (err) {
        // an error was caught while performing the request
        // if not retriable, resolve with the encountered error
        if (!isRetriableError(err)) {
          // abort with error
          throw err
        }
        // if no more attempts remaining, throw an error
        const remainingAttempts = maxAttempts - attempt
        if (!remainingAttempts) {
          const errMsg = `InfuraProvider - cannot complete request. All retries exhausted.\nOriginal Error:\n${err.toString()}\n\n`
          const retriesExhaustedErr = new Error(errMsg)
          throw retriesExhaustedErr
        }
        // otherwise, ignore error and retry again after timeout
        await timeout(1000)
      }
    }
    // request was handled correctly, end
  })
}
Example #2
0
function createInfuraMiddleware({
  network = 'mainnet'
}) {
  return createAsyncMiddleware(async (req, res) => {
    const {
      fetchUrl,
      fetchParams
    } = fetchConfigFromReq({
      network,
      req
    })

    const response = await fetch(fetchUrl, fetchParams)
    const rawData = await response.text()

    // handle errors
    if (!response.ok) {
      switch (response.status) {
        case 405: {
          throw new JsonRpcError.MethodNotFound()
        }
        case 418: {
          const msg = 'Request is being rate limited.'
          const error = new Error(msg)
          throw new JsonRpcError.InternalError(error)
        }
        case 503:
        case 504: {
          const msg = 'Gateway timeout. The request took too long to process.'
          const error = new Error(msg)
          throw new JsonRpcError.InternalError(error)
        }
        default: {
          const error = new Error(rawData)
          throw new JsonRpcError.InternalError(error)
        }
      }
    }

    // special case for now
    if (req.method === 'eth_getBlockByNumber' && rawData === 'Not Found') {
      res.result = null
      return
    }

    const data = JSON.parse(rawData)
    res.result = data.result
    res.error = data.error
  })
}