From 323a91760f6df613fb16f3f3c2b2c9d76b2da0b7 Mon Sep 17 00:00:00 2001 From: Roman Volosovskyi Date: Thu, 29 Dec 2016 20:28:30 +0200 Subject: [PATCH] add StatusHttpProview for accessing web3 in webview --- package.json | 2 +- resources/web3_init.js | 66 +++++++++++++++++++++++++++++++++++++++++- 2 files changed, 66 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index f995439a07..fe0035cde6 100644 --- a/package.json +++ b/package.json @@ -68,7 +68,7 @@ "react-native-tcp": "^2.0.4", "react-native-udp": "^1.2.6", "react-native-vector-icons": "^2.0.3", - "react-native-webview-bridge": "github:status-im/react-native-webview-bridge#0.33.3", + "react-native-webview-bridge": "github:status-im/react-native-webview-bridge#0.33.4", "readable-stream": "^1.0.33", "realm": "^0.14.3", "stream-browserify": "^1.0.0", diff --git a/resources/web3_init.js b/resources/web3_init.js index 6b7cdebe8f..11cd7342e9 100644 --- a/resources/web3_init.js +++ b/resources/web3_init.js @@ -1 +1,65 @@ -web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545")); +var callbackId = 0; +var callbacks = {}; + +function httpCallback(id, data) { + var result = data; + var error = null; + + console.log(data); + + try { + result = JSON.parse(data); + } catch(e) { + error = {message: "InvalidResponse"}; + } + + + callbacks[id](error, result); +} + +var StatusHttpProvider = function (host, timeout) { + this.host = host || 'http://localhost:8545'; + this.timeout = timeout || 0; +}; + +StatusHttpProvider.prototype.send = function (payload) { + throw new Error('You tried to send "'+ payload.method +'" synchronously. Synchronous requests are not supported, sorry.'); +}; + +StatusHttpProvider.prototype.sendAsync = function (payload, callback) { + + var messageId = callbackId++; + callbacks[messageId] = callback; + if(typeof StatusBridge == "undefined") { + var data = { + payload: JSON.stringify(payload), + callbackId: JSON.stringify(messageId) + }; + + webkit.messageHandlers.sendRequest.postMessage(JSON.stringify(data)); + } else { + StatusBridge.sendRequest(JSON.stringify(messageId), JSON.stringify(payload)); + } +}; + +/** + * Synchronously tries to make Http request + * + * @method isConnected + * @return {Boolean} returns true if request haven't failed. Otherwise false + */ +StatusHttpProvider.prototype.isConnected = function() { + try { + this.sendAsync({ + id: 9999999999, + jsonrpc: '2.0', + method: 'net_listening', + params: [] + }, function(){}); + return true; + } catch(e) { + return false; + } +}; + +web3 = new Web3(new StatusHttpProvider("http://localhost:8545"));