|
| 1 | +(function () { |
| 2 | + var HttpRpcProvider = function (host) { |
| 3 | + this.handlers = []; |
| 4 | + this.host = host; |
| 5 | + }; |
| 6 | + |
| 7 | + function formatJsonRpcObject(object) { |
| 8 | + return { |
| 9 | + jsonrpc: '2.0', |
| 10 | + method: object.call, |
| 11 | + params: object.args, |
| 12 | + id: object._id |
| 13 | + } |
| 14 | + }; |
| 15 | + |
| 16 | + function formatJsonRpcMessage(message) { |
| 17 | + var object = JSON.parse(message); |
| 18 | + |
| 19 | + return { |
| 20 | + _id: object.id, |
| 21 | + data: object.result |
| 22 | + }; |
| 23 | + }; |
| 24 | + |
| 25 | + HttpRpcProvider.prototype.sendRequest = function (payload, cb) { |
| 26 | + var data = formatJsonRpcObject(payload); |
| 27 | + |
| 28 | + var request = new XMLHttpRequest(); |
| 29 | + request.open("POST", this.host, true); |
| 30 | + request.send(JSON.stringify(data)); |
| 31 | + request.onreadystatechange = function () { |
| 32 | + if (request.readyState === 4 && cb) { |
| 33 | + cb(request); |
| 34 | + } |
| 35 | + } |
| 36 | + }; |
| 37 | + |
| 38 | + HttpRpcProvider.prototype.send = function (payload) { |
| 39 | + var self = this; |
| 40 | + this.sendRequest(payload, function (request) { |
| 41 | + self.handlers.forEach(function (handler) { |
| 42 | + handler.call(self, formatJsonRpcMessage(request.responseText)); |
| 43 | + }); |
| 44 | + }); |
| 45 | + }; |
| 46 | + |
| 47 | + HttpRpcProvider.prototype.poll = function (payload, id) { |
| 48 | + var self = this; |
| 49 | + this.sendRequest(payload, function (request) { |
| 50 | + var parsed = JSON.parse(request.responseText); |
| 51 | + if (parsed.result instanceof Array ? parsed.result.length === 0 : !parsed.result) { |
| 52 | + return; |
| 53 | + } |
| 54 | + self.handlers.forEach(function (handler) { |
| 55 | + handler.call(self, {_event: payload.call, _id: id, data: parsed.result}); |
| 56 | + }); |
| 57 | + }); |
| 58 | + }; |
| 59 | + |
| 60 | + Object.defineProperty(HttpRpcProvider.prototype, "onmessage", { |
| 61 | + set: function (handler) { |
| 62 | + this.handlers.push(handler); |
| 63 | + } |
| 64 | + }); |
| 65 | + |
| 66 | + if (typeof(web3) !== "undefined" && web3.providers !== undefined) { |
| 67 | + web3.providers.HttpRpcProvider = HttpRpcProvider; |
| 68 | + } |
| 69 | +})(); |
| 70 | + |
0 commit comments