<commit_before>import { Injectable } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import WalletConnect from '@walletconnect/client';
import { convertHexToNumber } from '@walletconnect/utils';
import { personalSign, signTypedData_v4 } from 'eth-sig-util';
import { Events } from 'ionic-angular';
import { KeyProvider } from '../../providers/key/key';

import { ConfigProvider } from '../config/config';
import { HomeIntegrationsProvider } from '../home-integrations/home-integrations';

import { Logger } from '../../providers/logger/logger';
import { AnalyticsProvider } from '../analytics/analytics';
import { BwcProvider } from '../bwc/bwc';
import { ErrorsProvider } from '../errors/errors';
import { PersistenceProvider } from '../persistence/persistence';
import { WalletProvider } from '../wallet/wallet';
import {
  IProviderData,
  supportedProviders
} from './web3-providers/web3-providers';

import {
  KOVAN_CHAIN_ID,
  MAINNET_CHAIN_ID
} from '../../providers/wallet-connect/web3-providers/web3-providers';

import * as _ from 'lodash';
import { IncomingDataProvider } from '../incoming-data/incoming-data';

@Injectable()
export class WalletConnectProvider {
  private walletConnector: WalletConnect | null = null;
  private peerMeta: {
    description: string;
    url: string;
    icons: string[];
    name: string;
    ssl?: boolean;
  };
  private requests: any[] = [];
  private connected: boolean = false;
  private address: string;
  private activeChainId: number = 1;
  private walletId: string;

  constructor(
    private logger: Logger,
    private translate: TranslateService,
    private homeIntegrationsProvider: HomeIntegrationsProvider,
    private configProvider: ConfigProvider,
    private analyticsProvider: AnalyticsProvider,
    private persistenceProvider: PersistenceProvider,
    private errorsProvider: ErrorsProvider,
    private walletProvider: WalletProvider,
    private events: Events,
    private incomingDataProvider: IncomingDataProvider,
    private keyProvider: KeyProvider,
    private bwcProvider: BwcProvider
  ) {
    this.logger.debug('WalletConnect Provider initialized');
  }

  public signTypedData(data: any, wallet) {
    const key = this.keyProvider.getKey(wallet.keyId).get();
    const bitcore = this.bwcProvider.getBitcore();
    const xpriv = new bitcore.HDPrivateKey(key.xPrivKey);
    const priv = xpriv.deriveChild("m/44'/60'/0'/0/0").privateKey;
    const result = signTypedData_v4(Buffer.from(priv.toString(), 'hex'), {
      data
    });
    return result;
  }

  public personalSign(data: any, wallet) {
    const key = this.keyProvider.getKey(wallet.keyId).get();
    const bitcore = this.bwcProvider.getBitcore();
    const xpriv = new bitcore.HDPrivateKey(key.xPrivKey);
    const priv = xpriv.deriveChild("m/44'/60'/0'/0/0").privateKey;
    const result = personalSign(Buffer.from(priv.toString(), 'hex'), {
      data
    });
    return result;
  }

  public register(): void {
    this.homeIntegrationsProvider.register({
      name: 'newWalletConnect',
      title: 'WalletConnect',
      icon: 'assets/img/wallet-connect/wallet-connect.svg',
      showIcon: true,
      logo: null,
      logoWidth: '110',
      background:
        'linear-gradient(to bottom,rgba(60, 63, 69, 1) 0,rgba(45, 47, 51, 1) 100%)',
      page: 'WalletConnectPage',
      show: !!this.configProvider.get().showIntegration['newWalletConnect'],
      type: 'external-services'
    });
  }

  public async retrieveWalletConnector(walletConnectData) {
    if (walletConnectData) {
      const session = walletConnectData.session;
      const walletId = walletConnectData.walletId;

      this.logger.debug('retrieving session');

      this.walletConnector = new WalletConnect({ session });

      const { connected, accounts, peerMeta } = this.walletConnector;

      this.address = accounts[0]; // TODO handle multiple accounts

      this.activeChainId = this.walletConnector.chainId;

      this.connected = connected;
      this.peerMeta = peerMeta;
      this.walletId = walletId;

      this.subscribeToEvents();
    }
  }

  public async initWalletConnect(uri): Promise<void> {
    try {
      this.walletConnector = new WalletConnect({
        uri
      });
      if (!this.walletConnector.connected) {
        this.logger.debug('walletConnector.createSession');
        await this.walletConnector.createSession();
      }
      await this.subscribeToEvents();
    } catch (error) {
      this.errorsProvider.showDefaultError(
        error,
        this.translate.instant('Could not connect')
      );
    }
  }

  public checkDappStatus(): Promise<void> {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        if (this.peerMeta) return resolve();

        const error = this.translate.instant(
          'Dapp not responding. Try scanning a new QR code'
        );
        this.errorsProvider.showDefaultError(
          error,
          this.translate.instant('Could not connect')
        );
        return reject(error);
      }, 10000);
    });
  }

  public async getConnectionData() {
    return {
      connected: this.connected,
      peerMeta: this.peerMeta,
      walletId: this.walletId,
      requests: await this.getPendingRequests(),
      address: this.address,
      activeChainId: this.activeChainId<commit_msg>refactored checkDappStatus to use interval<commit_after>import { Injectable } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import WalletConnect from '@walletconnect/client';
import { convertHexToNumber } from '@walletconnect/utils';
import { personalSign, signTypedData_v4 } from 'eth-sig-util';
import { Events } from 'ionic-angular';
import { KeyProvider } from '../../providers/key/key';

import { ConfigProvider } from '../config/config';
import { HomeIntegrationsProvider } from '../home-integrations/home-integrations';

import { Logger } from '../../providers/logger/logger';
import { AnalyticsProvider } from '../analytics/analytics';
import { BwcProvider } from '../bwc/bwc';
import { ErrorsProvider } from '../errors/errors';
import { PersistenceProvider } from '../persistence/persistence';
import { WalletProvider } from '../wallet/wallet';
import {
  IProviderData,
  supportedProviders
} from './web3-providers/web3-providers';

import {
  KOVAN_CHAIN_ID,
  MAINNET_CHAIN_ID
} from '../../providers/wallet-connect/web3-providers/web3-providers';

import * as _ from 'lodash';
import { IncomingDataProvider } from '../incoming-data/incoming-data';

@Injectable()
export class WalletConnectProvider {
  private walletConnector: WalletConnect | null = null;
  private peerMeta: {
    description: string;
    url: string;
    icons: string[];
    name: string;
    ssl?: boolean;
  };
  private requests: any[] = [];
  private connected: boolean = false;
  private address: string;
  private activeChainId: number = 1;
  private walletId: string;

  constructor(
    private logger: Logger,
    private translate: TranslateService,
    private homeIntegrationsProvider: HomeIntegrationsProvider,
    private configProvider: ConfigProvider,
    private analyticsProvider: AnalyticsProvider,
    private persistenceProvider: PersistenceProvider,
    private errorsProvider: ErrorsProvider,
    private walletProvider: WalletProvider,
    private events: Events,
    private incomingDataProvider: IncomingDataProvider,
    private keyProvider: KeyProvider,
    private bwcProvider: BwcProvider
  ) {
    this.logger.debug('WalletConnect Provider initialized');
  }

  public signTypedData(data: any, wallet) {
    const key = this.keyProvider.getKey(wallet.keyId).get();
    const bitcore = this.bwcProvider.getBitcore();
    const xpriv = new bitcore.HDPrivateKey(key.xPrivKey);
    const priv = xpriv.deriveChild("m/44'/60'/0'/0/0").privateKey;
    const result = signTypedData_v4(Buffer.from(priv.toString(), 'hex'), {
      data
    });
    return result;
  }

  public personalSign(data: any, wallet) {
    const key = this.keyProvider.getKey(wallet.keyId).get();
    const bitcore = this.bwcProvider.getBitcore();
    const xpriv = new bitcore.HDPrivateKey(key.xPrivKey);
    const priv = xpriv.deriveChild("m/44'/60'/0'/0/0").privateKey;
    const result = personalSign(Buffer.from(priv.toString(), 'hex'), {
      data
    });
    return result;
  }

  public register(): void {
    this.homeIntegrationsProvider.register({
      name: 'newWalletConnect',
      title: 'WalletConnect',
      icon: 'assets/img/wallet-connect/wallet-connect.svg',
      showIcon: true,
      logo: null,
      logoWidth: '110',
      background:
        'linear-gradient(to bottom,rgba(60, 63, 69, 1) 0,rgba(45, 47, 51, 1) 100%)',
      page: 'WalletConnectPage',
      show: !!this.configProvider.get().showIntegration['newWalletConnect'],
      type: 'external-services'
    });
  }

  public async retrieveWalletConnector(walletConnectData) {
    if (walletConnectData) {
      const session = walletConnectData.session;
      const walletId = walletConnectData.walletId;

      this.logger.debug('retrieving session');

      this.walletConnector = new WalletConnect({ session });

      const { connected, accounts, peerMeta } = this.walletConnector;

      this.address = accounts[0]; // TODO handle multiple accounts

      this.activeChainId = this.walletConnector.chainId;

      this.connected = connected;
      this.peerMeta = peerMeta;
      this.walletId = walletId;

      this.subscribeToEvents();
    }
  }

  public async initWalletConnect(uri): Promise<void> {
    try {
      this.walletConnector = new WalletConnect({
        uri
      });
      if (!this.walletConnector.connected) {
        this.logger.debug('walletConnector.createSession');
        await this.walletConnector.createSession();
      }
      await this.subscribeToEvents();
    } catch (error) {
      this.errorsProvider.showDefaultError(
        error,
        this.translate.instant('Could not connect')
      );
    }
  }

  public checkDappStatus(): Promise<void> {
    return new Promise((resolve, reject) => {
      let retry = 0;
      const interval = setInterval( () => {
        this.logger.log(JSON.stringify(this.peerMeta));
        if (this.peerMeta)  {
          clearInterval(interval);
          return resolve();
        }

        retry++;

        if(retry >= 10) {
          clearInterval(interval);
          const error = this.translate.instant(
            'Dapp not responding. Try scanning a new QR code'
          );
          this.errorsProvider.showDefaultError(
            error,
            this.translate.instant('Could not connect')
          );
          return reject(error);
        }

      }, 1000);
    });
  }

  public async getConnectionData() {
    return {
      connected: this.connected,
      peerMeta: this.peerMeta,
      walletId: this.walletId,
      requests: await this.getPendingRequests(),
      address: this.address,
      activeChainId: this.activeChainId
{'fraction_non_alphanumeric': 0.12138044072118011, 'fraction_numerical': 0.008923693316335822, 'mean_word_length': 3.2718786464410736, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 12, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1361846', 'n_tokens_mistral': 3194, 'n_tokens_neox': 3174, 'n_words': 708}