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

BatchRequest assumes JSON RPC requests are returned in order #4596

Merged
merged 2 commits into from
Dec 6, 2021
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -487,6 +487,7 @@ Released with 1.0.0-beta.37 code base.

### Fixed
- Fix readthedoc's build for web3js documentation (#4425)
- Fix response sorting for batch requests (#4250)

### Changed

Expand Down
9 changes: 8 additions & 1 deletion packages/web3-core-requestmanager/src/batch.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,10 @@ Batch.prototype.add = function (request) {
*/
Batch.prototype.execute = function () {
var requests = this.requests;
var sortResponses = this._sortResponses.bind(this);

this.requestManager.sendBatch(requests, function (err, results) {
results = results || [];
results = sortResponses(results);
requests.map(function (request, index) {
return results[index] || {};
}).forEach(function (result, index) {
Expand All @@ -71,5 +73,10 @@ Batch.prototype.execute = function () {
});
};

// Sort responses
Batch.prototype._sortResponses = function (responses) {
return (responses || []).sort((a, b) => a.id - b.id);
}

module.exports = Batch;

19 changes: 19 additions & 0 deletions test/batch.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,25 @@ var FakeIpcProvider = require('./helpers/FakeIpcProvider');


describe('lib/web3/batch', function () {
describe('_sortResponses', function () {
it('should sort the responses in order of requests', function() {
var provider = new FakeIpcProvider();
var web3 = new Web3(provider);

var batch = new web3.BatchRequest();
batch.add(web3.eth.getBalance.request('0x0000000000000000000000000000000000000000', 'latest', () => {}));
batch.add(web3.eth.getBalance.request('0x0000000000000000000000000000000000000005', 'latest', () => {}));

const res1 = {id: 1, result: 'res1'}
const res2 = {id: 2, result: 'res2'}
const res3 = {id: 3, result: 'res3'}
const sortedResponses = batch._sortResponses([res3, res1, res2]);

assert.deepEqual(sortedResponses, [res1, res2, res3]);
batch.execute();
});
});

describe('execute', function () {
it('should execute batch request', function (done) {

Expand Down