Open wootzappcom opened 3 years ago
https://github.com/trustwallet/trust-web3-provider/blob/master/src/index.js
class TrustWeb3Provider extends EventEmitter {
setConfig(config) {
this.setAddress(config.address);
this.chainId = config.chainId;
this.rpc = new RPCServer(config.rpcUrl);
this.isDebug = !!config.isDebug;
}
request(payload) {
// this points to window in methods like web3.eth.getAccounts()
var that = this;
if (!(this instanceof TrustWeb3Provider)) {
that = window.ethereum;
}
return that._request(payload, false);
}
}
eth_sendTransaction(payload) {
this.postMessage("signTransaction", payload.id, payload.params[0]);
}
eth_requestAccounts(payload) {
this.postMessage("requestAccounts", payload.id, {});
}
window.trustwallet = {
Provider: TrustWeb3Provider,
Web3: Web3,
postMessage: null,
};
webview.addJavascriptInterface(this, "_tw_")
val source = """
(function() {
var config = {
chainId: $chainId,
rpcUrl: "$rpcUrl",
isDebug: true
};
window.ethereum = new trustwallet.Provider(config);
window.web3 = new trustwallet.Web3(window.ethereum);
trustwallet.postMessage = (json) => {
window._tw_.postMessage(JSON.stringify(json));
}
})();
"""
view?.evaluateJavascript(initJs, null)
var config = {
address: "$address",
rpcUrl: "$rpcurl",
chainId: "$chainId"
};
const provider = new window.Trust(config);
window.ethereum = provider;
provider.setMaxListeners(1000);
provider.postMessage = function(handler, id, data) {
switch (handler) {
case 'signTransaction':
var gasLimit = data.gasLimit || data.gas || null;
var gasPrice = data.gasPrice || null;
var nonce = data.nonce || -1;
console.log("signTransaction")
signTransaction.postMessage(id.toLocaleString('fullwide',{useGrouping:false}) + "#" + data);
// return trust.signTransaction(id, data.to || null, data.value, nonce, gasLimit, gasPrice, data.data || null);
case 'signMessage':
console.log("signMessage")
signMessage.postMessage(id.toLocaleString('fullwide',{useGrouping:false}) + "#" + data);
case 'signPersonalMessage':
console.log("signPersonalMessage")
signPersonalMessage.postMessage(id.toLocaleString('fullwide',{useGrouping:false}) + "#" + data);
case 'signTypedMessage':
case 'eth_signTypedData_v3':
console.log("eth_signTypedData_v3")
eth_signTypedData_v3.postMessage(id.toLocaleString('fullwide',{useGrouping:false}) + "#" + data);
case 'requestAccounts':
case 'eth_requestAccounts':
console.log("eth_requestAccounts" + id)
eth_requestAccounts.postMessage(id.toLocaleString('fullwide',{useGrouping:false}) + "#" + data);
}
};
window.web3 = new window.Web3(provider);
window.web3.eth.defaultAccount = config.address;
//Test.postMessage(window.web3.eth.defaultAccount);
window.chrome = {webstore: {}};
//Test.postMessage("over");
})();
reference - https://github.com/hhstore/blog/issues/271
https://stackoverflow.com/questions/53689662/flutter-webview-two-way-communication-with-javascript