Skip to content

Commit

Permalink
Executes events emit via v8 instead of direct ExecuteScript
Browse files Browse the repository at this point in the history
  • Loading branch information
SergeyZhukovsky committed May 10, 2021
1 parent e572fb1 commit af6e4d0
Show file tree
Hide file tree
Showing 7 changed files with 99 additions and 33 deletions.
11 changes: 11 additions & 0 deletions components/brave_wallet/common/BUILD.gn
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,17 @@ source_set("common") {
"features.cc",
"features.h",
]
deps = [
"//base",
":common_constants",
]
}

source_set("common_constants") {
sources = [
"web3_provider_constants.cc",
"web3_provider_constants.h",
]
deps = [ ":mojom" ]
}

Expand Down
15 changes: 15 additions & 0 deletions components/brave_wallet/common/web3_provider_constants.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/* Copyright (c) 2021 The Brave Authors. All rights reserved.
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "brave/components/brave_wallet/common/web3_provider_constants.h"

namespace brave_wallet {

const char kConnectEvent[] = "connect";
const char kDisconnectEvent[] = "disconnect";
const char kChainChangedEvent[] = "chainChanged";
const char kAccountsChangedEvent[] = "accountsChanged";

} // namespace brave_wallet
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,16 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef BRAVE_COMPONENTS_BRAVE_WALLET_RENDERER_WEB3_PROVIDER_CONSTANTS_H_
#define BRAVE_COMPONENTS_BRAVE_WALLET_RENDERER_WEB3_PROVIDER_CONSTANTS_H_
#ifndef BRAVE_COMPONENTS_BRAVE_WALLET_COMMON_WEB3_PROVIDER_CONSTANTS_H_
#define BRAVE_COMPONENTS_BRAVE_WALLET_COMMON_WEB3_PROVIDER_CONSTANTS_H_

namespace brave_wallet {

extern const char kConnectEvent[];
extern const char kDisconnectEvent[];
extern const char kChainChangedEvent[];
extern const char kAccountsChangedEvent[];

enum class ProviderErrors {
kUserRejectedRequest = 4001, // User rejected the request
kUnauthorized = 4100, // The requested account and/or method has not
Expand All @@ -21,4 +26,4 @@ enum class ProviderErrors {

} // namespace brave_wallet

#endif // BRAVE_COMPONENTS_BRAVE_WALLET_RENDERER_WEB3_PROVIDER_CONSTANTS_H_
#endif // BRAVE_COMPONENTS_BRAVE_WALLET_COMMON_WEB3_PROVIDER_CONSTANTS_H_
2 changes: 1 addition & 1 deletion components/brave_wallet/renderer/BUILD.gn
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ source_set("renderer") {
"brave_wallet_js_handler.h",
"brave_wallet_response_helpers.cc",
"brave_wallet_response_helpers.h",
"web3_provider_constants.h",
]

deps = [
"//base",
"//brave/components/brave_wallet/common:common_constants",
"//brave/components/brave_wallet/common:mojom",
"//brave/components/brave_wallet/resources:ethereum_provider_generated_resources",
"//content/public/renderer",
Expand Down
90 changes: 62 additions & 28 deletions components/brave_wallet/renderer/brave_wallet_js_handler.cc
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,16 @@
#include "brave/components/brave_wallet/renderer/brave_wallet_js_handler.h"

#include <utility>
#include <vector>

#include "base/json/json_writer.h"
#include "base/no_destructor.h"
#include "base/strings/string16.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "brave/components/brave_wallet/common/web3_provider_constants.h"
#include "brave/components/brave_wallet/renderer/brave_wallet_response_helpers.h"
#include "brave/components/brave_wallet/renderer/web3_provider_constants.h"
#include "brave/components/brave_wallet/resources/grit/brave_wallet_script_generated.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/v8_value_converter.h"
Expand All @@ -29,25 +31,9 @@ namespace {

static base::NoDestructor<std::string> g_provider_script("");

const char kConnectEventScript[] =
R"((function() {
window.ethereum.emit('connect', '%s');
})();)";

const char kDisconnectEventScript[] =
R"((function() {
window.ethereum.emit('disconnect', %s);
})();)";

const char kChainChangedEventScript[] =
R"((function() {
window.ethereum.emit('chainChanged', '%s');
})();)";

const char kAccountsChangedEventScript[] =
R"((function() {
window.ethereum.emit('accountsChanged', %s);
})();)";
// Hardcode id to 1 as it is unused
const uint32_t kRequestId = 1;
const char kRequestJsonRPC[] = "2.0";

std::string LoadDataResource(const int id) {
auto& resource_bundle = ui::ResourceBundle::GetSharedInstance();
Expand All @@ -58,6 +44,45 @@ std::string LoadDataResource(const int id) {
return resource_bundle.GetRawDataResource(id).as_string();
}

v8::MaybeLocal<v8::Value> GetProperty(v8::Local<v8::Context> context,
v8::Local<v8::Value> object,
const base::string16& name) {
v8::Isolate* isolate = context->GetIsolate();
v8::Local<v8::String> name_str =
gin::ConvertToV8(isolate, name).As<v8::String>();
v8::Local<v8::Object> object_obj;
if (!object->ToObject(context).ToLocal(&object_obj)) {
return v8::MaybeLocal<v8::Value>();
}

return object_obj->Get(context, name_str);
}

void CallMethodOfObject(blink::WebLocalFrame* web_frame,
const base::string16& object_name,
const base::string16& method_name,
base::Value arguments) {
if (web_frame->IsProvisional())
return;
v8::Local<v8::Context> context = web_frame->MainWorldScriptContext();
v8::Context::Scope context_scope(context);
v8::Local<v8::Value> object;
v8::Local<v8::Value> method;
if (!GetProperty(context, context->Global(), object_name).ToLocal(&object) ||
!GetProperty(context, object, method_name).ToLocal(&method)) {
return;
}
std::vector<v8::Local<v8::Value>> args;
for (auto const& argument : arguments.GetList()) {
args.push_back(content::V8ValueConverter::Create()->ToV8Value(&argument,
context));
}

web_frame->ExecuteMethodAndReturnValue(
v8::Local<v8::Function>::Cast(method), object,
static_cast<int>(args.size()), args.data()).ToLocalChecked();
}

} // namespace

namespace brave_wallet {
Expand Down Expand Up @@ -151,8 +176,8 @@ v8::Local<v8::Promise> BraveWalletJSHandler::Request(
return v8::Local<v8::Promise>();

// Hardcode id to 1 as it is unused
ALLOW_UNUSED_LOCAL(out_dict->SetIntPath("id", 1));
ALLOW_UNUSED_LOCAL(out_dict->SetStringPath("jsonrpc", "2.0"));
ALLOW_UNUSED_LOCAL(out_dict->SetIntPath("id", kRequestId));
ALLOW_UNUSED_LOCAL(out_dict->SetStringPath("jsonrpc", kRequestJsonRPC));
std::string formed_input;
if (!base::JSONWriter::Write(*out_dict, &formed_input))
return v8::Local<v8::Promise>();
Expand Down Expand Up @@ -223,22 +248,31 @@ void BraveWalletJSHandler::InjectInitScript() {
ExecuteScript(*g_provider_script);
}

void BraveWalletJSHandler::FireEvent(const std::string& event,
const std::string& event_args) {
base::Value args = base::Value(base::Value::Type::LIST);
args.Append(event);
args.Append(event_args);
CallMethodOfObject(render_frame_->GetWebFrame(),
STRING16_LITERAL("ethereum"),
STRING16_LITERAL("emit"),
std::move(args));
}

void BraveWalletJSHandler::ConnectEvent(const std::string& chain_id) {
ExecuteScript(base::StringPrintf(kConnectEventScript, chain_id.c_str()));
FireEvent(kConnectEvent, chain_id);
}

void BraveWalletJSHandler::DisconnectEvent(const std::string& message) {
ExecuteScript(base::StringPrintf(kDisconnectEventScript,
FormProviderErrorResponse(message).c_str()));
FireEvent(kDisconnectEvent, message);
}

void BraveWalletJSHandler::ChainChangedEvent(const std::string& chain_id) {
ExecuteScript(base::StringPrintf(kChainChangedEventScript, chain_id.c_str()));
FireEvent(kChainChangedEvent, chain_id);
}

void BraveWalletJSHandler::AccountsChangedEvent(const std::string& accounts) {
ExecuteScript(
base::StringPrintf(kAccountsChangedEventScript, accounts.c_str()));
FireEvent(kAccountsChangedEvent, accounts);
}

} // namespace brave_wallet
1 change: 1 addition & 0 deletions components/brave_wallet/renderer/brave_wallet_js_handler.h
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ class BraveWalletJSHandler {
~BraveWalletJSHandler();

void AddJavaScriptObjectToFrame(v8::Local<v8::Context> context);
void FireEvent(const std::string& event, const std::string& event_args);
void ConnectEvent(const std::string& chain_id);
void DisconnectEvent(const std::string& message);
void ChainChangedEvent(const std::string& chain_id);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
#include <string>

#include "base/values.h"
#include "brave/components/brave_wallet/renderer/web3_provider_constants.h"
#include "brave/components/brave_wallet/common/web3_provider_constants.h"

namespace brave_wallet {

Expand Down

0 comments on commit af6e4d0

Please sign in to comment.