Skip to content

Commit

Permalink
BatchRequest assumes JSON RPC requests are returned in order (#4596)
Browse files Browse the repository at this point in the history
* 🐛 Update sorting for the batch request

* 📝 Update the changelog
  • Loading branch information
nazarhussain committed Dec 6, 2021
1 parent 2bd1842 commit 44b0848
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 1 deletion.
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

0 comments on commit 44b0848

Please sign in to comment.