tronprotocol / tronweb

Javascript API Library for interacting with the TRON Network
MIT License
413 stars 271 forks source link

fix: TronWeb not usable within ServiceWorkers in Browser extensions #438

Closed wsdt closed 9 months ago

wsdt commented 10 months ago

TronWeb currently can't be used in Browser Extension Service Workers due to Axios incompatibility with it.

There are usually two ways to fix this:

  1. Convert to fetch
  2. Add a fetch-adapter

Tests seem to run as they did before (some did fail for me before changing anything already).

Had to directly include https://github.com/vespaiach/axios-fetch-adapter as it wasn't possible to use the package as is.

svein1010 commented 10 months ago

Thank you for your great work! It may take a while to equip the function and release a new version. Currently you can create yourself HttpProvider and replace the original Provider with it.

import * as TronWeb from 'tronweb';
class FetchHttpProvider {
  constructor(host, timeout = 30000, user = false, password = false, headers = {}, statusPage = '/') {
    host = host.replace(/\/+$/, '');
    this.host = host;
    this.timeout = timeout;
    this.user = user;
    this.password = password;
    this.headers = headers;
    this.statusPage = statusPage;

    this.instance = axios.create({
      baseURL: host,
      timeout: timeout,
      adapter: fetchAdapter,
      headers: headers,
      auth: user && {
        user,
        password
      }
    });
  }

  setStatusPage(statusPage = '/') {
    this.statusPage = statusPage;
  }
  async isConnected(statusPage = this.statusPage) {
    return this.request(statusPage)
      .then(data => {
        return TronWeb.utils.hasProperties(data, 'blockID', 'block_header');
      })
      .catch(() => false);
  }
  request(url, payload = {}, method = 'get') {
    method = method.toLowerCase();
    return this.instance
      .request({
        data: method == 'post' && Object.keys(payload).length ? payload : null,
        params: method == 'get' && payload,
        url,
        method
      })
      .then(({ data }) => data);
  }
}
TronWeb.providers.HttpProvider = FetchHttpProvider;

const tronWeb = new TronWeb({
  fullHost: 'https://api.nileex.io',
  // headers: { 'TRON-PRO-API-KEY': 'your api key' },
  privateKey: 'Your private key'
});
wsdt commented 9 months ago

Why got this closed?