Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

web3-providers-http: Migrate from xhr2-cookies to cross-fetch #5179

Merged
merged 7 commits into from
Jul 1, 2022
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -565,10 +565,14 @@ Released with 1.0.0-beta.37 code base.

## [1.7.5]

### Changed
- Replace xhr2-cookies deps to cross-fetch for web3-providers-http (#5085)

### Added
- Documentation details about `maxFeePerGas` and `maxPriorityFeePerGas` (#5121)

### Fixed
- Fix typos in web3-eth-accounts.rst & TESTING.md (#5047)
- Improve README.md & Fix typos (#4848)


30 changes: 23 additions & 7 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 4 additions & 2 deletions packages/web3-providers-http/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,10 @@
"types": "types/index.d.ts",
"main": "lib/index.js",
"dependencies": {
"web3-core-helpers": "1.7.4",
"xhr2-cookies": "1.1.0"
"abortcontroller-polyfill": "^1.7.3",
"cross-fetch": "^3.1.4",
"es6-promise": "^4.2.8",
"web3-core-helpers": "1.7.4"
},
"devDependencies": {
"dtslint": "^3.4.1",
Expand Down
136 changes: 86 additions & 50 deletions packages/web3-providers-http/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,29 +19,33 @@
* Marek Kotewicz <marek@parity.io>
* Marian Oancea
* Fabian Vogelsteller <fabian@ethereum.org>
* AyanamiTech <ayanami0330@protonmail.com>
* @date 2015
*/

var errors = require('web3-core-helpers').errors;
var XHR2 = require('xhr2-cookies').XMLHttpRequest; // jshint ignore: line
var fetch = require('cross-fetch');
var http = require('http');
var https = require('https');

// Apply missing polyfill for IE
require('es6-promise').polyfill();
require('abortcontroller-polyfill/dist/polyfill-patch-fetch');

/**
* HttpProvider should be used to send rpc calls over http
*/
var HttpProvider = function HttpProvider(host, options) {
options = options || {};

this.withCredentials = options.withCredentials || false;
this.withCredentials = options.withCredentials;
this.timeout = options.timeout || 0;
this.headers = options.headers;
this.agent = options.agent;
this.connected = false;

// keepAlive is true unless explicitly set to false
const keepAlive = options.keepAlive !== false;
var keepAlive = options.keepAlive !== false;
this.host = host || 'http://localhost:8545';
if (!this.agent) {
if (this.host.substring(0,5) === "https") {
Expand All @@ -52,77 +56,109 @@ var HttpProvider = function HttpProvider(host, options) {
}
};

HttpProvider.prototype._prepareRequest = function(){
var request;

// the current runtime is a browser
if (typeof XMLHttpRequest !== 'undefined') {
request = new XMLHttpRequest();
/**
* Should be used to make async request
*
* @method send
* @param {Object} payload
* @param {Function} callback triggered on end with (err, result)
*/
HttpProvider.prototype.send = function (payload, callback) {
var options = {
method: 'POST',
body: JSON.stringify(payload)
};
var headers = {};
var controller;

if (typeof AbortController !== 'undefined') {
controller = new AbortController();
} else if (typeof AbortController === 'undefined' && typeof window !== 'undefined' && typeof window.AbortController !== 'undefined') {
// Some chrome version doesn't recognize new AbortController(); so we are using it from window instead
// https://stackoverflow.com/questions/55718778/why-abortcontroller-is-not-defined
controller = new window.AbortController();
} else {
request = new XHR2();
var agents = {httpsAgent: this.httpsAgent, httpAgent: this.httpAgent, baseUrl: this.baseUrl};
// Disable user defined timeout
this.timeout = 0;
}

// the current runtime is node
if (typeof XMLHttpRequest === 'undefined') {
// https://github.com/node-fetch/node-fetch#custom-agent
var agents = {httpsAgent: this.httpsAgent, httpAgent: this.httpAgent};

if (this.agent) {
agents.httpsAgent = this.agent.https;
agents.httpAgent = this.agent.http;
agents.baseUrl = this.agent.baseUrl;
}

request.nodejsSet(agents);
if (this.host.substring(0,5) === "https") {
options.agent = agents.httpsAgent;
} else {
options.agent = agents.httpAgent;
}
}

request.open('POST', this.host, true);
request.setRequestHeader('Content-Type','application/json');
request.timeout = this.timeout;
request.withCredentials = this.withCredentials;

if(this.headers) {
this.headers.forEach(function(header) {
request.setRequestHeader(header.name, header.value);
headers[header.name] = header.value;
});
}

return request;
};
// Default headers
if (!headers['Content-Type']) {
headers['Content-Type'] = 'application/json';
}

/**
* Should be used to make async request
*
* @method send
* @param {Object} payload
* @param {Function} callback triggered on end with (err, result)
*/
HttpProvider.prototype.send = function (payload, callback) {
var _this = this;
var request = this._prepareRequest();
options.credentials = this.withCredentials;
options.headers = headers;

request.onreadystatechange = function() {
if (request.readyState === 4 && request.timeout !== 1) {
var result = request.responseText;
var error = null;
if (this.timeout > 0) {
this.timeoutId = setTimeout(function() {
controller.abort();
}, this.timeout);
}

try {
result = JSON.parse(result);
} catch(e) {
error = errors.InvalidResponse(request.responseText);
}
// Prevent global leak of connected
var _this = this;

_this.connected = true;
callback(error, result);
var success = function(response) {
if (this.timeoutId !== undefined) {
clearTimeout(this.timeoutId);
}
var result = response;
var error = null;

try {
// Response is a stream data so should be awaited for json response
result.json().then(function(data) {
result = data;
_this.connected = true;
callback(error, result);
});
} catch (e) {
_this.connected = false;
callback(errors.InvalidResponse(result));
}
};

request.ontimeout = function() {
_this.connected = false;
callback(errors.ConnectionTimeout(this.timeout));
};
var failed = function(error) {
if (this.timeoutId !== undefined) {
clearTimeout(this.timeoutId);
}

try {
request.send(JSON.stringify(payload));
} catch(error) {
this.connected = false;
if (error.name === 'AbortError') {
_this.connected = false;
callback(errors.ConnectionTimeout(this.timeout));
}

_this.connected = false;
callback(errors.InvalidConnection(this.host));
}

fetch(this.host, options)
.then(success.bind(this))
.catch(failed.bind(this));
};

HttpProvider.prototype.disconnect = function () {
Expand Down
11 changes: 5 additions & 6 deletions packages/web3-providers-http/types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@
* @author Josh Stevens <joshstevens19@hotmail.co.uk>
* @date 2018
*/
import * as http from 'http';
import * as https from 'https';
import type { Agent as HTTPAgent } from 'http';
import type { Agent as HTTPSAgent } from 'https';

import { HttpProviderBase, JsonRpcResponse } from 'web3-core-helpers';

Expand All @@ -30,9 +30,8 @@ export interface HttpHeader {
}

export interface HttpProviderAgent {
baseUrl?: string;
http?: http.Agent;
https?: https.Agent;
http?: HTTPAgent;
https?: HTTPSAgent;
}

export interface HttpProviderOptions {
Expand All @@ -46,7 +45,7 @@ export interface HttpProviderOptions {
export class HttpProvider extends HttpProviderBase {
host: string;

withCredentials: boolean;
withCredentials?: string;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will be breaking change, why we need it to be string?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can remain consistent with existing 1.x https://web3js.readthedocs.io/en/v1.7.4/web3.html#configuration and have withCredentials as boolean in web3.js options obj, and based on boolean value provided by user we can pass string to fetch ( include, omit ) here and it will go as fetch wants plus we will not introduce breaking change.

Copy link

@ghost ghost Jul 1, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jdevcs @nazarhussain Then it should be something more like withCredentials?: boolean | string; and handle boolean value with if block. Great idea.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jdevcs Please re-review.

timeout: number;
headers?: HttpHeader[];
agent?: HttpProviderAgent;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ const httpProvider = new HttpProvider('http://localhost:8545', {
],
withCredentials: false,
agent: {
baseUrl: 'base',
http: new http.Agent({}),
https: new https.Agent({})
}
Expand Down
Loading