How to use the @requestnetwork/utils.retry function in @requestnetwork/utils

To help you get started, we’ve selected a few @requestnetwork/utils examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github RequestNetwork / requestNetwork / packages / request-client.js / src / api / payment-network / btc / default-providers / blockcypher-com.ts View on Github external
public async getAddressBalanceWithEvents(
    bitcoinNetworkId: number,
    address: string,
    eventName: Types.EVENTS_NAMES,
  ): Promise {
    const baseUrl = this.getBaseUrl(bitcoinNetworkId);
    const queryUrl = `${baseUrl}/addrs/${address}`;
    try {
      const res = await Utils.retry(async () => fetch(queryUrl), {
        maxRetries: BLOCKCYPHER_REQUEST_MAX_RETRY,
        retryDelay: BLOCKCYPHER_REQUEST_RETRY_DELAY,
      })();

      // tslint:disable-next-line:no-magic-numbers
      if (res.status >= 400) {
        throw new Error(`Error ${res.status}. Bad response from server ${queryUrl}`);
      }
      const addressInfo = await res.json();

      return this.parse(addressInfo, eventName);
    } catch (err) {
      // tslint:disable-next-line:no-console
      console.warn(err.message || err);
      return { balance: '-1', events: [] };
    }
github RequestNetwork / requestNetwork / packages / request-client.js / src / api / payment-network / btc / default-providers / blockstream-info.ts View on Github external
public async getAddressBalanceWithEvents(
    bitcoinNetworkId: number,
    address: string,
    eventName: Types.EVENTS_NAMES,
  ): Promise {
    const baseUrl = this.getBaseUrl(bitcoinNetworkId);
    const queryUrl = `${baseUrl}/address/${address}/txs`;
    try {
      const res = await Utils.retry(async () => fetch(queryUrl), {
        maxRetries: BLOCKSTREAMINFO_REQUEST_MAX_RETRY,
        retryDelay: BLOCKSTREAMINFO_REQUEST_RETRY_DELAY,
      })();

      // tslint:disable-next-line:no-magic-numbers
      if (res.status >= 400) {
        throw new Error(`Error ${res.status}. Bad response from server ${queryUrl}`);
      }
      let txs: any[] = await res.json();

      let checkForMoreTransactions = txs.length === TXS_PER_PAGE;
      // if there are 'TXS_PER_PAGE' transactions, need to check the pagination
      while (checkForMoreTransactions) {
        const lastTxHash = txs[txs.length - 1].txid;

        const resExtraPage = await Utils.retry(
github RequestNetwork / requestNetwork / packages / ethereum-storage / src / smart-contract-manager.ts View on Github external
private async recursiveGetPastEvents(
    fromBlock: number,
    toBlock: number | string,
  ): Promise {
    const toBlockNumber: number = await this.getBlockNumberFromNumberOrString(toBlock);

    // Reading event logs
    // If getPastEvents doesn't throw, we can return the returned events from the function
    let events;
    try {
      events = await Utils.retry(
        (args: any) =>
          Promise.race([
            Utils.timeoutPromise(this.timeout, 'Web3 getPastEvents connection timeout'),
            this.requestHashStorage.getPastEvents(args),
          ]),
        {
          maxRetries: this.maxRetries || config.getEthereumMaxRetries(),
          retryDelay: this.retryDelay || config.getEthereumRetryDelay(),
        },
      )({
        event: 'NewHash',
        fromBlock,
        toBlock: toBlockNumber,
      });

      this.logger.debug(`Events from ${fromBlock} to ${toBlock} fetched`, ['ethereum']);
github RequestNetwork / requestNetwork / packages / ethereum-storage / src / gas-price-providers / ethgasstation-provider.ts View on Github external
public async getGasPrice(type: StorageTypes.GasPriceType): Promise {
    const res = await Utils.retry(async () => this.fetch(this.providerUrl), {
      maxRetries: ETHGASSTATION_REQUEST_MAX_RETRY,
      retryDelay: ETHGASSTATION_RETRY_DELAY,
    })();

    // tslint:disable-next-line:no-magic-numbers
    if (res.status >= 400) {
      throw new Error(
        `EthGasStation error ${res.status}. Bad response from server ${this.providerUrl}`,
      );
    }
    const apiResponse = await res.json();

    // Check if the API response has the correct format
    if (
      !apiResponse.fast ||
      !apiResponse.average ||
github RequestNetwork / requestNetwork / packages / request-client.js / src / api / payment-network / btc / default-providers / blockchain-info.ts View on Github external
maxRetries: BLOCKCHAININFO_REQUEST_MAX_RETRY,
        retryDelay: BLOCKCHAININFO_REQUEST_RETRY_DELAY,
      })();

      // tslint:disable-next-line:no-magic-numbers
      if (res.status >= 400) {
        throw new Error(`Error ${res.status}. Bad response from server ${queryUrl}`);
      }
      const addressInfo = await res.json();

      // count the number of extra pages to retrieve
      const numberOfExtraPages = Math.floor(addressInfo.n_tx / (TXS_PER_PAGE + 1));

      // get all the transactions from the whole pagination
      for (let i = 1; i <= numberOfExtraPages; i++) {
        const resExtraPage = await Utils.retry(
          async () =>
            fetch(`${blockchainInfoUrl}/rawaddr/${address}?cors=true&offset=${i * TXS_PER_PAGE}`),
          {
            maxRetries: BLOCKCHAININFO_REQUEST_MAX_RETRY,
            retryDelay: BLOCKCHAININFO_REQUEST_RETRY_DELAY,
          },
        )();

        // tslint:disable-next-line:no-magic-numbers
        if (resExtraPage.status >= 400) {
          throw new Error(
            `Error ${resExtraPage.status}. Bad response from server ${blockchainInfoUrl}`,
          );
        }
        const extraPageAddressInfo = await resExtraPage.json();
github RequestNetwork / requestNetwork / packages / request-client.js / src / http-data-access.ts View on Github external
public async getChannelsByMultipleTopics(
    topics: string[],
    updatedBetween?: DataAccessTypes.ITimestampBoundaries,
  ): Promise {
    const { data } = await Utils.retry(
      async () =>
        axios.get(
          '/getChannelsByMultipleTopics',
          Object.assign(this.axiosConfig, {
            params: { topics, updatedBetween },
          }),
        ),
      {
        maxRetries: HTTP_REQUEST_MAX_RETRY,
        retryDelay: HTTP_REQUEST_RETRY_DELAY,
      },
    )();

    return data;
  }
}
github RequestNetwork / requestNetwork / packages / request-client.js / src / http-data-access.ts View on Github external
public async getTransactionsByChannelId(
    channelId: string,
    timestampBoundaries?: DataAccessTypes.ITimestampBoundaries,
  ): Promise {
    const { data } = await Utils.retry(
      async () =>
        axios.get(
          '/getTransactionsByChannelId',
          Object.assign(this.axiosConfig, {
            params: { channelId, timestampBoundaries },
          }),
        ),
      {
        maxRetries: HTTP_REQUEST_MAX_RETRY,
        retryDelay: HTTP_REQUEST_RETRY_DELAY,
      },
    )();

    return data;
  }
github RequestNetwork / requestNetwork / packages / ethereum-storage / src / ethereum-blocks.ts View on Github external
public async getBlock(blockNumber: number | string): Promise {
    return Utils.retry(this.eth.getBlock, {
      maxRetries: this.maxRetries,
      retryDelay: this.retryDelay,
    })(blockNumber);
  }
github RequestNetwork / requestNetwork / packages / request-client.js / src / http-data-access.ts View on Github external
public async getChannelsByTopic(
    topic: string,
    updatedBetween?: DataAccessTypes.ITimestampBoundaries,
  ): Promise {
    const { data } = await Utils.retry(
      async () =>
        axios.get(
          '/getChannelsByTopic',
          Object.assign(this.axiosConfig, {
            params: { topic, updatedBetween },
          }),
        ),
      {
        maxRetries: HTTP_REQUEST_MAX_RETRY,
        retryDelay: HTTP_REQUEST_RETRY_DELAY,
      },
    )();

    return data;
  }
github RequestNetwork / requestNetwork / packages / ethereum-storage / src / ethereum-blocks.ts View on Github external
() =>
        Utils.retry(
          () => {
            this.logger.debug(`Getting last block number`, ['ethereum', 'ethereum-blocks']);
            return this.eth.getBlockNumber();
          },
          {
            maxRetries: this.maxRetries,
            retryDelay: this.retryDelay,
          },
        )(),
      this.getLastBlockNumberMinDelay,