givenProvider.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. This file is part of web3.js.
  3. web3.js is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Lesser General Public License as published by
  5. the Free Software Foundation, either version 3 of the License, or
  6. (at your option) any later version.
  7. web3.js is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Lesser General Public License for more details.
  11. You should have received a copy of the GNU Lesser General Public License
  12. along with web3.js. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. /**
  15. * @file givenProvider.js
  16. * @author Fabian Vogelsteller <fabian@ethereum.org>
  17. * @date 2017
  18. */
  19. "use strict";
  20. var givenProvider = null;
  21. // ADD GIVEN PROVIDER
  22. /* jshint ignore:start */
  23. var global = typeof globalThis === 'object' ? globalThis : undefined;
  24. if (!global) {
  25. try {
  26. global = Function('return this')();
  27. }
  28. catch (e) {
  29. global = self;
  30. }
  31. }
  32. // EIP-1193: window.ethereum
  33. if (typeof global.ethereum !== 'undefined') {
  34. givenProvider = global.ethereum;
  35. // Legacy web3.currentProvider
  36. }
  37. else if (typeof global.web3 !== 'undefined' && global.web3.currentProvider) {
  38. if (global.web3.currentProvider.sendAsync) {
  39. global.web3.currentProvider.send = global.web3.currentProvider.sendAsync;
  40. delete global.web3.currentProvider.sendAsync;
  41. }
  42. // if connection is 'ipcProviderWrapper', add subscription support
  43. if (!global.web3.currentProvider.on &&
  44. global.web3.currentProvider.connection &&
  45. global.web3.currentProvider.connection.constructor.name === 'ipcProviderWrapper') {
  46. global.web3.currentProvider.on = function (type, callback) {
  47. if (typeof callback !== 'function')
  48. throw new Error('The second parameter callback must be a function.');
  49. switch (type) {
  50. case 'data':
  51. this.connection.on('data', function (data) {
  52. var result = '';
  53. data = data.toString();
  54. try {
  55. result = JSON.parse(data);
  56. }
  57. catch (e) {
  58. return callback(new Error('Couldn\'t parse response data' + data));
  59. }
  60. // notification
  61. if (!result.id && result.method.indexOf('_subscription') !== -1) {
  62. callback(null, result);
  63. }
  64. });
  65. break;
  66. default:
  67. this.connection.on(type, callback);
  68. break;
  69. }
  70. };
  71. }
  72. givenProvider = global.web3.currentProvider;
  73. }
  74. /* jshint ignore:end */
  75. module.exports = givenProvider;