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 all 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: 3 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -565,6 +565,9 @@ 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)

Expand All @@ -575,4 +578,3 @@ Released with 1.0.0-beta.37 code base.
### Security
- Updated `got` lib version and fixed other libs using npm audit fix


26 changes: 20 additions & 6 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
142 changes: 93 additions & 49 deletions packages/web3-providers-http/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,22 +19,26 @@
* Marek Kotewicz <[email protected]>
* Marian Oancea
* Fabian Vogelsteller <[email protected]>
* AyanamiTech <[email protected]>
* @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;
Expand All @@ -52,77 +56,117 @@ 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();
// As the Fetch API supports the credentials as following options 'include', 'omit', 'same-origin'
// https://developer.mozilla.org/en-US/docs/Web/API/fetch#credentials
// To avoid breaking change in 1.x we override this value based on boolean option.
if(this.withCredentials) {
options.credentials = 'include';
} else {
options.credentials = 'omit';
}

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 <[email protected]>
* @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?: boolean;
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
37 changes: 0 additions & 37 deletions test/helpers/FakeIpcProvider2.js

This file was deleted.

Loading