diff --git a/browser/brave_content_browser_client.cc b/browser/brave_content_browser_client.cc index 45f5a9bec5f0..a8a174dc0a3d 100644 --- a/browser/brave_content_browser_client.cc +++ b/browser/brave_content_browser_client.cc @@ -144,9 +144,8 @@ using extensions::ChromeContentBrowserClientExtensionsPart; #if BUILDFLAG(BRAVE_WALLET_ENABLED) #include "brave/browser/brave_wallet/brave_wallet_context_utils.h" -#include "brave/browser/brave_wallet/brave_wallet_service_factory.h" +#include "brave/browser/brave_wallet/rpc_controller_factory.h" #include "brave/components/brave_wallet/browser/brave_wallet_provider_impl.h" -#include "brave/components/brave_wallet/browser/brave_wallet_service.h" #include "brave/components/brave_wallet/browser/brave_wallet_utils.h" #include "brave/components/brave_wallet/common/brave_wallet.mojom.h" #if !defined(OS_ANDROID) @@ -207,19 +206,17 @@ void BindCosmeticFiltersResources( void MaybeBindBraveWalletProvider( content::RenderFrameHost* const frame_host, mojo::PendingReceiver receiver) { - auto* context = frame_host->GetBrowserContext(); - if (!brave_wallet::IsAllowedForContext(context)) - return; + auto* rpc_controller = brave_wallet::RpcControllerFactory::GetForContext( + frame_host->GetBrowserContext()); - brave_wallet::BraveWalletService* service = - brave_wallet::BraveWalletServiceFactory::GetInstance()->GetForContext( - context); + if (!rpc_controller) + return; content::WebContents* web_contents = content::WebContents::FromRenderFrameHost(frame_host); mojo::MakeSelfOwnedReceiver( std::make_unique( - service->AsWeakPtr(), + rpc_controller, #if defined(OS_ANDROID) std::make_unique< brave_wallet::BraveWalletProviderDelegateImplAndroid>( diff --git a/browser/brave_profile_prefs.cc b/browser/brave_profile_prefs.cc index 2b64fffd09a3..56bbac192e21 100644 --- a/browser/brave_profile_prefs.cc +++ b/browser/brave_profile_prefs.cc @@ -64,7 +64,7 @@ #endif #if BUILDFLAG(BRAVE_WALLET_ENABLED) -#include "brave/components/brave_wallet/browser/brave_wallet_service.h" +#include "brave/components/brave_wallet/browser/keyring_controller.h" #endif #if BUILDFLAG(ETHEREUM_REMOTE_CLIENT_ENABLED) @@ -331,7 +331,7 @@ void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry) { // Brave Wallet #if BUILDFLAG(BRAVE_WALLET_ENABLED) - brave_wallet::BraveWalletService::RegisterProfilePrefs(registry); + brave_wallet::KeyringController::RegisterProfilePrefs(registry); #endif // Brave Search diff --git a/browser/brave_wallet/BUILD.gn b/browser/brave_wallet/BUILD.gn index 3d819645a97c..355a43e6662b 100644 --- a/browser/brave_wallet/BUILD.gn +++ b/browser/brave_wallet/BUILD.gn @@ -7,14 +7,21 @@ source_set("brave_wallet") { check_includes = false sources = [ + "asset_ratio_controller_factory.cc", + "asset_ratio_controller_factory.h", "brave_wallet_context_utils.cc", "brave_wallet_context_utils.h", - "brave_wallet_service_factory.cc", - "brave_wallet_service_factory.h", + "keyring_controller_factory.cc", + "keyring_controller_factory.h", + "rpc_controller_factory.cc", + "rpc_controller_factory.h", + "swap_controller_factory.cc", + "swap_controller_factory.h", ] deps = [ "//brave/components/brave_wallet/browser", "//brave/components/brave_wallet/common", + "//brave/components/brave_wallet/common:mojom", "//chrome/browser/profiles:profiles", "//components/keyed_service/content:content", "//components/user_prefs", diff --git a/browser/brave_wallet/android/brave_wallet_native_worker.cc b/browser/brave_wallet/android/brave_wallet_native_worker.cc index 0c5de69b024f..a4678fb22968 100644 --- a/browser/brave_wallet/android/brave_wallet_native_worker.cc +++ b/browser/brave_wallet/android/brave_wallet_native_worker.cc @@ -9,23 +9,14 @@ #include "base/android/jni_string.h" #include "base/json/json_writer.h" #include "base/values.h" -#include "brave/browser/brave_wallet/brave_wallet_service_factory.h" +#include "brave/browser/brave_wallet/asset_ratio_controller_factory.h" +#include "brave/browser/brave_wallet/keyring_controller_factory.h" #include "brave/build/android/jni_headers/BraveWalletNativeWorker_jni.h" #include "brave/components/brave_wallet/browser/asset_ratio_controller.h" -#include "brave/components/brave_wallet/browser/brave_wallet_service.h" -#include "brave/components/brave_wallet/browser/hd_keyring.h" #include "brave/components/brave_wallet/browser/keyring_controller.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" - -namespace { - -brave_wallet::BraveWalletService* GetBraveWalletService() { - return brave_wallet::BraveWalletServiceFactory::GetForContext( - ProfileManager::GetActiveUserProfile()->GetOriginalProfile()); -} - -} // namespace +#include "mojo/public/cpp/bindings/pending_receiver.h" namespace chrome { namespace android { @@ -40,6 +31,37 @@ BraveWalletNativeWorker::BraveWalletNativeWorker( BraveWalletNativeWorker::~BraveWalletNativeWorker() {} +void BraveWalletNativeWorker::EnsureConnected() { + auto* profile = ProfileManager::GetActiveUserProfile()->GetOriginalProfile(); + if (!keyring_controller_) { + auto pending = + brave_wallet::KeyringControllerFactory::GetInstance()->GetForContext( + profile); + keyring_controller_.Bind(std::move(pending)); + } + DCHECK(keyring_controller_); + keyring_controller_.set_disconnect_handler( + base::BindOnce(&BraveWalletNativeWorker::OnConnectionError, + weak_ptr_factory_.GetWeakPtr())); + + if (!asset_ratio_controller_) { + auto pending = + brave_wallet::AssetRatioControllerFactory::GetInstance()->GetForContext( + profile); + asset_ratio_controller_.Bind(std::move(pending)); + } + DCHECK(asset_ratio_controller_); + asset_ratio_controller_.set_disconnect_handler( + base::BindOnce(&BraveWalletNativeWorker::OnConnectionError, + weak_ptr_factory_.GetWeakPtr())); +} + +void BraveWalletNativeWorker::OnConnectionError() { + keyring_controller_.reset(); + asset_ratio_controller_.reset(); + EnsureConnected(); +} + void BraveWalletNativeWorker::Destroy( JNIEnv* env, const base::android::JavaParamRef& jcaller) { @@ -48,44 +70,53 @@ void BraveWalletNativeWorker::Destroy( base::android::ScopedJavaLocalRef BraveWalletNativeWorker::GetRecoveryWords(JNIEnv* env) { - auto* keyring_controller = GetBraveWalletService()->keyring_controller(); - keyring_controller->GetMnemonicForDefaultKeyring(); - return base::android::ConvertUTF8ToJavaString( - env, keyring_controller->GetMnemonicForDefaultKeyring()); + EnsureConnected(); + + auto callback = base::BindOnce([](const std::string& mnemonic) {}); + keyring_controller_->GetMnemonicForDefaultKeyring(std::move(callback)); + + // TODO(bridiver) - convert this to callback + return base::android::ConvertUTF8ToJavaString(env, ""); } bool BraveWalletNativeWorker::IsWalletLocked(JNIEnv* env) { - auto* keyring_controller = GetBraveWalletService()->keyring_controller(); - return keyring_controller->IsLocked(); + EnsureConnected(); + // return keyring_controller_->IsLocked(); + return false; } base::android::ScopedJavaLocalRef BraveWalletNativeWorker::CreateWallet( JNIEnv* env, const base::android::JavaParamRef& password) { - auto* keyring_controller = GetBraveWalletService()->keyring_controller(); - auto* keyring = keyring_controller->CreateDefaultKeyring( - base::android::ConvertJavaStringToUTF8(env, password)); - if (keyring) { - keyring->AddAccounts(); - } + EnsureConnected(); - return base::android::ConvertUTF8ToJavaString( - env, keyring_controller->GetMnemonicForDefaultKeyring()); + auto callback = base::BindOnce([](const std::string& mnemonic) {}); + keyring_controller_->CreateWallet( + base::android::ConvertJavaStringToUTF8(env, password), + std::move(callback)); + + // TODO(bridiver) - convert this to callback + return base::android::ConvertUTF8ToJavaString(env, ""); } void BraveWalletNativeWorker::LockWallet(JNIEnv* env) { - auto* keyring_controller = GetBraveWalletService()->keyring_controller(); - keyring_controller->Lock(); + EnsureConnected(); + keyring_controller_->Lock(); } bool BraveWalletNativeWorker::UnlockWallet( JNIEnv* env, const base::android::JavaParamRef& password) { - auto* keyring_controller = GetBraveWalletService()->keyring_controller(); + EnsureConnected(); + + auto callback = base::BindOnce([](bool unlocked) {}); + keyring_controller_->Unlock( + base::android::ConvertJavaStringToUTF8(env, password), + std::move(callback)); - return keyring_controller->Unlock( - base::android::ConvertJavaStringToUTF8(env, password)); + // TODO(bridiver) - convert to callback + return true; } base::android::ScopedJavaLocalRef @@ -93,35 +124,32 @@ BraveWalletNativeWorker::RestoreWallet( JNIEnv* env, const base::android::JavaParamRef& mnemonic, const base::android::JavaParamRef& password) { - auto* keyring_controller = GetBraveWalletService()->keyring_controller(); - auto* keyring = keyring_controller->RestoreDefaultKeyring( + EnsureConnected(); + auto callback = base::BindOnce([](bool is_valid) {}); + keyring_controller_->RestoreWallet( base::android::ConvertJavaStringToUTF8(env, mnemonic), - base::android::ConvertJavaStringToUTF8(env, password)); - if (keyring) { - keyring->AddAccounts(); - } - return base::android::ConvertUTF8ToJavaString( - env, keyring_controller->GetMnemonicForDefaultKeyring()); + base::android::ConvertJavaStringToUTF8(env, password), + std::move(callback)); + + // TODO(bridiver) - convert to callback and this should return true/false not + // the mnemonic + return base::android::ConvertUTF8ToJavaString(env, ""); } void BraveWalletNativeWorker::ResetWallet(JNIEnv* env) { - auto* keyring_controller = GetBraveWalletService()->keyring_controller(); - keyring_controller->Reset(); + EnsureConnected(); + keyring_controller_->Reset(); } void BraveWalletNativeWorker::GetAssetPrice( JNIEnv* env, const base::android::JavaParamRef& asset) { - brave_wallet::BraveWalletService* brave_wallet_service = - GetBraveWalletService(); - if (brave_wallet_service) { - auto* asset_ratio_controller = - brave_wallet_service->asset_ratio_controller(); - asset_ratio_controller->GetPrice( - base::android::ConvertJavaStringToUTF8(env, asset), - base::BindOnce(&BraveWalletNativeWorker::OnGetPrice, - weak_ptr_factory_.GetWeakPtr())); - } + EnsureConnected(); + + asset_ratio_controller_->GetPrice( + base::android::ConvertJavaStringToUTF8(env, asset), + base::BindOnce(&BraveWalletNativeWorker::OnGetPrice, + weak_ptr_factory_.GetWeakPtr())); } void BraveWalletNativeWorker::OnGetPrice(bool success, @@ -136,34 +164,29 @@ void BraveWalletNativeWorker::GetAssetPriceHistory( JNIEnv* env, const base::android::JavaParamRef& asset, const jint timeFrameType) { - brave_wallet::BraveWalletService* brave_wallet_service = - GetBraveWalletService(); - if (brave_wallet_service) { - auto* asset_ratio_controller = - brave_wallet_service->asset_ratio_controller(); - - brave_wallet::mojom::AssetPriceTimeframe time_frame; - if (timeFrameType == 0) { - time_frame = brave_wallet::mojom::AssetPriceTimeframe::Live; - } else if (timeFrameType == 1) { - time_frame = brave_wallet::mojom::AssetPriceTimeframe::OneDay; - } else if (timeFrameType == 2) { - time_frame = brave_wallet::mojom::AssetPriceTimeframe::OneWeek; - } else if (timeFrameType == 3) { - time_frame = brave_wallet::mojom::AssetPriceTimeframe::OneMonth; - } else if (timeFrameType == 4) { - time_frame = brave_wallet::mojom::AssetPriceTimeframe::ThreeMonths; - } else if (timeFrameType == 5) { - time_frame = brave_wallet::mojom::AssetPriceTimeframe::OneYear; - } else { - time_frame = brave_wallet::mojom::AssetPriceTimeframe::All; - } - - asset_ratio_controller->GetPriceHistory( - base::android::ConvertJavaStringToUTF8(env, asset), time_frame, - base::BindOnce(&BraveWalletNativeWorker::OnGetPriceHistory, - weak_ptr_factory_.GetWeakPtr())); + EnsureConnected(); + + brave_wallet::mojom::AssetPriceTimeframe time_frame; + if (timeFrameType == 0) { + time_frame = brave_wallet::mojom::AssetPriceTimeframe::Live; + } else if (timeFrameType == 1) { + time_frame = brave_wallet::mojom::AssetPriceTimeframe::OneDay; + } else if (timeFrameType == 2) { + time_frame = brave_wallet::mojom::AssetPriceTimeframe::OneWeek; + } else if (timeFrameType == 3) { + time_frame = brave_wallet::mojom::AssetPriceTimeframe::OneMonth; + } else if (timeFrameType == 4) { + time_frame = brave_wallet::mojom::AssetPriceTimeframe::ThreeMonths; + } else if (timeFrameType == 5) { + time_frame = brave_wallet::mojom::AssetPriceTimeframe::OneYear; + } else { + time_frame = brave_wallet::mojom::AssetPriceTimeframe::All; } + + asset_ratio_controller_->GetPriceHistory( + base::android::ConvertJavaStringToUTF8(env, asset), time_frame, + base::BindOnce(&BraveWalletNativeWorker::OnGetPriceHistory, + weak_ptr_factory_.GetWeakPtr())); } void BraveWalletNativeWorker::OnGetPriceHistory( diff --git a/browser/brave_wallet/android/brave_wallet_native_worker.h b/browser/brave_wallet/android/brave_wallet_native_worker.h index febbfb483499..c7aaa95fd58c 100644 --- a/browser/brave_wallet/android/brave_wallet_native_worker.h +++ b/browser/brave_wallet/android/brave_wallet_native_worker.h @@ -14,6 +14,7 @@ #include "base/android/jni_weak_ref.h" #include "base/memory/weak_ptr.h" #include "brave/components/brave_wallet/common/brave_wallet.mojom.h" +#include "mojo/public/cpp/bindings/remote.h" namespace chrome { namespace android { @@ -51,6 +52,13 @@ class BraveWalletNativeWorker { std::vector values); private: + void EnsureConnected(); + void OnConnectionError(); + + mojo::Remote keyring_controller_; + mojo::Remote + asset_ratio_controller_; + JavaObjectWeakGlobalRef weak_java_brave_wallet_native_worker_; base::WeakPtrFactory weak_ptr_factory_; }; diff --git a/browser/brave_wallet/asset_ratio_controller_browsertest.cc b/browser/brave_wallet/asset_ratio_controller_browsertest.cc index d3351aa85d9f..4163b5ca7c7e 100644 --- a/browser/brave_wallet/asset_ratio_controller_browsertest.cc +++ b/browser/brave_wallet/asset_ratio_controller_browsertest.cc @@ -3,9 +3,8 @@ * 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/browser/brave_wallet/brave_wallet_service_factory.h" +#include "brave/browser/brave_wallet/asset_ratio_controller_factory.h" #include "brave/components/brave_wallet/browser/asset_ratio_controller.h" -#include "brave/components/brave_wallet/browser/brave_wallet_service.h" #include "brave/components/brave_wallet/common/brave_wallet.mojom.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" @@ -131,16 +130,15 @@ class AssetRatioControllerTest : public InProcessBrowserTest { return browser()->tab_strip_model()->GetActiveWebContents(); } - brave_wallet::BraveWalletService* GetBraveWalletService() { - brave_wallet::BraveWalletService* service = - brave_wallet::BraveWalletServiceFactory::GetInstance()->GetForContext( + mojo::Remote + GetAssetRatioController() { + auto pending = + brave_wallet::AssetRatioControllerFactory::GetInstance()->GetForContext( browser()->profile()); - EXPECT_TRUE(service); - return service; - } - - brave_wallet::AssetRatioController* GetAssetRatioController() { - return GetBraveWalletService()->asset_ratio_controller(); + mojo::Remote + asset_ratio_controller; + asset_ratio_controller.Bind(std::move(pending)); + return asset_ratio_controller; } private: @@ -157,7 +155,7 @@ class AssetRatioControllerTest : public InProcessBrowserTest { IN_PROC_BROWSER_TEST_F(AssetRatioControllerTest, GetPrice) { ResetHTTPSServer(base::BindRepeating(&HandleRequest)); - auto* controller = GetAssetRatioController(); + auto controller = GetAssetRatioController(); controller->GetPrice("basic-attention-token", base::BindOnce(&AssetRatioControllerTest::OnGetPrice, base::Unretained(this))); @@ -166,7 +164,7 @@ IN_PROC_BROWSER_TEST_F(AssetRatioControllerTest, GetPrice) { IN_PROC_BROWSER_TEST_F(AssetRatioControllerTest, GetPriceServerError) { ResetHTTPSServer(base::BindRepeating(&HandleRequestServerError)); - auto* controller = GetAssetRatioController(); + auto controller = GetAssetRatioController(); controller->GetPrice("basic-attention-token", base::BindOnce(&AssetRatioControllerTest::OnGetPrice, base::Unretained(this))); @@ -175,7 +173,7 @@ IN_PROC_BROWSER_TEST_F(AssetRatioControllerTest, GetPriceServerError) { IN_PROC_BROWSER_TEST_F(AssetRatioControllerTest, GetPriceHistory) { ResetHTTPSServer(base::BindRepeating(&HandleRequest)); - auto* controller = GetAssetRatioController(); + auto controller = GetAssetRatioController(); controller->GetPriceHistory( "basic-attention-token", brave_wallet::mojom::AssetPriceTimeframe::OneDay, base::BindOnce(&AssetRatioControllerTest::OnGetPriceHistory, @@ -199,7 +197,7 @@ IN_PROC_BROWSER_TEST_F(AssetRatioControllerTest, GetPriceHistory) { IN_PROC_BROWSER_TEST_F(AssetRatioControllerTest, GetPriceHistoryServerError) { ResetHTTPSServer(base::BindRepeating(&HandleRequestServerError)); - auto* controller = GetAssetRatioController(); + auto controller = GetAssetRatioController(); controller->GetPriceHistory( "basic-attention-token", brave_wallet::mojom::AssetPriceTimeframe::OneDay, base::BindOnce(&AssetRatioControllerTest::OnGetPriceHistory, diff --git a/browser/brave_wallet/asset_ratio_controller_factory.cc b/browser/brave_wallet/asset_ratio_controller_factory.cc new file mode 100644 index 000000000000..1be09d4090bd --- /dev/null +++ b/browser/brave_wallet/asset_ratio_controller_factory.cc @@ -0,0 +1,54 @@ +/* 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/browser/brave_wallet/asset_ratio_controller_factory.h" + +#include "brave/browser/brave_wallet/brave_wallet_context_utils.h" +#include "brave/components/brave_wallet/browser/asset_ratio_controller.h" +#include "chrome/browser/profiles/incognito_helpers.h" +#include "components/keyed_service/content/browser_context_dependency_manager.h" +#include "content/public/browser/storage_partition.h" +#include "services/network/public/cpp/shared_url_loader_factory.h" + +namespace brave_wallet { + +// static +AssetRatioControllerFactory* AssetRatioControllerFactory::GetInstance() { + return base::Singleton::get(); +} + +// static +mojo::PendingRemote +AssetRatioControllerFactory::GetForContext(content::BrowserContext* context) { + if (!IsAllowedForContext(context)) + return mojo::PendingRemote(); + + return static_cast( + GetInstance()->GetServiceForBrowserContext(context, true)) + ->MakeRemote(); +} + +AssetRatioControllerFactory::AssetRatioControllerFactory() + : BrowserContextKeyedServiceFactory( + "AssetRatioController", + BrowserContextDependencyManager::GetInstance()) {} + +AssetRatioControllerFactory::~AssetRatioControllerFactory() {} + +KeyedService* AssetRatioControllerFactory::BuildServiceInstanceFor( + content::BrowserContext* context) const { + auto* default_storage_partition = context->GetDefaultStoragePartition(); + auto shared_url_loader_factory = + default_storage_partition->GetURLLoaderFactoryForBrowserProcess(); + + return new AssetRatioController(shared_url_loader_factory); +} + +content::BrowserContext* AssetRatioControllerFactory::GetBrowserContextToUse( + content::BrowserContext* context) const { + return chrome::GetBrowserContextRedirectedInIncognito(context); +} + +} // namespace brave_wallet diff --git a/browser/brave_wallet/asset_ratio_controller_factory.h b/browser/brave_wallet/asset_ratio_controller_factory.h new file mode 100644 index 000000000000..6ec272ac864b --- /dev/null +++ b/browser/brave_wallet/asset_ratio_controller_factory.h @@ -0,0 +1,44 @@ +/* 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/. */ + +#ifndef BRAVE_BROWSER_BRAVE_WALLET_ASSET_RATIO_CONTROLLER_FACTORY_H_ +#define BRAVE_BROWSER_BRAVE_WALLET_ASSET_RATIO_CONTROLLER_FACTORY_H_ + +#include "base/memory/singleton.h" +#include "brave/components/brave_wallet/common/brave_wallet.mojom.h" +#include "components/keyed_service/content/browser_context_keyed_service_factory.h" +#include "components/keyed_service/core/keyed_service.h" +#include "content/public/browser/browser_context.h" +#include "mojo/public/cpp/bindings/pending_remote.h" + +namespace brave_wallet { + +class AssetRatioController; + +class AssetRatioControllerFactory : public BrowserContextKeyedServiceFactory { + public: + static mojo::PendingRemote GetForContext( + content::BrowserContext* context); + static AssetRatioControllerFactory* GetInstance(); + + private: + friend struct base::DefaultSingletonTraits; + + AssetRatioControllerFactory(); + AssetRatioControllerFactory(const AssetRatioControllerFactory&) = delete; + AssetRatioControllerFactory& operator=(const AssetRatioControllerFactory&) = + delete; + + ~AssetRatioControllerFactory() override; + + KeyedService* BuildServiceInstanceFor( + content::BrowserContext* context) const override; + content::BrowserContext* GetBrowserContextToUse( + content::BrowserContext* context) const override; +}; + +} // namespace brave_wallet + +#endif // BRAVE_BROWSER_BRAVE_WALLET_ASSET_RATIO_CONTROLLER_FACTORY_H_ diff --git a/browser/brave_wallet/brave_wallet_event_emitter_browsertest.cc b/browser/brave_wallet/brave_wallet_event_emitter_browsertest.cc index 1261b986cd97..57e80874c5e5 100644 --- a/browser/brave_wallet/brave_wallet_event_emitter_browsertest.cc +++ b/browser/brave_wallet/brave_wallet_event_emitter_browsertest.cc @@ -7,11 +7,10 @@ #include "base/task/post_task.h" #include "base/test/scoped_feature_list.h" #include "base/test/thread_test_helper.h" -#include "brave/browser/brave_wallet/brave_wallet_service_factory.h" +#include "brave/browser/brave_wallet/rpc_controller_factory.h" #include "brave/common/brave_paths.h" #include "brave/common/pref_names.h" #include "brave/components/brave_wallet/browser/brave_wallet_constants.h" -#include "brave/components/brave_wallet/browser/brave_wallet_service.h" #include "brave/components/brave_wallet/browser/eth_json_rpc_controller.h" #include "brave/components/brave_wallet/common/features.h" #include "chrome/browser/profiles/profile.h" @@ -95,16 +94,12 @@ class BraveWalletEventEmitterTest : public InProcessBrowserTest { net::EmbeddedTestServer* https_server() { return https_server_.get(); } - brave_wallet::BraveWalletService* GetBraveWalletService() { - brave_wallet::BraveWalletService* service = - brave_wallet::BraveWalletServiceFactory::GetInstance()->GetForContext( - browser()->profile()); - EXPECT_TRUE(service); - return service; - } - brave_wallet::EthJsonRpcController* GetEthJsonRpcController() { - return GetBraveWalletService()->rpc_controller(); + brave_wallet::EthJsonRpcController* controller = + brave_wallet::RpcControllerFactory::GetInstance()->GetForContext( + browser()->profile()); + EXPECT_NE(controller, nullptr); + return controller; } private: diff --git a/browser/brave_wallet/brave_wallet_service_factory.cc b/browser/brave_wallet/brave_wallet_service_factory.cc deleted file mode 100644 index cceff200a379..000000000000 --- a/browser/brave_wallet/brave_wallet_service_factory.cc +++ /dev/null @@ -1,56 +0,0 @@ -/* Copyright (c) 2019 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/browser/brave_wallet/brave_wallet_service_factory.h" - -#include "brave/components/brave_wallet/browser/brave_wallet_service.h" -#include "chrome/browser/profiles/incognito_helpers.h" -#include "components/keyed_service/content/browser_context_dependency_manager.h" -#include "components/user_prefs/user_prefs.h" -#include "content/public/browser/browser_context.h" -#include "content/public/browser/storage_partition.h" -#include "services/network/public/cpp/shared_url_loader_factory.h" - -namespace brave_wallet { - -// static -BraveWalletServiceFactory* BraveWalletServiceFactory::GetInstance() { - return base::Singleton::get(); -} - -// static -BraveWalletService* BraveWalletServiceFactory::GetForContext( - content::BrowserContext* context) { - return static_cast( - GetInstance()->GetServiceForBrowserContext(context, true)); -} - -BraveWalletServiceFactory::BraveWalletServiceFactory() - : BrowserContextKeyedServiceFactory( - "BraveWalletService", - BrowserContextDependencyManager::GetInstance()) { -} - -BraveWalletServiceFactory::~BraveWalletServiceFactory() {} - -KeyedService* BraveWalletServiceFactory::BuildServiceInstanceFor( - content::BrowserContext* context) const { - auto* default_storage_partition = context->GetDefaultStoragePartition(); - auto shared_url_loader_factory = - default_storage_partition->GetURLLoaderFactoryForBrowserProcess(); - return new BraveWalletService(user_prefs::UserPrefs::Get(context), - shared_url_loader_factory); -} - -content::BrowserContext* BraveWalletServiceFactory::GetBrowserContextToUse( - content::BrowserContext* context) const { - return chrome::GetBrowserContextRedirectedInIncognito(context); -} - -bool BraveWalletServiceFactory::ServiceIsCreatedWithBrowserContext() const { - return true; -} - -} // namespace brave_wallet diff --git a/browser/brave_wallet/brave_wallet_service_factory.h b/browser/brave_wallet/brave_wallet_service_factory.h deleted file mode 100644 index 3a6beaba4565..000000000000 --- a/browser/brave_wallet/brave_wallet_service_factory.h +++ /dev/null @@ -1,38 +0,0 @@ -/* Copyright (c) 2019 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/. */ - -#ifndef BRAVE_BROWSER_BRAVE_WALLET_BRAVE_WALLET_SERVICE_FACTORY_H_ -#define BRAVE_BROWSER_BRAVE_WALLET_BRAVE_WALLET_SERVICE_FACTORY_H_ - -#include "base/memory/singleton.h" -#include "components/keyed_service/content/browser_context_keyed_service_factory.h" - -namespace brave_wallet { - -class BraveWalletService; - -class BraveWalletServiceFactory : public BrowserContextKeyedServiceFactory { - public: - static BraveWalletService* GetForContext(content::BrowserContext* context); - static BraveWalletServiceFactory* GetInstance(); - - private: - friend struct base::DefaultSingletonTraits; - - BraveWalletServiceFactory(); - ~BraveWalletServiceFactory() override; - - KeyedService* BuildServiceInstanceFor( - content::BrowserContext* context) const override; - content::BrowserContext* GetBrowserContextToUse( - content::BrowserContext* context) const override; - bool ServiceIsCreatedWithBrowserContext() const override; - - DISALLOW_COPY_AND_ASSIGN(BraveWalletServiceFactory); -}; - -} // namespace brave_wallet - -#endif // BRAVE_BROWSER_BRAVE_WALLET_BRAVE_WALLET_SERVICE_FACTORY_H_ diff --git a/browser/brave_wallet/eth_json_rpc_controller_browsertest.cc b/browser/brave_wallet/eth_json_rpc_controller_browsertest.cc index dd1a45c9d972..764a4736876f 100644 --- a/browser/brave_wallet/eth_json_rpc_controller_browsertest.cc +++ b/browser/brave_wallet/eth_json_rpc_controller_browsertest.cc @@ -4,10 +4,9 @@ * You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "base/path_service.h" -#include "brave/browser/brave_wallet/brave_wallet_service_factory.h" +#include "brave/browser/brave_wallet/rpc_controller_factory.h" #include "brave/common/brave_paths.h" #include "brave/common/pref_names.h" -#include "brave/components/brave_wallet/browser/brave_wallet_service.h" #include "brave/components/brave_wallet/browser/eth_json_rpc_controller.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" @@ -156,16 +155,12 @@ class EthJsonRpcBrowserTest : public InProcessBrowserTest { return browser()->tab_strip_model()->GetActiveWebContents(); } - brave_wallet::BraveWalletService* GetBraveWalletService() { - brave_wallet::BraveWalletService* service = - brave_wallet::BraveWalletServiceFactory::GetInstance()->GetForContext( - browser()->profile()); - EXPECT_TRUE(service); - return service; - } - brave_wallet::EthJsonRpcController* GetEthJsonRpcController() { - return GetBraveWalletService()->rpc_controller(); + brave_wallet::EthJsonRpcController* controller = + brave_wallet::RpcControllerFactory::GetInstance()->GetForContext( + browser()->profile()); + EXPECT_NE(controller, nullptr); + return controller; } private: diff --git a/browser/brave_wallet/keyring_controller_factory.cc b/browser/brave_wallet/keyring_controller_factory.cc new file mode 100644 index 000000000000..8f0ab247a21f --- /dev/null +++ b/browser/brave_wallet/keyring_controller_factory.cc @@ -0,0 +1,49 @@ +/* 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/browser/brave_wallet/keyring_controller_factory.h" + +#include "brave/browser/brave_wallet/brave_wallet_context_utils.h" +#include "brave/components/brave_wallet/browser/keyring_controller.h" +#include "chrome/browser/profiles/incognito_helpers.h" +#include "components/keyed_service/content/browser_context_dependency_manager.h" +#include "components/user_prefs/user_prefs.h" + +namespace brave_wallet { + +// static +KeyringControllerFactory* KeyringControllerFactory::GetInstance() { + return base::Singleton::get(); +} + +// static +mojo::PendingRemote +KeyringControllerFactory::GetForContext(content::BrowserContext* context) { + if (!IsAllowedForContext(context)) + return mojo::PendingRemote(); + + return static_cast( + GetInstance()->GetServiceForBrowserContext(context, true)) + ->MakeRemote(); +} + +KeyringControllerFactory::KeyringControllerFactory() + : BrowserContextKeyedServiceFactory( + "KeyringController", + BrowserContextDependencyManager::GetInstance()) {} + +KeyringControllerFactory::~KeyringControllerFactory() {} + +KeyedService* KeyringControllerFactory::BuildServiceInstanceFor( + content::BrowserContext* context) const { + return new KeyringController(user_prefs::UserPrefs::Get(context)); +} + +content::BrowserContext* KeyringControllerFactory::GetBrowserContextToUse( + content::BrowserContext* context) const { + return chrome::GetBrowserContextRedirectedInIncognito(context); +} + +} // namespace brave_wallet diff --git a/browser/brave_wallet/keyring_controller_factory.h b/browser/brave_wallet/keyring_controller_factory.h new file mode 100644 index 000000000000..511b3ee3bdbf --- /dev/null +++ b/browser/brave_wallet/keyring_controller_factory.h @@ -0,0 +1,42 @@ +/* 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/. */ + +#ifndef BRAVE_BROWSER_BRAVE_WALLET_KEYRING_CONTROLLER_FACTORY_H_ +#define BRAVE_BROWSER_BRAVE_WALLET_KEYRING_CONTROLLER_FACTORY_H_ + +#include "base/memory/singleton.h" +#include "brave/components/brave_wallet/common/brave_wallet.mojom.h" +#include "components/keyed_service/content/browser_context_keyed_service_factory.h" +#include "components/keyed_service/core/keyed_service.h" +#include "content/public/browser/browser_context.h" +#include "mojo/public/cpp/bindings/pending_remote.h" + +namespace brave_wallet { + +class KeyringController; + +class KeyringControllerFactory : public BrowserContextKeyedServiceFactory { + public: + static mojo::PendingRemote GetForContext( + content::BrowserContext* context); + static KeyringControllerFactory* GetInstance(); + + private: + friend struct base::DefaultSingletonTraits; + + KeyringControllerFactory(); + ~KeyringControllerFactory() override; + + KeyedService* BuildServiceInstanceFor( + content::BrowserContext* context) const override; + content::BrowserContext* GetBrowserContextToUse( + content::BrowserContext* context) const override; + + DISALLOW_COPY_AND_ASSIGN(KeyringControllerFactory); +}; + +} // namespace brave_wallet + +#endif // BRAVE_BROWSER_BRAVE_WALLET_KEYRING_CONTROLLER_FACTORY_H_ diff --git a/browser/brave_wallet/rpc_controller_factory.cc b/browser/brave_wallet/rpc_controller_factory.cc new file mode 100644 index 000000000000..8d362a3445df --- /dev/null +++ b/browser/brave_wallet/rpc_controller_factory.cc @@ -0,0 +1,56 @@ +/* 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/browser/brave_wallet/rpc_controller_factory.h" + +#include "brave/browser/brave_wallet/brave_wallet_context_utils.h" +#include "brave/components/brave_wallet/browser/brave_wallet_constants.h" +#include "brave/components/brave_wallet/browser/eth_json_rpc_controller.h" +#include "chrome/browser/profiles/incognito_helpers.h" +#include "components/keyed_service/content/browser_context_dependency_manager.h" +#include "content/public/browser/storage_partition.h" +#include "services/network/public/cpp/shared_url_loader_factory.h" + +namespace brave_wallet { + +// static +RpcControllerFactory* RpcControllerFactory::GetInstance() { + return base::Singleton::get(); +} + +// static +EthJsonRpcController* RpcControllerFactory::GetForContext( + content::BrowserContext* context) { + if (!IsAllowedForContext(context)) { + return nullptr; + } + + return static_cast( + GetInstance()->GetServiceForBrowserContext(context, true)); +} + +RpcControllerFactory::RpcControllerFactory() + : BrowserContextKeyedServiceFactory( + "RpcController", + BrowserContextDependencyManager::GetInstance()) {} + +RpcControllerFactory::~RpcControllerFactory() {} + +KeyedService* RpcControllerFactory::BuildServiceInstanceFor( + content::BrowserContext* context) const { + auto* default_storage_partition = context->GetDefaultStoragePartition(); + auto shared_url_loader_factory = + default_storage_partition->GetURLLoaderFactoryForBrowserProcess(); + + return new EthJsonRpcController(brave_wallet::Network::kMainnet, + shared_url_loader_factory); +} + +content::BrowserContext* RpcControllerFactory::GetBrowserContextToUse( + content::BrowserContext* context) const { + return chrome::GetBrowserContextRedirectedInIncognito(context); +} + +} // namespace brave_wallet diff --git a/browser/brave_wallet/rpc_controller_factory.h b/browser/brave_wallet/rpc_controller_factory.h new file mode 100644 index 000000000000..d0ef1d1ba481 --- /dev/null +++ b/browser/brave_wallet/rpc_controller_factory.h @@ -0,0 +1,39 @@ +/* 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/. */ + +#ifndef BRAVE_BROWSER_BRAVE_WALLET_RPC_CONTROLLER_FACTORY_H_ +#define BRAVE_BROWSER_BRAVE_WALLET_RPC_CONTROLLER_FACTORY_H_ + +#include "base/memory/singleton.h" +#include "components/keyed_service/content/browser_context_keyed_service_factory.h" +#include "components/keyed_service/core/keyed_service.h" +#include "content/public/browser/browser_context.h" + +namespace brave_wallet { + +class EthJsonRpcController; + +class RpcControllerFactory : public BrowserContextKeyedServiceFactory { + public: + static EthJsonRpcController* GetForContext(content::BrowserContext* context); + static RpcControllerFactory* GetInstance(); + + private: + friend struct base::DefaultSingletonTraits; + + RpcControllerFactory(); + ~RpcControllerFactory() override; + + KeyedService* BuildServiceInstanceFor( + content::BrowserContext* context) const override; + content::BrowserContext* GetBrowserContextToUse( + content::BrowserContext* context) const override; + + DISALLOW_COPY_AND_ASSIGN(RpcControllerFactory); +}; + +} // namespace brave_wallet + +#endif // BRAVE_BROWSER_BRAVE_WALLET_RPC_CONTROLLER_FACTORY_H_ diff --git a/browser/brave_wallet/swap_controller_browsertest.cc b/browser/brave_wallet/swap_controller_browsertest.cc index 3448b20c07a6..cd45f4263c29 100644 --- a/browser/brave_wallet/swap_controller_browsertest.cc +++ b/browser/brave_wallet/swap_controller_browsertest.cc @@ -3,8 +3,7 @@ * 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/browser/brave_wallet/brave_wallet_service_factory.h" -#include "brave/components/brave_wallet/browser/brave_wallet_service.h" +#include "brave/browser/brave_wallet/swap_controller_factory.h" #include "brave/components/brave_wallet/browser/swap_controller.h" #include "brave/components/brave_wallet/common/brave_wallet.mojom.h" #include "chrome/browser/profiles/profile.h" @@ -13,6 +12,7 @@ #include "chrome/test/base/ui_test_utils.h" #include "content/public/test/browser_test.h" #include "content/public/test/browser_test_utils.h" +#include "mojo/public/cpp/bindings/remote.h" #include "net/base/url_util.h" #include "net/dns/mock_host_resolver.h" #include "net/test/embedded_test_server/http_request.h" @@ -86,11 +86,11 @@ std::unique_ptr HandleRequestServerError( return std::move(http_response); } -brave_wallet::mojom::SwapParams GetCannedSwapParams() { - brave_wallet::mojom::SwapParams params; - params.buy_token = "ETH"; - params.sell_token = "DAI"; - params.buy_amount = "1000000000000000000000"; +brave_wallet::mojom::SwapParamsPtr GetCannedSwapParams() { + auto params = brave_wallet::mojom::SwapParams::New(); + params->buy_token = "ETH"; + params->sell_token = "DAI"; + params->buy_amount = "1000000000000000000000"; return params; } // namespace @@ -209,16 +209,13 @@ class SwapControllerTest : public InProcessBrowserTest { return browser()->tab_strip_model()->GetActiveWebContents(); } - brave_wallet::BraveWalletService* GetBraveWalletService() { - brave_wallet::BraveWalletService* service = - brave_wallet::BraveWalletServiceFactory::GetInstance()->GetForContext( + mojo::Remote GetSwapController() { + auto pending = + brave_wallet::SwapControllerFactory::GetInstance()->GetForContext( browser()->profile()); - EXPECT_TRUE(service); - return service; - } - - brave_wallet::SwapController* GetSwapController() { - return GetBraveWalletService()->swap_controller(); + mojo::Remote asset_ratio_controller; + asset_ratio_controller.Bind(std::move(pending)); + return asset_ratio_controller; } private: @@ -237,7 +234,7 @@ IN_PROC_BROWSER_TEST_F(SwapControllerTest, GetPriceQuote) { params.buy_token = "ETH"; params.sell_token = "DAI"; params.buy_amount = "1000000000000000000000"; - auto* controller = GetSwapController(); + auto controller = GetSwapController(); controller->GetPriceQuote( GetCannedSwapParams(), base::BindOnce(&SwapControllerTest::OnGetPriceQuoteResponse, @@ -266,7 +263,7 @@ IN_PROC_BROWSER_TEST_F(SwapControllerTest, GetPriceQuote) { IN_PROC_BROWSER_TEST_F(SwapControllerTest, GetPriceQuoteServerError) { ResetHTTPSServer(base::BindRepeating(&HandleRequestServerError)); - auto* controller = GetSwapController(); + auto controller = GetSwapController(); controller->GetPriceQuote( GetCannedSwapParams(), base::BindOnce(&SwapControllerTest::OnGetPriceQuoteResponse, @@ -277,7 +274,7 @@ IN_PROC_BROWSER_TEST_F(SwapControllerTest, GetPriceQuoteServerError) { IN_PROC_BROWSER_TEST_F(SwapControllerTest, GetTransactionPayload) { ResetHTTPSServer(base::BindRepeating(&HandleRequest)); - auto* controller = GetSwapController(); + auto controller = GetSwapController(); controller->GetTransactionPayload( GetCannedSwapParams(), base::BindOnce(&SwapControllerTest::OnGetTransactionPayloadResponse, @@ -310,7 +307,7 @@ IN_PROC_BROWSER_TEST_F(SwapControllerTest, GetTransactionPayload) { IN_PROC_BROWSER_TEST_F(SwapControllerTest, GetTransactionPayloadServerError) { ResetHTTPSServer(base::BindRepeating(&HandleRequestServerError)); - auto* controller = GetSwapController(); + auto controller = GetSwapController(); controller->GetTransactionPayload( GetCannedSwapParams(), base::BindOnce(&SwapControllerTest::OnGetTransactionPayloadResponse, diff --git a/browser/brave_wallet/swap_controller_factory.cc b/browser/brave_wallet/swap_controller_factory.cc new file mode 100644 index 000000000000..fb1e7f55a490 --- /dev/null +++ b/browser/brave_wallet/swap_controller_factory.cc @@ -0,0 +1,54 @@ +/* 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/browser/brave_wallet/swap_controller_factory.h" + +#include "brave/browser/brave_wallet/brave_wallet_context_utils.h" +#include "brave/components/brave_wallet/browser/swap_controller.h" +#include "chrome/browser/profiles/incognito_helpers.h" +#include "components/keyed_service/content/browser_context_dependency_manager.h" +#include "content/public/browser/storage_partition.h" +#include "services/network/public/cpp/shared_url_loader_factory.h" + +namespace brave_wallet { + +// static +SwapControllerFactory* SwapControllerFactory::GetInstance() { + return base::Singleton::get(); +} + +// static +mojo::PendingRemote SwapControllerFactory::GetForContext( + content::BrowserContext* context) { + if (!IsAllowedForContext(context)) + return mojo::PendingRemote(); + + return static_cast( + GetInstance()->GetServiceForBrowserContext(context, true)) + ->MakeRemote(); +} + +SwapControllerFactory::SwapControllerFactory() + : BrowserContextKeyedServiceFactory( + "SwapController", + BrowserContextDependencyManager::GetInstance()) {} + +SwapControllerFactory::~SwapControllerFactory() {} + +KeyedService* SwapControllerFactory::BuildServiceInstanceFor( + content::BrowserContext* context) const { + auto* default_storage_partition = context->GetDefaultStoragePartition(); + auto shared_url_loader_factory = + default_storage_partition->GetURLLoaderFactoryForBrowserProcess(); + + return new SwapController(shared_url_loader_factory); +} + +content::BrowserContext* SwapControllerFactory::GetBrowserContextToUse( + content::BrowserContext* context) const { + return chrome::GetBrowserContextRedirectedInIncognito(context); +} + +} // namespace brave_wallet diff --git a/browser/brave_wallet/swap_controller_factory.h b/browser/brave_wallet/swap_controller_factory.h new file mode 100644 index 000000000000..61bc062f8c84 --- /dev/null +++ b/browser/brave_wallet/swap_controller_factory.h @@ -0,0 +1,43 @@ +/* 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/. */ + +#ifndef BRAVE_BROWSER_BRAVE_WALLET_SWAP_CONTROLLER_FACTORY_H_ +#define BRAVE_BROWSER_BRAVE_WALLET_SWAP_CONTROLLER_FACTORY_H_ + +#include "base/memory/singleton.h" +#include "brave/components/brave_wallet/common/brave_wallet.mojom.h" +#include "components/keyed_service/content/browser_context_keyed_service_factory.h" +#include "components/keyed_service/core/keyed_service.h" +#include "content/public/browser/browser_context.h" +#include "mojo/public/cpp/bindings/pending_remote.h" + +namespace brave_wallet { + +class SwapController; + +class SwapControllerFactory : public BrowserContextKeyedServiceFactory { + public: + static mojo::PendingRemote GetForContext( + content::BrowserContext* context); + static SwapControllerFactory* GetInstance(); + + private: + friend struct base::DefaultSingletonTraits; + + SwapControllerFactory(); + SwapControllerFactory(const SwapControllerFactory&) = delete; + SwapControllerFactory& operator=(const SwapControllerFactory&) = delete; + + ~SwapControllerFactory() override; + + KeyedService* BuildServiceInstanceFor( + content::BrowserContext* context) const override; + content::BrowserContext* GetBrowserContextToUse( + content::BrowserContext* context) const override; +}; + +} // namespace brave_wallet + +#endif // BRAVE_BROWSER_BRAVE_WALLET_SWAP_CONTROLLER_FACTORY_H_ diff --git a/browser/browser_context_keyed_service_factories.cc b/browser/browser_context_keyed_service_factories.cc index 5d9a9828cb15..8706ab690e32 100644 --- a/browser/browser_context_keyed_service_factories.cc +++ b/browser/browser_context_keyed_service_factories.cc @@ -34,7 +34,10 @@ #endif #if BUILDFLAG(BRAVE_WALLET_ENABLED) -#include "brave/browser/brave_wallet/brave_wallet_service_factory.h" +#include "brave/browser/brave_wallet/asset_ratio_controller_factory.h" +#include "brave/browser/brave_wallet/keyring_controller_factory.h" +#include "brave/browser/brave_wallet/rpc_controller_factory.h" +#include "brave/browser/brave_wallet/swap_controller_factory.h" #endif #if BUILDFLAG(ETHEREUM_REMOTE_CLIENT_ENABLED) @@ -75,7 +78,10 @@ void EnsureBrowserContextKeyedServiceFactoriesBuilt() { #endif #if BUILDFLAG(BRAVE_WALLET_ENABLED) - brave_wallet::BraveWalletServiceFactory::GetInstance(); + brave_wallet::AssetRatioControllerFactory::GetInstance(); + brave_wallet::KeyringControllerFactory::GetInstance(); + brave_wallet::RpcControllerFactory::GetInstance(); + brave_wallet::SwapControllerFactory::GetInstance(); #endif #if BUILDFLAG(ETHEREUM_REMOTE_CLIENT_ENABLED) diff --git a/browser/net/decentralized_dns_network_delegate_helper.cc b/browser/net/decentralized_dns_network_delegate_helper.cc index 9d85b732365a..24e7dbbad435 100644 --- a/browser/net/decentralized_dns_network_delegate_helper.cc +++ b/browser/net/decentralized_dns_network_delegate_helper.cc @@ -7,17 +7,16 @@ #include -#include "net/base/net_errors.h" - -#include "brave/browser/brave_wallet/brave_wallet_service_factory.h" -#include "brave/components/brave_wallet/browser/brave_wallet_service.h" +#include "brave/browser/brave_wallet/rpc_controller_factory.h" #include "brave/components/brave_wallet/browser/brave_wallet_utils.h" +#include "brave/components/brave_wallet/browser/eth_call_data_builder.h" #include "brave/components/brave_wallet/browser/eth_json_rpc_controller.h" #include "brave/components/decentralized_dns/constants.h" #include "brave/components/decentralized_dns/utils.h" #include "brave/components/ipfs/ipfs_utils.h" #include "chrome/browser/browser_process.h" #include "content/public/browser/browser_context.h" +#include "net/base/net_errors.h" namespace decentralized_dns { @@ -37,41 +36,40 @@ int OnBeforeURLRequest_DecentralizedDnsPreRedirectWork( return net::OK; } + auto* rpc_controller = + brave_wallet::RpcControllerFactory::GetForContext(ctx->browser_context); + + if (!rpc_controller) + return net::OK; + if (IsUnstoppableDomainsTLD(ctx->request_url) && IsUnstoppableDomainsResolveMethodEthereum( g_browser_process->local_state())) { - auto* service = brave_wallet::BraveWalletServiceFactory::GetForContext( - ctx->browser_context); - if (!service) { - return net::OK; - } - - if (!service->rpc_controller()->UnstoppableDomainsProxyReaderGetMany( - kProxyReaderContractAddress, ctx->request_url.host(), - std::vector(std::begin(kRecordKeys), - std::end(kRecordKeys)), - base::BindOnce(&OnBeforeURLRequest_DecentralizedDnsRedirectWork, - next_callback, ctx))) { + auto keys = std::vector(std::begin(kRecordKeys), + std::end(kRecordKeys)); + std::string data; + if (!brave_wallet::unstoppable_domains::GetMany( + keys, ctx->request_url.host(), &data)) return net::OK; - } + + rpc_controller->UnstoppableDomainsProxyReaderGetMany( + kProxyReaderContractAddress, ctx->request_url.host(), keys, + base::BindOnce(&OnBeforeURLRequest_DecentralizedDnsRedirectWork, + next_callback, ctx)); return net::ERR_IO_PENDING; } if (IsENSTLD(ctx->request_url) && IsENSResolveMethodEthereum(g_browser_process->local_state())) { - auto* service = brave_wallet::BraveWalletServiceFactory::GetForContext( - ctx->browser_context); - if (!service) { + std::string data; + if (!brave_wallet::ens::GetResolverAddress(ctx->request_url.host(), &data)) return net::OK; - } - if (!service->rpc_controller()->EnsProxyReaderGetResolverAddress( - kEnsRegistryContractAddress, ctx->request_url.host(), - base::BindOnce(&OnBeforeURLRequest_EnsRedirectWork, next_callback, - ctx))) { - return net::OK; - } + rpc_controller->EnsProxyReaderGetResolverAddress( + kEnsRegistryContractAddress, ctx->request_url.host(), + base::BindOnce(&OnBeforeURLRequest_EnsRedirectWork, next_callback, + ctx)); return net::ERR_IO_PENDING; } diff --git a/browser/ui/webui/brave_wallet/common_handler/wallet_handler.cc b/browser/ui/webui/brave_wallet/common_handler/wallet_handler.cc index a4c528808816..2d9f31b96d7e 100644 --- a/browser/ui/webui/brave_wallet/common_handler/wallet_handler.cc +++ b/browser/ui/webui/brave_wallet/common_handler/wallet_handler.cc @@ -9,46 +9,76 @@ #include #include -#include "brave/browser/brave_wallet/brave_wallet_service_factory.h" +#include "base/bind.h" +#include "brave/browser/brave_wallet/asset_ratio_controller_factory.h" +#include "brave/browser/brave_wallet/keyring_controller_factory.h" +#include "brave/browser/brave_wallet/swap_controller_factory.h" #include "brave/components/brave_wallet/browser/asset_ratio_controller.h" -#include "brave/components/brave_wallet/browser/brave_wallet_service.h" #include "brave/components/brave_wallet/browser/hd_keyring.h" #include "brave/components/brave_wallet/browser/keyring_controller.h" #include "brave/components/brave_wallet/browser/swap_controller.h" #include "chrome/browser/profiles/profile.h" -#include "content/public/browser/web_ui.h" - -namespace { - -brave_wallet::BraveWalletService* GetBraveWalletService( - content::BrowserContext* context) { - return brave_wallet::BraveWalletServiceFactory::GetInstance()->GetForContext( - context); -} - -} // namespace WalletHandler::WalletHandler( mojo::PendingReceiver receiver, - mojo::PendingRemote page, - content::WebUI* web_ui, - ui::MojoWebUIController* webui_controller) + Profile* profile) : receiver_(this, std::move(receiver)), - page_(std::move(page)), - web_ui_(web_ui), + profile_(profile), weak_ptr_factory_(this) {} WalletHandler::~WalletHandler() = default; +void WalletHandler::EnsureConnected() { + if (!keyring_controller_) { + auto pending = + brave_wallet::KeyringControllerFactory::GetInstance()->GetForContext( + profile_); + keyring_controller_.Bind(std::move(pending)); + } + DCHECK(keyring_controller_); + keyring_controller_.set_disconnect_handler(base::BindOnce( + &WalletHandler::OnConnectionError, weak_ptr_factory_.GetWeakPtr())); + + if (!asset_ratio_controller_) { + auto pending = + brave_wallet::AssetRatioControllerFactory::GetInstance()->GetForContext( + profile_); + asset_ratio_controller_.Bind(std::move(pending)); + } + DCHECK(asset_ratio_controller_); + asset_ratio_controller_.set_disconnect_handler(base::BindOnce( + &WalletHandler::OnConnectionError, weak_ptr_factory_.GetWeakPtr())); + + if (!swap_controller_) { + auto pending = + brave_wallet::SwapControllerFactory::GetInstance()->GetForContext( + profile_); + swap_controller_.Bind(std::move(pending)); + } + DCHECK(swap_controller_); + swap_controller_.set_disconnect_handler(base::BindOnce( + &WalletHandler::OnConnectionError, weak_ptr_factory_.GetWeakPtr())); +} + +void WalletHandler::OnConnectionError() { + keyring_controller_.reset(); + asset_ratio_controller_.reset(); + swap_controller_.reset(); + EnsureConnected(); +} + void WalletHandler::GetWalletInfo(GetWalletInfoCallback callback) { - auto* profile = Profile::FromWebUI(web_ui_); + EnsureConnected(); + + keyring_controller_->GetDefaultKeyringInfo( + base::BindOnce(&WalletHandler::OnGetWalletInfo, + weak_ptr_factory_.GetWeakPtr(), std::move(callback))); +} + +void WalletHandler::OnGetWalletInfo( + GetWalletInfoCallback callback, + brave_wallet::mojom::KeyringInfoPtr keyring_info) { std::vector accounts; - auto* service = GetBraveWalletService(profile); - auto* keyring_controller = service->keyring_controller(); - auto* default_keyring = keyring_controller->GetDefaultKeyring(); - if (default_keyring) { - accounts = default_keyring->GetAccounts(); - } std::vector favorite_apps_copy( favorite_apps.size()); @@ -57,97 +87,49 @@ void WalletHandler::GetWalletInfo(GetWalletInfoCallback callback) { [](const brave_wallet::mojom::AppItemPtr& favorite_app) -> brave_wallet::mojom::AppItemPtr { return favorite_app.Clone(); }); std::move(callback).Run( - keyring_controller->IsDefaultKeyringCreated(), - keyring_controller->IsLocked(), std::move(favorite_apps_copy), - service->IsWalletBackedUp(), accounts, service->WalletAccountNames()); + keyring_info->is_default_keyring_created, keyring_info->is_locked, + std::move(favorite_apps_copy), keyring_info->is_backed_up, + keyring_info->accounts, keyring_info->account_names); } void WalletHandler::LockWallet() { - auto* profile = Profile::FromWebUI(web_ui_); - auto* keyring_controller = - GetBraveWalletService(profile)->keyring_controller(); - keyring_controller->Lock(); + EnsureConnected(); + keyring_controller_->Lock(); } void WalletHandler::UnlockWallet(const std::string& password, UnlockWalletCallback callback) { - auto* profile = Profile::FromWebUI(web_ui_); - auto* keyring_controller = - GetBraveWalletService(profile)->keyring_controller(); - bool result = keyring_controller->Unlock(password); - std::move(callback).Run(result); + EnsureConnected(); + keyring_controller_->Unlock(password, std::move(callback)); } void WalletHandler::GetAssetPrice(const std::string& asset, GetAssetPriceCallback callback) { - auto* profile = Profile::FromWebUI(web_ui_); - auto* asset_ratio_controller = - GetBraveWalletService(profile)->asset_ratio_controller(); - asset_ratio_controller->GetPrice( - asset, - base::BindOnce(&WalletHandler::OnGetPrice, weak_ptr_factory_.GetWeakPtr(), - std::move(callback))); -} - -void WalletHandler::OnGetPrice(GetAssetPriceCallback callback, - bool success, - const std::string& price) { - std::move(callback).Run(price); + EnsureConnected(); + asset_ratio_controller_->GetPrice(asset, std::move(callback)); } void WalletHandler::GetAssetPriceHistory( const std::string& asset, brave_wallet::mojom::AssetPriceTimeframe timeframe, GetAssetPriceHistoryCallback callback) { - auto* profile = Profile::FromWebUI(web_ui_); - auto* asset_ratio_controller = - GetBraveWalletService(profile)->asset_ratio_controller(); - asset_ratio_controller->GetPriceHistory( - asset, timeframe, - base::BindOnce(&WalletHandler::OnGetPriceHistory, - weak_ptr_factory_.GetWeakPtr(), std::move(callback))); -} - -void WalletHandler::OnGetPriceHistory( - GetAssetPriceHistoryCallback callback, - bool success, - std::vector values) { - std::move(callback).Run(std::move(values)); + EnsureConnected(); + asset_ratio_controller_->GetPriceHistory(asset, timeframe, + std::move(callback)); } void WalletHandler::GetPriceQuote(brave_wallet::mojom::SwapParamsPtr params, GetPriceQuoteCallback callback) { - auto* profile = Profile::FromWebUI(web_ui_); - auto* swap_controller = GetBraveWalletService(profile)->swap_controller(); - swap_controller->GetPriceQuote( - *params, - base::BindOnce(&WalletHandler::OnGetPriceQuote, - weak_ptr_factory_.GetWeakPtr(), std::move(callback))); -} - -void WalletHandler::OnGetPriceQuote( - GetPriceQuoteCallback callback, - bool success, - brave_wallet::mojom::SwapResponsePtr response) { - std::move(callback).Run(std::move(response)); + EnsureConnected(); + swap_controller_->GetPriceQuote(std::move(params), std::move(callback)); } void WalletHandler::GetTransactionPayload( brave_wallet::mojom::SwapParamsPtr params, GetTransactionPayloadCallback callback) { - auto* profile = Profile::FromWebUI(web_ui_); - auto* swap_controller = GetBraveWalletService(profile)->swap_controller(); - swap_controller->GetTransactionPayload( - *params, - base::BindOnce(&WalletHandler::OnGetTransactionPayload, - weak_ptr_factory_.GetWeakPtr(), std::move(callback))); -} - -void WalletHandler::OnGetTransactionPayload( - GetTransactionPayloadCallback callback, - bool success, - brave_wallet::mojom::SwapResponsePtr response) { - std::move(callback).Run(std::move(response)); + EnsureConnected(); + swap_controller_->GetTransactionPayload(std::move(params), + std::move(callback)); } void WalletHandler::AddFavoriteApp( @@ -165,20 +147,17 @@ void WalletHandler::RemoveFavoriteApp( } void WalletHandler::NotifyWalletBackupComplete() { - auto* profile = Profile::FromWebUI(web_ui_); - auto* service = GetBraveWalletService(profile); - service->NotifyWalletBackupComplete(); + EnsureConnected(); + keyring_controller_->NotifyWalletBackupComplete(); } void WalletHandler::SetInitialAccountNames( const std::vector& account_names) { - auto* profile = Profile::FromWebUI(web_ui_); - auto* service = GetBraveWalletService(profile); - service->SetInitialAccountNames(account_names); + EnsureConnected(); + keyring_controller_->SetInitialAccountNames(account_names); } void WalletHandler::AddNewAccountName(const std::string& account_name) { - auto* profile = Profile::FromWebUI(web_ui_); - auto* service = GetBraveWalletService(profile); - service->AddNewAccountName(account_name); + EnsureConnected(); + keyring_controller_->AddNewAccountName(account_name); } diff --git a/browser/ui/webui/brave_wallet/common_handler/wallet_handler.h b/browser/ui/webui/brave_wallet/common_handler/wallet_handler.h index a7f3db621a04..69207cc43b1a 100644 --- a/browser/ui/webui/brave_wallet/common_handler/wallet_handler.h +++ b/browser/ui/webui/brave_wallet/common_handler/wallet_handler.h @@ -11,24 +11,16 @@ #include "base/memory/weak_ptr.h" #include "brave/components/brave_wallet/common/brave_wallet.mojom.h" -#include "content/public/browser/web_contents_observer.h" #include "mojo/public/cpp/bindings/pending_receiver.h" -#include "mojo/public/cpp/bindings/pending_remote.h" -#include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/bindings/remote.h" -#include "ui/webui/mojo_web_ui_controller.h" -namespace content { -class WebUI; -} +class Profile; class WalletHandler : public brave_wallet::mojom::WalletHandler { public: WalletHandler( mojo::PendingReceiver receiver, - mojo::PendingRemote page, - content::WebUI* web_ui, - ui::MojoWebUIController* webui_controller); + Profile* profile); WalletHandler(const WalletHandler&) = delete; WalletHandler& operator=(const WalletHandler&) = delete; @@ -55,26 +47,22 @@ class WalletHandler : public brave_wallet::mojom::WalletHandler { void AddNewAccountName(const std::string& account_name) override; private: - void OnGetPrice(GetAssetPriceCallback callback, - bool success, - const std::string& price); - void OnGetPriceHistory( - GetAssetPriceHistoryCallback callback, - bool success, - std::vector values); - void OnGetPriceQuote(GetPriceQuoteCallback callback, - bool success, - brave_wallet::mojom::SwapResponsePtr response); - void OnGetTransactionPayload(GetTransactionPayloadCallback, - bool success, - brave_wallet::mojom::SwapResponsePtr response); + void EnsureConnected(); + void OnConnectionError(); + + void OnGetWalletInfo(GetWalletInfoCallback callback, + brave_wallet::mojom::KeyringInfoPtr keyring_info); + + mojo::Remote keyring_controller_; + mojo::Remote + asset_ratio_controller_; + mojo::Remote swap_controller_; // TODO(bbondy): This needs to be persisted in prefs std::vector favorite_apps; mojo::Receiver receiver_; - mojo::Remote page_; - content::WebUI* const web_ui_; + Profile* profile_; // NOT OWNED base::WeakPtrFactory weak_ptr_factory_; }; diff --git a/browser/ui/webui/brave_wallet/page_handler/BUILD.gn b/browser/ui/webui/brave_wallet/page_handler/BUILD.gn index 76f02b91e55c..5ca646374711 100644 --- a/browser/ui/webui/brave_wallet/page_handler/BUILD.gn +++ b/browser/ui/webui/brave_wallet/page_handler/BUILD.gn @@ -12,6 +12,7 @@ source_set("page_handler") { "//brave/browser/brave_wallet", "//brave/components/brave_wallet/browser", "//brave/components/brave_wallet/common:mojom", + "//chrome/browser/profiles:profile", "//content/public/browser", "//mojo/public/cpp/bindings", "//ui/webui:webui", diff --git a/browser/ui/webui/brave_wallet/page_handler/wallet_page_handler.cc b/browser/ui/webui/brave_wallet/page_handler/wallet_page_handler.cc index db6956ea7cbc..81df31adda3a 100644 --- a/browser/ui/webui/brave_wallet/page_handler/wallet_page_handler.cc +++ b/browser/ui/webui/brave_wallet/page_handler/wallet_page_handler.cc @@ -7,83 +7,57 @@ #include -#include "brave/browser/brave_wallet/brave_wallet_service_factory.h" -#include "brave/components/brave_wallet/browser/brave_wallet_service.h" +#include "brave/browser/brave_wallet/keyring_controller_factory.h" #include "brave/components/brave_wallet/browser/hd_keyring.h" #include "brave/components/brave_wallet/browser/keyring_controller.h" -#include "content/public/browser/web_contents.h" -#include "content/public/browser/web_ui.h" - -#include "ui/webui/mojo_bubble_web_ui_controller.h" - -namespace { - -brave_wallet::BraveWalletService* GetBraveWalletService( - content::BrowserContext* context) { - return brave_wallet::BraveWalletServiceFactory::GetInstance()->GetForContext( - context); -} - -} // namespace +#include "chrome/browser/profiles/profile.h" WalletPageHandler::WalletPageHandler( mojo::PendingReceiver receiver, - mojo::PendingRemote page, - content::WebUI* web_ui, - ui::MojoWebUIController* webui_controller) + Profile* profile) : receiver_(this, std::move(receiver)), - page_(std::move(page)), - web_ui_(web_ui) { - Observe(web_ui_->GetWebContents()); -} + profile_(profile), + weak_ptr_factory_(this) {} WalletPageHandler::~WalletPageHandler() = default; +void WalletPageHandler::EnsureConnected() { + if (!keyring_controller_) { + auto pending = + brave_wallet::KeyringControllerFactory::GetInstance()->GetForContext( + profile_); + keyring_controller_.Bind(std::move(pending)); + } + DCHECK(keyring_controller_); + keyring_controller_.set_disconnect_handler(base::BindOnce( + &WalletPageHandler::OnConnectionError, weak_ptr_factory_.GetWeakPtr())); +} + +void WalletPageHandler::OnConnectionError() { + keyring_controller_.reset(); + EnsureConnected(); +} + void WalletPageHandler::CreateWallet(const std::string& password, CreateWalletCallback callback) { - auto* browser_context = web_ui_->GetWebContents()->GetBrowserContext(); - auto* keyring_controller = - GetBraveWalletService(browser_context)->keyring_controller(); - auto* keyring = keyring_controller->CreateDefaultKeyring(password); - if (keyring) { - keyring->AddAccounts(); - } - std::move(callback).Run(keyring_controller->GetMnemonicForDefaultKeyring()); + EnsureConnected(); + keyring_controller_->CreateWallet(password, std::move(callback)); } void WalletPageHandler::AddAccountToWallet( AddAccountToWalletCallback callback) { - auto* browser_context = web_ui_->GetWebContents()->GetBrowserContext(); - auto* keyring_controller = - GetBraveWalletService(browser_context)->keyring_controller(); - auto* keyring = keyring_controller->GetDefaultKeyring(); - if (keyring) { - keyring->AddAccounts(); - } - std::move(callback).Run(keyring); + EnsureConnected(); + keyring_controller_->AddAccount(std::move(callback)); } void WalletPageHandler::GetRecoveryWords(GetRecoveryWordsCallback callback) { - auto* browser_context = web_ui_->GetWebContents()->GetBrowserContext(); - auto* keyring_controller = - GetBraveWalletService(browser_context)->keyring_controller(); - keyring_controller->GetMnemonicForDefaultKeyring(); - std::move(callback).Run(keyring_controller->GetMnemonicForDefaultKeyring()); + EnsureConnected(); + keyring_controller_->GetMnemonicForDefaultKeyring(std::move(callback)); } void WalletPageHandler::RestoreWallet(const std::string& mnemonic, const std::string& password, RestoreWalletCallback callback) { - auto* browser_context = web_ui_->GetWebContents()->GetBrowserContext(); - auto* keyring_controller = - GetBraveWalletService(browser_context)->keyring_controller(); - auto* keyring = keyring_controller->RestoreDefaultKeyring(mnemonic, password); - if (keyring) { - keyring->AddAccounts(); - } - std::move(callback).Run(keyring); -} - -void WalletPageHandler::OnVisibilityChanged(content::Visibility visibility) { - webui_hidden_ = visibility == content::Visibility::HIDDEN; + EnsureConnected(); + keyring_controller_->RestoreWallet(mnemonic, password, std::move(callback)); } diff --git a/browser/ui/webui/brave_wallet/page_handler/wallet_page_handler.h b/browser/ui/webui/brave_wallet/page_handler/wallet_page_handler.h index 01eb9241e87f..1dda0d60f311 100644 --- a/browser/ui/webui/brave_wallet/page_handler/wallet_page_handler.h +++ b/browser/ui/webui/brave_wallet/page_handler/wallet_page_handler.h @@ -8,47 +8,42 @@ #include +#include "base/memory/weak_ptr.h" #include "brave/components/brave_wallet/common/brave_wallet.mojom.h" -#include "content/public/browser/web_contents_observer.h" #include "mojo/public/cpp/bindings/pending_receiver.h" -#include "mojo/public/cpp/bindings/pending_remote.h" #include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/bindings/remote.h" -#include "ui/webui/mojo_web_ui_controller.h" -namespace content { -class WebUI; -} +class Profile; -class WalletPageHandler : public brave_wallet::mojom::PageHandler, - public content::WebContentsObserver { +class WalletPageHandler : public brave_wallet::mojom::PageHandler { public: WalletPageHandler( mojo::PendingReceiver receiver, - mojo::PendingRemote page, - content::WebUI* web_ui, - ui::MojoWebUIController* webui_controller); + Profile* profile); WalletPageHandler(const WalletPageHandler&) = delete; WalletPageHandler& operator=(const WalletPageHandler&) = delete; ~WalletPageHandler() override; - // content::WebContentsObserver: - void OnVisibilityChanged(content::Visibility visibility) override; - // brave_wallet::mojom::PageHandler: - void CreateWallet(const std::string& password, CreateWalletCallback) override; + void CreateWallet(const std::string& password, + CreateWalletCallback callback) override; void RestoreWallet(const std::string& mnemonic, const std::string& password, - RestoreWalletCallback) override; + RestoreWalletCallback callback) override; + void GetRecoveryWords(GetRecoveryWordsCallback callback) override; void AddAccountToWallet(AddAccountToWalletCallback) override; - void GetRecoveryWords(GetRecoveryWordsCallback) override; private: - bool webui_hidden_ = false; + void EnsureConnected(); + void OnConnectionError(); + mojo::Receiver receiver_; - mojo::Remote page_; - content::WebUI* const web_ui_; + mojo::Remote keyring_controller_; + + Profile* profile_; // NOT OWNED + base::WeakPtrFactory weak_ptr_factory_; }; #endif // BRAVE_BROWSER_UI_WEBUI_BRAVE_WALLET_PAGE_HANDLER_WALLET_PAGE_HANDLER_H_ diff --git a/browser/ui/webui/brave_wallet/panel_handler/wallet_panel_handler.cc b/browser/ui/webui/brave_wallet/panel_handler/wallet_panel_handler.cc index b8136220d127..44f8e57e6104 100644 --- a/browser/ui/webui/brave_wallet/panel_handler/wallet_panel_handler.cc +++ b/browser/ui/webui/brave_wallet/panel_handler/wallet_panel_handler.cc @@ -9,14 +9,9 @@ WalletPanelHandler::WalletPanelHandler( mojo::PendingReceiver receiver, - mojo::PendingRemote page, - content::WebUI* web_ui, ui::MojoBubbleWebUIController* webui_controller) : receiver_(this, std::move(receiver)), - page_(std::move(page)), - web_ui_(web_ui), webui_controller_(webui_controller) { - Observe(web_ui_->GetWebContents()); } WalletPanelHandler::~WalletPanelHandler() = default; @@ -34,7 +29,3 @@ void WalletPanelHandler::CloseUI() { embedder->CloseUI(); } } - -void WalletPanelHandler::OnVisibilityChanged(content::Visibility visibility) { - webui_hidden_ = visibility == content::Visibility::HIDDEN; -} diff --git a/browser/ui/webui/brave_wallet/panel_handler/wallet_panel_handler.h b/browser/ui/webui/brave_wallet/panel_handler/wallet_panel_handler.h index 4ddf09b922fa..dff0d402ac0c 100644 --- a/browser/ui/webui/brave_wallet/panel_handler/wallet_panel_handler.h +++ b/browser/ui/webui/brave_wallet/panel_handler/wallet_panel_handler.h @@ -9,42 +9,30 @@ #include #include "brave/components/brave_wallet/common/brave_wallet.mojom.h" -#include "content/public/browser/web_contents_observer.h" #include "mojo/public/cpp/bindings/pending_receiver.h" -#include "mojo/public/cpp/bindings/pending_remote.h" #include "mojo/public/cpp/bindings/receiver.h" -#include "mojo/public/cpp/bindings/remote.h" #include "ui/webui/mojo_bubble_web_ui_controller.h" namespace content { class WebUI; } -class WalletPanelHandler : public brave_wallet::mojom::PanelHandler, - public content::WebContentsObserver { +class WalletPanelHandler : public brave_wallet::mojom::PanelHandler { public: WalletPanelHandler( mojo::PendingReceiver receiver, - mojo::PendingRemote page, - content::WebUI* web_ui, ui::MojoBubbleWebUIController* webui_controller); WalletPanelHandler(const WalletPanelHandler&) = delete; WalletPanelHandler& operator=(const WalletPanelHandler&) = delete; ~WalletPanelHandler() override; - // content::WebContentsObserver: - void OnVisibilityChanged(content::Visibility visibility) override; - // brave_wallet::mojom::PanelHandler: void ShowUI() override; void CloseUI() override; private: - bool webui_hidden_ = false; mojo::Receiver receiver_; - mojo::Remote page_; - content::WebUI* const web_ui_; ui::MojoBubbleWebUIController* const webui_controller_; }; diff --git a/browser/ui/webui/brave_wallet/wallet_page_ui.cc b/browser/ui/webui/brave_wallet/wallet_page_ui.cc index 289c5f12bdbc..7346a5bb3b69 100644 --- a/browser/ui/webui/brave_wallet/wallet_page_ui.cc +++ b/browser/ui/webui/brave_wallet/wallet_page_ui.cc @@ -60,8 +60,10 @@ void WalletPageUI::CreatePageHandler( mojo::PendingReceiver page_receiver, mojo::PendingReceiver wallet_receiver) { DCHECK(page); - page_handler_ = std::make_unique( - std::move(page_receiver), std::move(page), web_ui(), this); - wallet_handler_ = std::make_unique( - std::move(wallet_receiver), std::move(page), web_ui(), this); + auto* profile = Profile::FromWebUI(web_ui()); + DCHECK(profile); + page_handler_ = + std::make_unique(std::move(page_receiver), profile); + wallet_handler_ = + std::make_unique(std::move(wallet_receiver), profile); } diff --git a/browser/ui/webui/brave_wallet/wallet_panel_ui.cc b/browser/ui/webui/brave_wallet/wallet_panel_ui.cc index a46c3edfcda0..7a160f722af2 100644 --- a/browser/ui/webui/brave_wallet/wallet_panel_ui.cc +++ b/browser/ui/webui/brave_wallet/wallet_panel_ui.cc @@ -58,8 +58,10 @@ void WalletPanelUI::CreatePanelHandler( mojo::PendingReceiver panel_receiver, mojo::PendingReceiver wallet_receiver) { DCHECK(page); - panel_handler_ = std::make_unique( - std::move(panel_receiver), std::move(page), web_ui(), this); - wallet_handler_ = std::make_unique( - std::move(wallet_receiver), std::move(page), web_ui(), this); + auto* profile = Profile::FromWebUI(web_ui()); + DCHECK(profile); + panel_handler_ = + std::make_unique(std::move(panel_receiver), this); + wallet_handler_ = + std::make_unique(std::move(wallet_receiver), profile); } diff --git a/chromium_src/ios/chrome/browser/browser_state/browser_state_keyed_service_factories.mm b/chromium_src/ios/chrome/browser/browser_state/browser_state_keyed_service_factories.mm index e18a1718f124..70720324f41d 100644 --- a/chromium_src/ios/chrome/browser/browser_state/browser_state_keyed_service_factories.mm +++ b/chromium_src/ios/chrome/browser/browser_state/browser_state_keyed_service_factories.mm @@ -30,9 +30,9 @@ #error "This file requires ARC support." #endif -#if BUILDFLAG(BRAVE_WALLET_ENABLED) -#include "brave/ios/browser/api/wallet/brave_wallet_service_factory.h" -#endif +// #if BUILDFLAG(BRAVE_WALLET_ENABLED) +// #include "brave/ios/browser/api/wallet/brave_wallet_service_factory.h" +// #endif void EnsureBrowserStateKeyedServiceFactoriesBuilt() { autofill::PersonalDataManagerFactory::GetInstance(); @@ -54,7 +54,7 @@ void EnsureBrowserStateKeyedServiceFactoriesBuilt() { ReadingListModelFactory::GetInstance(); SessionSyncServiceFactory::GetInstance(); SyncSetupServiceFactory::GetInstance(); -#if BUILDFLAG(BRAVE_WALLET_ENABLED) - BraveWalletServiceFactory::GetInstance(); -#endif + // #if BUILDFLAG(BRAVE_WALLET_ENABLED) + // BraveWalletServiceFactory::GetInstance(); + // #endif } diff --git a/chromium_src/ios/chrome/browser/prefs/BUILD.gn b/chromium_src/ios/chrome/browser/prefs/BUILD.gn index 96774c9e8379..aa1f98642bda 100644 --- a/chromium_src/ios/chrome/browser/prefs/BUILD.gn +++ b/chromium_src/ios/chrome/browser/prefs/BUILD.gn @@ -3,11 +3,6 @@ # 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/. -import("//brave/components/brave_wallet/common/buildflags/buildflags.gni") - group("prefs") { deps = [ "//brave/components/brave_sync:prefs" ] - if (brave_wallet_enabled) { - deps += [ "//brave/components/brave_wallet/browser" ] - } } diff --git a/chromium_src/ios/chrome/browser/prefs/browser_prefs.mm b/chromium_src/ios/chrome/browser/prefs/browser_prefs.mm index ad5932d004cc..c45a86b18731 100644 --- a/chromium_src/ios/chrome/browser/prefs/browser_prefs.mm +++ b/chromium_src/ios/chrome/browser/prefs/browser_prefs.mm @@ -4,17 +4,9 @@ * You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "brave/components/brave_sync/brave_sync_prefs.h" -#include "brave/components/brave_wallet/common/buildflags/buildflags.h" - -#if BUILDFLAG(BRAVE_WALLET_ENABLED) -#include "brave/components/brave_wallet/browser/brave_wallet_service.h" -#endif void BraveRegisterBrowserStatePrefs(PrefRegistrySimple* registry) { brave_sync::Prefs::RegisterProfilePrefs(registry); -#if BUILDFLAG(BRAVE_WALLET_ENABLED) - brave_wallet::BraveWalletService::RegisterProfilePrefs(registry); -#endif } #define BRAVE_REGISTER_BROWSER_STATE_PREFS BraveRegisterBrowserStatePrefs(registry); diff --git a/components/brave_wallet/browser/BUILD.gn b/components/brave_wallet/browser/BUILD.gn index e461999cd619..58fbaecb3af7 100644 --- a/components/brave_wallet/browser/BUILD.gn +++ b/components/brave_wallet/browser/BUILD.gn @@ -20,8 +20,6 @@ static_library("browser") { "brave_wallet_provider_events_observer.h", "brave_wallet_provider_impl.cc", "brave_wallet_provider_impl.h", - "brave_wallet_service.cc", - "brave_wallet_service.h", "brave_wallet_types.cc", "brave_wallet_types.h", "brave_wallet_utils.cc", @@ -80,6 +78,7 @@ static_library("browser") { "//brave/vendor/bip39wally-core-native:bip39wally-core", "//components/keyed_service/core", "//components/prefs", + "//components/sync_preferences", "//crypto", "//services/network/public/cpp", "//third_party/abseil-cpp:absl", diff --git a/components/brave_wallet/browser/asset_ratio_controller.cc b/components/brave_wallet/browser/asset_ratio_controller.cc index faa311de62ac..c99c40533c0e 100644 --- a/components/brave_wallet/browser/asset_ratio_controller.cc +++ b/components/brave_wallet/browser/asset_ratio_controller.cc @@ -51,6 +51,13 @@ AssetRatioController::AssetRatioController( AssetRatioController::~AssetRatioController() {} +mojo::PendingRemote +AssetRatioController::MakeRemote() { + mojo::PendingRemote remote; + receivers_.Add(this, remote.InitWithNewPipeAndPassReceiver()); + return remote; +} + void AssetRatioController::SetBaseURLForTest(const GURL& base_url_for_test) { base_url_for_test_ = base_url_for_test; } diff --git a/components/brave_wallet/browser/asset_ratio_controller.h b/components/brave_wallet/browser/asset_ratio_controller.h index ac923ff405a7..23aae63bbf63 100644 --- a/components/brave_wallet/browser/asset_ratio_controller.h +++ b/components/brave_wallet/browser/asset_ratio_controller.h @@ -17,6 +17,12 @@ #include "brave/components/brave_wallet/browser/asset_ratio_response_parser.h" #include "url/gurl.h" +#include "brave/components/brave_wallet/common/brave_wallet.mojom.h" +#include "components/keyed_service/core/keyed_service.h" +#include "mojo/public/cpp/bindings/pending_remote.h" +#include "mojo/public/cpp/bindings/receiver_set.h" +#include "mojo/public/cpp/bindings/remote.h" + namespace network { class SharedURLLoaderFactory; class SimpleURLLoader; @@ -24,23 +30,23 @@ class SimpleURLLoader; namespace brave_wallet { -class AssetRatioController { +class AssetRatioController : public KeyedService, + public mojom::AssetRatioController { public: AssetRatioController( scoped_refptr url_loader_factory); - ~AssetRatioController(); + ~AssetRatioController() override; + AssetRatioController(const AssetRatioController&) = delete; + AssetRatioController& operator=(const AssetRatioController&) = delete; - using GetPriceCallback = - base::OnceCallback; - void GetPrice(const std::string& asset, GetPriceCallback callback); + mojo::PendingRemote MakeRemote(); - using GetPriceHistoryCallback = base::OnceCallback values)>; + void GetPrice(const std::string& asset, GetPriceCallback callback) override; // The asset param is a string like: "bat" void GetPriceHistory(const std::string& asset, brave_wallet::mojom::AssetPriceTimeframe timeframe, - GetPriceHistoryCallback callback); + GetPriceHistoryCallback callback) override; + static GURL GetPriceURL(const std::string& asset); static GURL GetPriceHistoryURL( const std::string& asset, @@ -57,6 +63,8 @@ class AssetRatioController { const std::string& body, const std::map& headers); + mojo::ReceiverSet receivers_; + static GURL base_url_for_test_; api_request_helper::APIRequestHelper api_request_helper_; base::WeakPtrFactory weak_ptr_factory_; diff --git a/components/brave_wallet/browser/brave_wallet_provider_impl.cc b/components/brave_wallet/browser/brave_wallet_provider_impl.cc index 69a7e8e6380e..4463d6861416 100644 --- a/components/brave_wallet/browser/brave_wallet_provider_impl.cc +++ b/components/brave_wallet/browser/brave_wallet_provider_impl.cc @@ -8,33 +8,26 @@ #include #include "brave/components/brave_wallet/browser/brave_wallet_provider_delegate.h" -#include "brave/components/brave_wallet/browser/brave_wallet_service.h" #include "brave/components/brave_wallet/browser/eth_json_rpc_controller.h" namespace brave_wallet { BraveWalletProviderImpl::BraveWalletProviderImpl( - base::WeakPtr wallet_service, + EthJsonRpcController* rpc_controller, std::unique_ptr delegate) : delegate_(std::move(delegate)), - wallet_service_(wallet_service), - weak_factory_(this) {} + rpc_controller_(rpc_controller), + weak_factory_(this) { + DCHECK(rpc_controller); +} BraveWalletProviderImpl::~BraveWalletProviderImpl() { - if (!wallet_service_) - return; - - auto* rpc_controller = wallet_service_->rpc_controller(); - rpc_controller->RemoveObserver(this); + rpc_controller_->RemoveObserver(this); } void BraveWalletProviderImpl::Request(const std::string& json_payload, RequestCallback callback) { - if (!wallet_service_) - return; - - auto* rpc_controller = wallet_service_->rpc_controller(); - rpc_controller->Request( + rpc_controller_->Request( json_payload, base::BindOnce(&BraveWalletProviderImpl::OnResponse, weak_factory_.GetWeakPtr(), std::move(callback)), @@ -59,23 +52,15 @@ void BraveWalletProviderImpl::Enable() { } void BraveWalletProviderImpl::GetChainId(GetChainIdCallback callback) { - if (!wallet_service_) - return; - - auto* rpc_controller = wallet_service_->rpc_controller(); std::move(callback).Run(EthJsonRpcController::GetChainIDFromNetwork( - rpc_controller->GetNetwork())); + rpc_controller_->GetNetwork())); } void BraveWalletProviderImpl::Init( ::mojo::PendingRemote events_listener) { if (!events_listener_.is_bound()) { events_listener_.Bind(std::move(events_listener)); - if (!wallet_service_) - return; - - auto* rpc_controller = wallet_service_->rpc_controller(); - rpc_controller->AddObserver(this); + rpc_controller_->AddObserver(this); } } diff --git a/components/brave_wallet/browser/brave_wallet_provider_impl.h b/components/brave_wallet/browser/brave_wallet_provider_impl.h index 3345acdabeb6..68781533fa66 100644 --- a/components/brave_wallet/browser/brave_wallet_provider_impl.h +++ b/components/brave_wallet/browser/brave_wallet_provider_impl.h @@ -13,15 +13,13 @@ #include "base/memory/weak_ptr.h" #include "brave/components/brave_wallet/browser/brave_wallet_provider_events_observer.h" #include "brave/components/brave_wallet/common/brave_wallet.mojom.h" -#include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/pending_remote.h" -#include "mojo/public/cpp/bindings/receiver_set.h" #include "mojo/public/cpp/bindings/remote.h" namespace brave_wallet { -class BraveWalletService; class BraveWalletProviderDelegate; +class EthJsonRpcController; class BraveWalletProviderImpl final : public mojom::BraveWalletProvider, public BraveWalletProviderEventsObserver { @@ -29,7 +27,7 @@ class BraveWalletProviderImpl final : public mojom::BraveWalletProvider, BraveWalletProviderImpl(const BraveWalletProviderImpl&) = delete; BraveWalletProviderImpl& operator=(const BraveWalletProviderImpl&) = delete; BraveWalletProviderImpl( - base::WeakPtr wallet_service, + EthJsonRpcController* rpc_controller, std::unique_ptr delegate); ~BraveWalletProviderImpl() override; @@ -49,7 +47,7 @@ class BraveWalletProviderImpl final : public mojom::BraveWalletProvider, private: std::unique_ptr delegate_; mojo::Remote events_listener_; - base::WeakPtr wallet_service_; + EthJsonRpcController* rpc_controller_; // NOT OWNED base::WeakPtrFactory weak_factory_; }; diff --git a/components/brave_wallet/browser/brave_wallet_service.cc b/components/brave_wallet/browser/brave_wallet_service.cc deleted file mode 100644 index 4f7c59914c09..000000000000 --- a/components/brave_wallet/browser/brave_wallet_service.cc +++ /dev/null @@ -1,114 +0,0 @@ -/* Copyright (c) 2019 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 -#include - -#include "brave/components/brave_wallet/browser/asset_ratio_controller.h" -#include "brave/components/brave_wallet/browser/brave_wallet_constants.h" -#include "brave/components/brave_wallet/browser/brave_wallet_service.h" -#include "brave/components/brave_wallet/browser/brave_wallet_utils.h" -#include "brave/components/brave_wallet/browser/eth_json_rpc_controller.h" -#include "brave/components/brave_wallet/browser/eth_tx_controller.h" -#include "brave/components/brave_wallet/browser/keyring_controller.h" -#include "brave/components/brave_wallet/browser/pref_names.h" -#include "brave/components/brave_wallet/browser/swap_controller.h" -#include "components/prefs/pref_registry_simple.h" -#include "components/prefs/pref_service.h" -#include "components/prefs/scoped_user_pref_update.h" -#include "services/network/public/cpp/shared_url_loader_factory.h" - -namespace brave_wallet { - -BraveWalletService::BraveWalletService( - PrefService* prefs, - scoped_refptr url_loader_factory) - : prefs_(prefs) { - rpc_controller_ = std::make_unique( - brave_wallet::Network::kMainnet, url_loader_factory); - keyring_controller_ = - std::make_unique(prefs); - tx_controller_ = std::make_unique( - rpc_controller_.get(), keyring_controller_.get(), prefs); - asset_ratio_controller_ = - std::make_unique(url_loader_factory); - swap_controller_ = - std::make_unique(url_loader_factory); -} - -BraveWalletService::~BraveWalletService() {} - -void BraveWalletService::RegisterProfilePrefs(PrefRegistrySimple* registry) { - registry->RegisterIntegerPref( - kBraveWalletWeb3Provider, - static_cast(brave_wallet::IsNativeWalletEnabled() - ? brave_wallet::Web3ProviderTypes::BRAVE_WALLET - : brave_wallet::Web3ProviderTypes::ASK)); - registry->RegisterStringPref(kBraveWalletPasswordEncryptorSalt, ""); - registry->RegisterStringPref(kBraveWalletPasswordEncryptorNonce, ""); - registry->RegisterStringPref(kBraveWalletEncryptedMnemonic, ""); - registry->RegisterIntegerPref(kBraveWalletDefaultKeyringAccountNum, 0); - registry->RegisterDictionaryPref(kBraveWalletTransactions); - registry->RegisterBooleanPref(kShowWalletIconOnToolbar, true); - registry->RegisterBooleanPref(kBraveWalletBackupComplete, false); - registry->RegisterTimePref(kBraveWalletLastUnlockTime, base::Time()); - registry->RegisterListPref(kBraveWalletAccountNames); -} - -brave_wallet::EthJsonRpcController* BraveWalletService::rpc_controller() const { - return rpc_controller_.get(); -} - -brave_wallet::KeyringController* BraveWalletService::keyring_controller() - const { - return keyring_controller_.get(); -} -brave_wallet::EthTxController* BraveWalletService::tx_controller() const { - return tx_controller_.get(); -} - -brave_wallet::AssetRatioController* BraveWalletService::asset_ratio_controller() - const { - return asset_ratio_controller_.get(); -} - -brave_wallet::SwapController* BraveWalletService::swap_controller() const { - return swap_controller_.get(); -} - -std::vector BraveWalletService::WalletAccountNames() const { - std::vector account_names; - for (const auto& account_name_value : - prefs_->Get(kBraveWalletAccountNames)->GetList()) { - const std::string* account_name = account_name_value.GetIfString(); - DCHECK(account_name) << "account name type should be string"; - account_names.push_back(*account_name); - } - return account_names; -} - -void BraveWalletService::SetInitialAccountNames( - const std::vector& account_names) { - std::vector account_names_list; - for (const std::string& name : account_names) { - account_names_list.push_back(base::Value(name)); - } - prefs_->Set(kBraveWalletAccountNames, base::Value(account_names_list)); -} - -void BraveWalletService::AddNewAccountName(const std::string& account_name) { - ListPrefUpdate update(prefs_, kBraveWalletAccountNames); - update->Append(base::Value(account_name)); -} - -bool BraveWalletService::IsWalletBackedUp() const { - return prefs_->GetBoolean(kBraveWalletBackupComplete); -} - -void BraveWalletService::NotifyWalletBackupComplete() { - prefs_->SetBoolean(kBraveWalletBackupComplete, true); -} - -} // namespace brave_wallet diff --git a/components/brave_wallet/browser/brave_wallet_service.h b/components/brave_wallet/browser/brave_wallet_service.h deleted file mode 100644 index f8e426613cb8..000000000000 --- a/components/brave_wallet/browser/brave_wallet_service.h +++ /dev/null @@ -1,67 +0,0 @@ -/* Copyright (c) 2019 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/. */ - -#ifndef BRAVE_COMPONENTS_BRAVE_WALLET_BROWSER_BRAVE_WALLET_SERVICE_H_ -#define BRAVE_COMPONENTS_BRAVE_WALLET_BROWSER_BRAVE_WALLET_SERVICE_H_ - -#include -#include -#include - -#include "base/macros.h" -#include "base/memory/weak_ptr.h" -#include "components/keyed_service/core/keyed_service.h" - -class PrefService; -class PrefRegistrySimple; - -namespace network { -class SharedURLLoaderFactory; -} // namespace network - -namespace brave_wallet { - -class EthJsonRpcController; -class EthTxController; -class KeyringController; -class AssetRatioController; -class SwapController; - -class BraveWalletService : public KeyedService, - public base::SupportsWeakPtr { - public: - explicit BraveWalletService( - PrefService* prefs, - scoped_refptr url_loader_factory); - ~BraveWalletService() override; - - static void RegisterProfilePrefs(PrefRegistrySimple* registry); - - brave_wallet::EthJsonRpcController* rpc_controller() const; - brave_wallet::KeyringController* keyring_controller() const; - brave_wallet::EthTxController* tx_controller() const; - brave_wallet::AssetRatioController* asset_ratio_controller() const; - brave_wallet::SwapController* swap_controller() const; - - std::vector WalletAccountNames() const; - void SetInitialAccountNames(const std::vector& account_names); - void AddNewAccountName(const std::string& account_name); - bool IsWalletBackedUp() const; - void NotifyWalletBackupComplete(); - - private: - PrefService* prefs_; - std::unique_ptr rpc_controller_; - std::unique_ptr keyring_controller_; - std::unique_ptr tx_controller_; - std::unique_ptr asset_ratio_controller_; - std::unique_ptr swap_controller_; - - DISALLOW_COPY_AND_ASSIGN(BraveWalletService); -}; - -} // namespace brave_wallet - -#endif // BRAVE_COMPONENTS_BRAVE_WALLET_BROWSER_BRAVE_WALLET_SERVICE_H_ diff --git a/components/brave_wallet/browser/eth_json_rpc_controller.cc b/components/brave_wallet/browser/eth_json_rpc_controller.cc index cdecbcea04e4..685ca31930da 100644 --- a/components/brave_wallet/browser/eth_json_rpc_controller.cc +++ b/components/brave_wallet/browser/eth_json_rpc_controller.cc @@ -286,7 +286,7 @@ void EthJsonRpcController::OnGetERC20TokenBalance( std::move(callback).Run(true, result); } -bool EthJsonRpcController::EnsProxyReaderGetResolverAddress( +void EthJsonRpcController::EnsProxyReaderGetResolverAddress( const std::string& contract_address, const std::string& domain, UnstoppableDomainsProxyReaderGetManyCallback callback) { @@ -295,12 +295,11 @@ bool EthJsonRpcController::EnsProxyReaderGetResolverAddress( weak_ptr_factory_.GetWeakPtr(), std::move(callback), domain); std::string data; if (!ens::GetResolverAddress(domain, &data)) { - return false; + std::move(callback).Run(false, ""); } Request(eth_call("", contract_address, "", "", "", data, "latest"), std::move(internal_callback), true); - return true; } void EthJsonRpcController::OnEnsProxyReaderGetResolverAddress( @@ -363,7 +362,7 @@ void EthJsonRpcController::OnEnsProxyReaderResolveAddress( std::move(callback).Run(true, result); } -bool EthJsonRpcController::UnstoppableDomainsProxyReaderGetMany( +void EthJsonRpcController::UnstoppableDomainsProxyReaderGetMany( const std::string& contract_address, const std::string& domain, const std::vector& keys, @@ -373,12 +372,11 @@ bool EthJsonRpcController::UnstoppableDomainsProxyReaderGetMany( weak_ptr_factory_.GetWeakPtr(), std::move(callback)); std::string data; if (!unstoppable_domains::GetMany(keys, domain, &data)) { - return false; + std::move(callback).Run(false, ""); } Request(eth_call("", contract_address, "", "", "", data, "latest"), std::move(internal_callback), true); - return true; } void EthJsonRpcController::OnUnstoppableDomainsProxyReaderGetMany( diff --git a/components/brave_wallet/browser/eth_json_rpc_controller.h b/components/brave_wallet/browser/eth_json_rpc_controller.h index 9483c62c9717..710518177b8b 100644 --- a/components/brave_wallet/browser/eth_json_rpc_controller.h +++ b/components/brave_wallet/browser/eth_json_rpc_controller.h @@ -19,6 +19,7 @@ #include "brave/components/brave_wallet/browser/brave_wallet_constants.h" #include "brave/components/brave_wallet/browser/brave_wallet_provider_events_observer.h" #include "brave/components/brave_wallet/browser/brave_wallet_types.h" +#include "components/keyed_service/core/keyed_service.h" #include "url/gurl.h" namespace network { @@ -28,12 +29,12 @@ class SimpleURLLoader; namespace brave_wallet { -class EthJsonRpcController { +class EthJsonRpcController : public KeyedService { public: EthJsonRpcController( Network network, scoped_refptr url_loader_factory); - ~EthJsonRpcController(); + ~EthJsonRpcController() override; using URLRequestCallback = base::OnceCallback; - bool UnstoppableDomainsProxyReaderGetMany( + + // Call getMany function of ProxyReader contract from Unstoppable Domains. + void UnstoppableDomainsProxyReaderGetMany( const std::string& contract_address, const std::string& domain, const std::vector& keys, UnstoppableDomainsProxyReaderGetManyCallback callback); - bool EnsProxyReaderGetResolverAddress( + void EnsProxyReaderGetResolverAddress( const std::string& contract_address, const std::string& domain, UnstoppableDomainsProxyReaderGetManyCallback callback); diff --git a/components/brave_wallet/browser/eth_nonce_tracker_unittest.cc b/components/brave_wallet/browser/eth_nonce_tracker_unittest.cc index 5f494e291864..c00f984960cf 100644 --- a/components/brave_wallet/browser/eth_nonce_tracker_unittest.cc +++ b/components/brave_wallet/browser/eth_nonce_tracker_unittest.cc @@ -5,6 +5,9 @@ #include "brave/components/brave_wallet/browser/eth_nonce_tracker.h" +#include +#include + #include "base/bind.h" #include "base/test/bind.h" #include "brave/components/brave_wallet/browser/brave_wallet_constants.h" @@ -14,10 +17,11 @@ #include "brave/components/brave_wallet/browser/eth_json_rpc_controller.h" #include "brave/components/brave_wallet/browser/eth_transaction.h" #include "brave/components/brave_wallet/browser/eth_tx_state_manager.h" -#include "chrome/browser/profiles/profile_manager.h" +#include "chrome/browser/prefs/browser_prefs.h" #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile_manager.h" #include "components/prefs/pref_service.h" +#include "components/sync_preferences/testing_pref_service_syncable.h" #include "content/public/test/browser_task_environment.h" #include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h" #include "services/network/test/test_url_loader_factory.h" @@ -27,21 +31,22 @@ namespace brave_wallet { class EthNonceTrackerUnitTest : public testing::Test { public: - EthNonceTrackerUnitTest() - : testing_profile_manager_(TestingBrowserProcess::GetGlobal()) { + EthNonceTrackerUnitTest() { shared_url_loader_factory_ = base::MakeRefCounted( &url_loader_factory_); } void SetUp() override { - ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); - ASSERT_TRUE(testing_profile_manager_.SetUp(temp_dir_.GetPath())); + TestingProfile::Builder builder; + auto prefs = + std::make_unique(); + RegisterUserProfilePrefs(prefs->registry()); + builder.SetPrefService(std::move(prefs)); + profile_ = builder.Build(); } - PrefService* GetPrefs() { - return ProfileManager::GetActiveUserProfile()->GetPrefs(); - } + PrefService* GetPrefs() { return profile_->GetPrefs(); } network::SharedURLLoaderFactory* shared_url_loader_factory() { return url_loader_factory_.GetSafeWeakWrapper().get(); @@ -69,8 +74,7 @@ class EthNonceTrackerUnitTest : public testing::Test { network::TestURLLoaderFactory url_loader_factory_; scoped_refptr shared_url_loader_factory_; content::BrowserTaskEnvironment task_environment_; - TestingProfileManager testing_profile_manager_; - base::ScopedTempDir temp_dir_; + std::unique_ptr profile_; }; TEST_F(EthNonceTrackerUnitTest, GetNonce) { diff --git a/components/brave_wallet/browser/eth_pending_tx_tracker_unittest.cc b/components/brave_wallet/browser/eth_pending_tx_tracker_unittest.cc index b6ccfd3f608e..ce247a1fa425 100644 --- a/components/brave_wallet/browser/eth_pending_tx_tracker_unittest.cc +++ b/components/brave_wallet/browser/eth_pending_tx_tracker_unittest.cc @@ -5,6 +5,9 @@ #include "brave/components/brave_wallet/browser/eth_pending_tx_tracker.h" +#include +#include + #include "base/bind.h" #include "base/test/bind.h" #include "brave/components/brave_wallet/browser/brave_wallet_constants.h" @@ -14,10 +17,10 @@ #include "brave/components/brave_wallet/browser/eth_nonce_tracker.h" #include "brave/components/brave_wallet/browser/eth_transaction.h" #include "brave/components/brave_wallet/browser/eth_tx_state_manager.h" -#include "chrome/browser/profiles/profile_manager.h" -#include "chrome/test/base/testing_browser_process.h" -#include "chrome/test/base/testing_profile_manager.h" +#include "chrome/browser/prefs/browser_prefs.h" +#include "chrome/test/base/testing_profile.h" #include "components/prefs/pref_service.h" +#include "components/sync_preferences/testing_pref_service_syncable.h" #include "content/public/test/browser_task_environment.h" #include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h" #include "services/network/test/test_url_loader_factory.h" @@ -27,21 +30,22 @@ namespace brave_wallet { class EthPendingTxTrackerUnitTest : public testing::Test { public: - EthPendingTxTrackerUnitTest() - : testing_profile_manager_(TestingBrowserProcess::GetGlobal()) { + EthPendingTxTrackerUnitTest() { shared_url_loader_factory_ = base::MakeRefCounted( &url_loader_factory_); } void SetUp() override { - ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); - ASSERT_TRUE(testing_profile_manager_.SetUp(temp_dir_.GetPath())); + TestingProfile::Builder builder; + auto prefs = + std::make_unique(); + RegisterUserProfilePrefs(prefs->registry()); + builder.SetPrefService(std::move(prefs)); + profile_ = builder.Build(); } - PrefService* GetPrefs() { - return ProfileManager::GetActiveUserProfile()->GetPrefs(); - } + PrefService* GetPrefs() { return profile_->GetPrefs(); } network::SharedURLLoaderFactory* shared_url_loader_factory() { return url_loader_factory_.GetSafeWeakWrapper().get(); @@ -57,8 +61,7 @@ class EthPendingTxTrackerUnitTest : public testing::Test { network::TestURLLoaderFactory url_loader_factory_; scoped_refptr shared_url_loader_factory_; content::BrowserTaskEnvironment task_environment_; - TestingProfileManager testing_profile_manager_; - base::ScopedTempDir temp_dir_; + std::unique_ptr profile_; }; TEST_F(EthPendingTxTrackerUnitTest, IsNonceTaken) { diff --git a/components/brave_wallet/browser/eth_tx_controller.cc b/components/brave_wallet/browser/eth_tx_controller.cc index b5ddd88bd0e1..fdfc5e7c733c 100644 --- a/components/brave_wallet/browser/eth_tx_controller.cc +++ b/components/brave_wallet/browser/eth_tx_controller.cc @@ -9,7 +9,6 @@ #include "base/bind.h" #include "base/logging.h" -#include "brave/components/brave_wallet/browser/brave_wallet_service.h" #include "brave/components/brave_wallet/browser/eth_address.h" #include "brave/components/brave_wallet/browser/eth_json_rpc_controller.h" #include "brave/components/brave_wallet/browser/hd_keyring.h" @@ -24,7 +23,7 @@ EthTxController::EthTxController(EthJsonRpcController* rpc_controller, keyring_controller_(keyring_controller), tx_state_manager_(std::make_unique(prefs)), nonce_tracker_(std::make_unique(tx_state_manager_.get(), - rpc_controller)), + rpc_controller_)), pending_tx_tracker_( std::make_unique(tx_state_manager_.get(), rpc_controller_, diff --git a/components/brave_wallet/browser/eth_tx_controller.h b/components/brave_wallet/browser/eth_tx_controller.h index 8a21bef5d81f..55b7ab994559 100644 --- a/components/brave_wallet/browser/eth_tx_controller.h +++ b/components/brave_wallet/browser/eth_tx_controller.h @@ -35,7 +35,9 @@ class EthTxController { protected: ~Observer() override = default; }; - EthTxController(EthJsonRpcController*, KeyringController*, PrefService*); + explicit EthTxController(EthJsonRpcController* rpc_controller, + KeyringController* keyring_controller, + PrefService* prefs); ~EthTxController(); EthTxController(const EthTxController&) = delete; EthTxController operator=(const EthTxController&) = delete; @@ -58,9 +60,8 @@ class EthTxController { bool status, const std::string& tx_hash); - EthJsonRpcController* rpc_controller_; - KeyringController* keyring_controller_; - + EthJsonRpcController* rpc_controller_; // NOT OWNED + KeyringController* keyring_controller_; // NOT OWNED std::unique_ptr tx_state_manager_; std::unique_ptr nonce_tracker_; std::unique_ptr pending_tx_tracker_; diff --git a/components/brave_wallet/browser/keyring_controller.cc b/components/brave_wallet/browser/keyring_controller.cc index d66e1e339574..397fdb6479c4 100644 --- a/components/brave_wallet/browser/keyring_controller.cc +++ b/components/brave_wallet/browser/keyring_controller.cc @@ -5,12 +5,17 @@ #include "brave/components/brave_wallet/browser/keyring_controller.h" +#include + #include "base/base64.h" #include "base/logging.h" +#include "brave/components/brave_wallet/browser/brave_wallet_constants.h" #include "brave/components/brave_wallet/browser/brave_wallet_utils.h" #include "brave/components/brave_wallet/browser/hd_keyring.h" #include "brave/components/brave_wallet/browser/pref_names.h" #include "components/prefs/pref_service.h" +#include "components/prefs/scoped_user_pref_update.h" +#include "components/sync_preferences/pref_service_syncable.h" #include "crypto/random.h" namespace brave_wallet { @@ -34,6 +39,36 @@ KeyringController::~KeyringController() { default_keyring_->GetAccounts().size()); } +mojo::PendingRemote KeyringController::MakeRemote() { + mojo::PendingRemote remote; + receivers_.Add(this, remote.InitWithNewPipeAndPassReceiver()); + return remote; +} + +// static +void KeyringController::RegisterProfilePrefs( + user_prefs::PrefRegistrySyncable* registry) { + // TODO(bridiver) - move to brave/browser + registry->RegisterIntegerPref( + kBraveWalletWeb3Provider, + static_cast(brave_wallet::IsNativeWalletEnabled() + ? brave_wallet::Web3ProviderTypes::BRAVE_WALLET + : brave_wallet::Web3ProviderTypes::ASK)); + // TODO(bridiver) - move to brave/browser + registry->RegisterBooleanPref(kShowWalletIconOnToolbar, true); + + // TODO(bridiver) - move to EthTxControllerFactory + registry->RegisterDictionaryPref(kBraveWalletTransactions); + + registry->RegisterStringPref(kBraveWalletPasswordEncryptorSalt, ""); + registry->RegisterStringPref(kBraveWalletPasswordEncryptorNonce, ""); + registry->RegisterStringPref(kBraveWalletEncryptedMnemonic, ""); + registry->RegisterIntegerPref(kBraveWalletDefaultKeyringAccountNum, 0); + registry->RegisterBooleanPref(kBraveWalletBackupComplete, false); + registry->RegisterTimePref(kBraveWalletLastUnlockTime, base::Time()); + registry->RegisterListPref(kBraveWalletAccountNames); +} + HDKeyring* KeyringController::CreateDefaultKeyring( const std::string& password) { if (!CreateEncryptor(password)) @@ -53,7 +88,7 @@ HDKeyring* KeyringController::ResumeDefaultKeyring( return nullptr; } - const std::string mnemonic = GetMnemonicForDefaultKeyring(); + const std::string mnemonic = GetMnemonicForDefaultKeyringImpl(); if (mnemonic.empty() || !CreateDefaultKeyringInternal(mnemonic)) { return nullptr; } @@ -82,7 +117,44 @@ HDKeyring* KeyringController::RestoreDefaultKeyring( return default_keyring_.get(); } -std::string KeyringController::GetMnemonicForDefaultKeyring() { +void KeyringController::GetDefaultKeyringInfo( + GetDefaultKeyringInfoCallback callback) { + mojom::KeyringInfoPtr keyring = mojom::KeyringInfo::New(); + keyring->is_default_keyring_created = IsDefaultKeyringCreated(); + keyring->is_locked = IsLocked(); + keyring->is_backed_up = prefs_->GetBoolean(kBraveWalletBackupComplete); + if (default_keyring_) { + keyring->accounts = default_keyring_->GetAccounts(); + keyring->account_names = GetAccountNames(); + } + std::move(callback).Run(std::move(keyring)); +} + +void KeyringController::GetMnemonicForDefaultKeyring( + GetMnemonicForDefaultKeyringCallback callback) { + std::move(callback).Run(GetMnemonicForDefaultKeyringImpl()); +} + +void KeyringController::CreateWallet(const std::string& password, + CreateWalletCallback callback) { + auto* keyring = CreateDefaultKeyring(password); + if (keyring) + keyring->AddAccounts(); + + std::move(callback).Run(GetMnemonicForDefaultKeyringImpl()); +} + +void KeyringController::RestoreWallet(const std::string& mnemonic, + const std::string& password, + RestoreWalletCallback callback) { + auto* keyring = RestoreDefaultKeyring(mnemonic, password); + if (keyring) + keyring->AddAccounts(); + + std::move(callback).Run(keyring); +} + +const std::string KeyringController::GetMnemonicForDefaultKeyringImpl() { if (IsLocked()) { LOG(ERROR) << __func__ << ": Must Unlock controller first"; return std::string(); @@ -100,6 +172,47 @@ std::string KeyringController::GetMnemonicForDefaultKeyring() { return std::string(mnemonic.begin(), mnemonic.end()); } +void KeyringController::AddAccount(AddAccountCallback callback) { + auto* keyring = GetDefaultKeyring(); + if (keyring) + keyring->AddAccounts(); + + std::move(callback).Run(keyring); +} + +void KeyringController::IsWalletBackedUp(IsWalletBackedUpCallback callback) { + std::move(callback).Run(prefs_->GetBoolean(kBraveWalletBackupComplete)); +} + +void KeyringController::NotifyWalletBackupComplete() { + prefs_->SetBoolean(kBraveWalletBackupComplete, true); +} + +std::vector KeyringController::GetAccountNames() const { + std::vector account_names; + for (const auto& account_name_value : + prefs_->Get(kBraveWalletAccountNames)->GetList()) { + const std::string* account_name = account_name_value.GetIfString(); + DCHECK(account_name) << "account name type should be string"; + account_names.push_back(*account_name); + } + return account_names; +} + +void KeyringController::SetInitialAccountNames( + const std::vector& account_names) { + std::vector account_names_list; + for (const std::string& name : account_names) { + account_names_list.push_back(base::Value(name)); + } + prefs_->Set(kBraveWalletAccountNames, base::Value(account_names_list)); +} + +void KeyringController::AddNewAccountName(const std::string& account_name) { + ListPrefUpdate update(prefs_, kBraveWalletAccountNames); + update->Append(base::Value(account_name)); +} + HDKeyring* KeyringController::GetDefaultKeyring() { if (IsLocked()) { LOG(ERROR) << __func__ << ": Must Unlock controller first"; @@ -124,14 +237,16 @@ void KeyringController::Lock() { encryptor_.reset(); } -bool KeyringController::Unlock(const std::string& password) { +void KeyringController::Unlock(const std::string& password, + UnlockCallback callback) { if (!ResumeDefaultKeyring(password)) { encryptor_.reset(); - return false; + std::move(callback).Run(false); + return; } UpdateLastUnlockPref(prefs_); - return true; + std::move(callback).Run(true); } void KeyringController::Reset() { diff --git a/components/brave_wallet/browser/keyring_controller.h b/components/brave_wallet/browser/keyring_controller.h index c171b77283e0..a7eab853e7b5 100644 --- a/components/brave_wallet/browser/keyring_controller.h +++ b/components/brave_wallet/browser/keyring_controller.h @@ -12,9 +12,17 @@ #include "base/gtest_prod_util.h" #include "brave/components/brave_wallet/browser/password_encryptor.h" +#include "brave/components/brave_wallet/common/brave_wallet.mojom.h" +#include "components/keyed_service/core/keyed_service.h" +#include "mojo/public/cpp/bindings/pending_remote.h" +#include "mojo/public/cpp/bindings/receiver_set.h" class PrefService; +namespace user_prefs { +class PrefRegistrySyncable; +} + namespace brave_wallet { class HDKeyring; @@ -30,10 +38,14 @@ FORWARD_DECLARE_TEST(KeyringControllerUnitTest, LockAndUnlock); FORWARD_DECLARE_TEST(KeyringControllerUnitTest, Reset); // This class is not thread-safe and should have single owner -class KeyringController { +class KeyringController : public KeyedService, public mojom::KeyringController { public: explicit KeyringController(PrefService* prefs); - ~KeyringController(); + ~KeyringController() override; + + static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* prefs); + + mojo::PendingRemote MakeRemote(); // Currently only support one default keyring, `CreateDefaultKeyring` and // `RestoreDefaultKeyring` will overwrite existing one if success @@ -41,23 +53,39 @@ class KeyringController { // Restore default keyring from backup seed phrase HDKeyring* RestoreDefaultKeyring(const std::string& mnemonic, const std::string& password); + + // mojom::KeyringController // Must unlock before using this API otherwise it will return empty string - std::string GetMnemonicForDefaultKeyring(); + void GetMnemonicForDefaultKeyring( + GetMnemonicForDefaultKeyringCallback callback) override; + void CreateWallet(const std::string& password, + CreateWalletCallback callback) override; + void RestoreWallet(const std::string& mnemonic, + const std::string& password, + RestoreWalletCallback callback) override; + void Unlock(const std::string& password, UnlockCallback callback) override; + void Lock() override; + void AddAccount(AddAccountCallback callback) override; + void IsWalletBackedUp(IsWalletBackedUpCallback callback) override; + void NotifyWalletBackupComplete() override; + void SetInitialAccountNames( + const std::vector& account_names) override; + void AddNewAccountName(const std::string& account_name) override; + void GetDefaultKeyringInfo(GetDefaultKeyringInfoCallback callback) override; + void Reset() override; + // Must unlock before using this API otherwise it will return nullptr HDKeyring* GetDefaultKeyring(); bool IsDefaultKeyringCreated(); bool IsLocked() const; - void Lock(); - bool Unlock(const std::string& password); + // bool Unlock(const std::string& password); /* TODO(darkdh): For other keyrings support void DeleteKeyring(size_t index); HDKeyring* GetKeyring(size_t index); */ - void Reset(); - private: FRIEND_TEST_ALL_PREFIXES(KeyringControllerUnitTest, GetPrefsInBytes); FRIEND_TEST_ALL_PREFIXES(KeyringControllerUnitTest, SetPrefsInBytes); @@ -70,6 +98,10 @@ class KeyringController { FRIEND_TEST_ALL_PREFIXES(KeyringControllerUnitTest, LockAndUnlock); FRIEND_TEST_ALL_PREFIXES(KeyringControllerUnitTest, Reset); + std::vector GetAccountNames() const; + + const std::string GetMnemonicForDefaultKeyringImpl(); + bool GetPrefsInBytes(const std::string& path, std::vector* bytes); void SetPrefsInBytes(const std::string& path, base::span bytes); @@ -87,6 +119,8 @@ class KeyringController { PrefService* prefs_; + mojo::ReceiverSet receivers_; + KeyringController(const KeyringController&) = delete; KeyringController& operator=(const KeyringController&) = delete; }; diff --git a/components/brave_wallet/browser/keyring_controller_unittest.cc b/components/brave_wallet/browser/keyring_controller_unittest.cc index e700e96624bc..e4a9422dcb11 100644 --- a/components/brave_wallet/browser/keyring_controller_unittest.cc +++ b/components/brave_wallet/browser/keyring_controller_unittest.cc @@ -5,12 +5,16 @@ #include "brave/components/brave_wallet/browser/keyring_controller.h" +#include + #include "base/base64.h" #include "brave/components/brave_wallet/browser/hd_keyring.h" #include "brave/components/brave_wallet/browser/pref_names.h" -#include "chrome/browser/profiles/profile_manager.h" +#include "chrome/browser/prefs/browser_prefs.h" #include "chrome/test/base/testing_browser_process.h" -#include "chrome/test/base/testing_profile_manager.h" +#include "chrome/test/base/testing_profile.h" +#include "components/prefs/pref_service.h" +#include "components/sync_preferences/testing_pref_service_syncable.h" #include "content/public/test/browser_task_environment.h" #include "testing/gtest/include/gtest/gtest.h" @@ -18,24 +22,32 @@ namespace brave_wallet { class KeyringControllerUnitTest : public testing::Test { public: - KeyringControllerUnitTest() - : testing_profile_manager_(TestingBrowserProcess::GetGlobal()) {} + KeyringControllerUnitTest() {} ~KeyringControllerUnitTest() override {} + void GetBooleanCallback(bool value) { bool_value_ = value; } + void GetStringCallback(const std::string& value) { string_value_ = value; } + protected: void SetUp() override { - ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); - ASSERT_TRUE(testing_profile_manager_.SetUp(temp_dir_.GetPath())); + TestingProfile::Builder builder; + auto prefs = + std::make_unique(); + RegisterUserProfilePrefs(prefs->registry()); + builder.SetPrefService(std::move(prefs)); + profile_ = builder.Build(); } - PrefService* GetPrefs() { - return ProfileManager::GetActiveUserProfile()->GetPrefs(); - } + PrefService* GetPrefs() { return profile_->GetPrefs(); } + + bool bool_value() { return bool_value_; } + const std::string string_value() { return string_value_; } private: content::BrowserTaskEnvironment task_environment_; - TestingProfileManager testing_profile_manager_; - base::ScopedTempDir temp_dir_; + std::unique_ptr profile_; + bool bool_value_; + std::string string_value_; }; TEST_F(KeyringControllerUnitTest, GetPrefsInBytes) { @@ -277,20 +289,33 @@ TEST_F(KeyringControllerUnitTest, UnlockResumesDefaultKeyring) { { // KeyringController is now destructed, simlulating relaunch KeyringController controller(GetPrefs()); - ASSERT_TRUE(controller.Unlock("brave")); + controller.Unlock( + "brave", base::BindOnce(&KeyringControllerUnitTest::GetBooleanCallback, + base::Unretained(this))); + base::RunLoop().RunUntilIdle(); + ASSERT_EQ(true, bool_value()); + ASSERT_FALSE(controller.IsLocked()); + HDKeyring* keyring = controller.GetDefaultKeyring(); EXPECT_EQ(GetPrefs()->GetString(kBraveWalletPasswordEncryptorSalt), salt); EXPECT_EQ(GetPrefs()->GetString(kBraveWalletPasswordEncryptorNonce), nonce); EXPECT_EQ(GetPrefs()->GetString(kBraveWalletEncryptedMnemonic), mnemonic); - ASSERT_NE(keyring, nullptr); - EXPECT_EQ(keyring->GetAccounts().size(), 2u); + ASSERT_NE(nullptr, keyring); + EXPECT_EQ(2u, keyring->GetAccounts().size()); } { KeyringController controller(GetPrefs()); // wrong password - ASSERT_FALSE(controller.Unlock("brave123")); + controller.Unlock( + "brave123", + base::BindOnce(&KeyringControllerUnitTest::GetBooleanCallback, + base::Unretained(this))); + ASSERT_TRUE(controller.IsLocked()); // empty password - ASSERT_FALSE(controller.Unlock("")); + controller.Unlock( + "", base::BindOnce(&KeyringControllerUnitTest::GetBooleanCallback, + base::Unretained(this))); + ASSERT_TRUE(controller.IsLocked()); } } @@ -302,21 +327,43 @@ TEST_F(KeyringControllerUnitTest, GetMnemonicForDefaultKeyring) { ASSERT_TRUE(controller.CreateEncryptor("brave")); // no pref exists yet - EXPECT_TRUE(controller.GetMnemonicForDefaultKeyring().empty()); + controller.GetMnemonicForDefaultKeyring(base::BindOnce( + &KeyringControllerUnitTest::GetStringCallback, base::Unretained(this))); + base::RunLoop().RunUntilIdle(); + EXPECT_TRUE(string_value().empty()); ASSERT_TRUE(controller.CreateDefaultKeyringInternal(mnemonic)); - EXPECT_EQ(controller.GetMnemonicForDefaultKeyring(), mnemonic); + controller.GetMnemonicForDefaultKeyring(base::BindOnce( + &KeyringControllerUnitTest::GetStringCallback, base::Unretained(this))); + base::RunLoop().RunUntilIdle(); + EXPECT_EQ(string_value(), mnemonic); // Lock controller controller.Lock(); - EXPECT_TRUE(controller.GetMnemonicForDefaultKeyring().empty()); + EXPECT_TRUE(controller.IsLocked()); + controller.GetMnemonicForDefaultKeyring(base::BindOnce( + &KeyringControllerUnitTest::GetStringCallback, base::Unretained(this))); + base::RunLoop().RunUntilIdle(); + EXPECT_TRUE(string_value().empty()); // unlock with wrong password - EXPECT_FALSE(controller.Unlock("brave123")); - EXPECT_TRUE(controller.GetMnemonicForDefaultKeyring().empty()); - - EXPECT_TRUE(controller.Unlock("brave")); - EXPECT_EQ(controller.GetMnemonicForDefaultKeyring(), mnemonic); + controller.Unlock( + "brave123", base::BindOnce(&KeyringControllerUnitTest::GetBooleanCallback, + base::Unretained(this))); + EXPECT_TRUE(controller.IsLocked()); + controller.GetMnemonicForDefaultKeyring(base::BindOnce( + &KeyringControllerUnitTest::GetStringCallback, base::Unretained(this))); + base::RunLoop().RunUntilIdle(); + EXPECT_TRUE(string_value().empty()); + + controller.Unlock( + "brave", base::BindOnce(&KeyringControllerUnitTest::GetBooleanCallback, + base::Unretained(this))); + EXPECT_FALSE(controller.IsLocked()); + controller.GetMnemonicForDefaultKeyring(base::BindOnce( + &KeyringControllerUnitTest::GetStringCallback, base::Unretained(this))); + base::RunLoop().RunUntilIdle(); + EXPECT_EQ(string_value(), mnemonic); } TEST_F(KeyringControllerUnitTest, GetDefaultKeyring) { @@ -331,7 +378,10 @@ TEST_F(KeyringControllerUnitTest, GetDefaultKeyring) { controller.Lock(); EXPECT_EQ(controller.GetDefaultKeyring(), nullptr); - EXPECT_TRUE(controller.Unlock("brave")); + controller.Unlock( + "brave", base::BindOnce(&KeyringControllerUnitTest::GetBooleanCallback, + base::Unretained(this))); + EXPECT_FALSE(controller.IsLocked()); ASSERT_NE(controller.GetDefaultKeyring(), nullptr); EXPECT_EQ(controller.GetDefaultKeyring()->GetAddress(0), address); } @@ -361,10 +411,14 @@ TEST_F(KeyringControllerUnitTest, LockAndUnlock) { EXPECT_EQ(GetPrefs()->GetInteger(kBraveWalletDefaultKeyringAccountNum), 1); EXPECT_TRUE(controller.default_keyring_->empty()); - EXPECT_FALSE(controller.Unlock("abc")); + controller.Unlock( + "abc", base::BindOnce(&KeyringControllerUnitTest::GetBooleanCallback, + base::Unretained(this))); EXPECT_TRUE(controller.IsLocked()); - EXPECT_TRUE(controller.Unlock("brave")); + controller.Unlock( + "brave", base::BindOnce(&KeyringControllerUnitTest::GetBooleanCallback, + base::Unretained(this))); EXPECT_FALSE(controller.IsLocked()); controller.default_keyring_->AddAccounts(1); @@ -374,7 +428,10 @@ TEST_F(KeyringControllerUnitTest, LockAndUnlock) { EXPECT_TRUE(controller.default_keyring_->empty()); // Simulate unlock shutdown - EXPECT_TRUE(controller.Unlock("brave")); + controller.Unlock( + "brave", base::BindOnce(&KeyringControllerUnitTest::GetBooleanCallback, + base::Unretained(this))); + EXPECT_FALSE(controller.IsLocked()); controller.default_keyring_->AddAccounts(1); } EXPECT_EQ(GetPrefs()->GetInteger(kBraveWalletDefaultKeyringAccountNum), 3); diff --git a/components/brave_wallet/browser/swap_controller.cc b/components/brave_wallet/browser/swap_controller.cc index eff34d9105c1..f3ada3f099c6 100644 --- a/components/brave_wallet/browser/swap_controller.cc +++ b/components/brave_wallet/browser/swap_controller.cc @@ -79,34 +79,40 @@ SwapController::SwapController( SwapController::~SwapController() {} +mojo::PendingRemote SwapController::MakeRemote() { + mojo::PendingRemote remote; + receivers_.Add(this, remote.InitWithNewPipeAndPassReceiver()); + return remote; +} + void SwapController::SetBaseURLForTest(const GURL& base_url_for_test) { base_url_for_test_ = base_url_for_test; } // static -GURL SwapController::GetPriceQuoteURL(const mojom::SwapParams& swap_params) { +GURL SwapController::GetPriceQuoteURL(mojom::SwapParamsPtr swap_params) { std::string spec = base::StringPrintf( "%sswap/v1/price", base_url_for_test_.is_empty() ? kSwapBaseURL : base_url_for_test_.spec().c_str()); GURL url(spec); - url = AppendSwapParams(url, swap_params); + url = AppendSwapParams(url, *swap_params); return url; } // static GURL SwapController::GetTransactionPayloadURL( - const mojom::SwapParams& swap_params) { + mojom::SwapParamsPtr swap_params) { std::string spec = base::StringPrintf( "%sswap/v1/quote", base_url_for_test_.is_empty() ? kSwapBaseURL : base_url_for_test_.spec().c_str()); GURL url(spec); - url = AppendSwapParams(url, swap_params); + url = AppendSwapParams(url, *swap_params); return url; } -void SwapController::GetPriceQuote(const mojom::SwapParams& swap_params, +void SwapController::GetPriceQuote(mojom::SwapParamsPtr swap_params, GetPriceQuoteCallback callback) { auto internal_callback = base::BindOnce(&SwapController::OnGetPriceQuote, @@ -134,7 +140,7 @@ void SwapController::OnGetPriceQuote( } void SwapController::GetTransactionPayload( - const mojom::SwapParams& swap_params, + mojom::SwapParamsPtr swap_params, GetTransactionPayloadCallback callback) { auto internal_callback = base::BindOnce(&SwapController::OnGetTransactionPayload, diff --git a/components/brave_wallet/browser/swap_controller.h b/components/brave_wallet/browser/swap_controller.h index 920a696e005b..0bf1030ae550 100644 --- a/components/brave_wallet/browser/swap_controller.h +++ b/components/brave_wallet/browser/swap_controller.h @@ -17,6 +17,12 @@ #include "brave/components/brave_wallet/browser/asset_ratio_response_parser.h" #include "url/gurl.h" +#include "brave/components/brave_wallet/common/brave_wallet.mojom.h" +#include "components/keyed_service/core/keyed_service.h" +#include "mojo/public/cpp/bindings/pending_remote.h" +#include "mojo/public/cpp/bindings/receiver_set.h" +#include "mojo/public/cpp/bindings/remote.h" + namespace network { class SharedURLLoaderFactory; class SimpleURLLoader; @@ -24,27 +30,25 @@ class SimpleURLLoader; namespace brave_wallet { -class SwapController { +class SwapController : public KeyedService, public mojom::SwapController { public: SwapController( scoped_refptr url_loader_factory); - ~SwapController(); - - using GetPriceQuoteCallback = - base::OnceCallback; - using GetTransactionPayloadCallback = - base::OnceCallback; + ~SwapController() override; + SwapController(const SwapController&) = delete; + SwapController& operator=(const SwapController&) = delete; + + mojo::PendingRemote MakeRemote(); + // Obtians a quote for the specified asset - void GetPriceQuote(const mojom::SwapParams& swap_params, - GetPriceQuoteCallback callback); + void GetPriceQuote(mojom::SwapParamsPtr swap_params, + GetPriceQuoteCallback callback) override; // Obtains the transaction payload to be signed. - void GetTransactionPayload(const mojom::SwapParams& swap_params, - GetTransactionPayloadCallback callback); + void GetTransactionPayload(mojom::SwapParamsPtr swap_params, + GetTransactionPayloadCallback callback) override; - static GURL GetPriceQuoteURL(const mojom::SwapParams& swap_params); - static GURL GetTransactionPayloadURL(const mojom::SwapParams& swap_params); + static GURL GetPriceQuoteURL(const mojom::SwapParamsPtr swap_params); + static GURL GetTransactionPayloadURL(mojom::SwapParamsPtr swap_params); static void SetBaseURLForTest(const GURL& base_url_for_test); private: @@ -60,6 +64,9 @@ class SwapController { static GURL base_url_for_test_; api_request_helper::APIRequestHelper api_request_helper_; + + mojo::ReceiverSet receivers_; + base::WeakPtrFactory weak_ptr_factory_; }; diff --git a/components/brave_wallet/common/brave_wallet.mojom b/components/brave_wallet/common/brave_wallet.mojom index acf1c5821876..daeed67d310c 100644 --- a/components/brave_wallet/common/brave_wallet.mojom +++ b/components/brave_wallet/common/brave_wallet.mojom @@ -108,6 +108,14 @@ struct SwapResponse { // Note we could also expose "sources" later }; +struct KeyringInfo { + bool is_default_keyring_created; + bool is_locked; + bool is_backed_up; + array accounts; + array account_names; +}; + // Browser-side handler for common panel / page things interface WalletHandler { GetWalletInfo() => (bool isWalletCreated, bool isWalletLocked, @@ -116,10 +124,12 @@ interface WalletHandler { array walletAccountNames); LockWallet(); UnlockWallet(string password) => (bool isWalletUnlocked); - GetAssetPrice(string asset) => (string price); - GetAssetPriceHistory(string asset, AssetPriceTimeframe timeframe) => (array values); - GetPriceQuote(SwapParams params) => (SwapResponse response); - GetTransactionPayload(SwapParams params) => (SwapResponse response); + GetAssetPrice(string asset) => (bool success, string price); + GetAssetPriceHistory(string asset, AssetPriceTimeframe timeframe) => + (bool success, array values); + GetPriceQuote(SwapParams params) => (bool success, SwapResponse response); + GetTransactionPayload(SwapParams params) => + (bool success, SwapResponse response); AddFavoriteApp(AppItem appItem); RemoveFavoriteApp(AppItem appItem); SetInitialAccountNames(array accountNames); @@ -130,3 +140,35 @@ interface WalletHandler { // WebUI-side handler for requests from the browser. interface Page { }; + +interface KeyringController { + CreateWallet(string password) => (string mnemonic); + GetMnemonicForDefaultKeyring() => (string mnemonic); + RestoreWallet(string mnemonic, string password) => (bool isValidMnemonic); + Lock(); + Unlock(string password) => (bool success); + AddAccount() => (bool success); + IsWalletBackedUp() => (bool backed_up); + NotifyWalletBackupComplete(); + SetInitialAccountNames(array accountNames); + AddNewAccountName(string accountName); + GetDefaultKeyringInfo() => (KeyringInfo keyring); + Reset(); +}; + +interface AssetRatioController { + GetPrice(string asset) => (bool success, string price); + GetPriceHistory(string asset, AssetPriceTimeframe timeframe) => + (bool success, array values); +}; + +interface SwapController { + GetPriceQuote(SwapParams params) => + (bool success, SwapResponse response); + GetTransactionPayload(SwapParams params) => + (bool success, SwapResponse response); +}; + +interface EthJsonRpcController { + +}; diff --git a/components/brave_wallet_ui/constants/types.ts b/components/brave_wallet_ui/constants/types.ts index 85334107b479..072ef5179284 100644 --- a/components/brave_wallet_ui/constants/types.ts +++ b/components/brave_wallet_ui/constants/types.ts @@ -243,7 +243,13 @@ export interface SwapResponse { buyTokenToEthRate: string } +export interface SwapResponseReturnInfo { + success: boolean, + response: SwapResponse +} + export interface GetAssetPriceReturnInfo { + success: boolean, price: string } @@ -253,6 +259,7 @@ export interface GetAssetPriceHistoryReturnInfo { } export interface GetAssetPriceHistoryReturnObjectInfo { + success: boolean, values: GetAssetPriceHistoryReturnInfo[] } @@ -276,8 +283,8 @@ export interface WalletAPIHandler { setInitialAccountNames: (accountNames: string[]) => Promise addNewAccountName: (accountName: string) => Promise restoreWallet: (mnemonic: string, password: string) => Promise - getPriceQuote: (swapParams: SwapParams) => Promise - getTransactionPayload: (swapParams: SwapParams) => Promise + getPriceQuote: (swapParams: SwapParams) => Promise + getTransactionPayload: (swapParams: SwapParams) => Promise } export interface RecoveryObject { diff --git a/ios/BUILD.gn b/ios/BUILD.gn index 67ce726bcc38..14c29c9a2892 100644 --- a/ios/BUILD.gn +++ b/ios/BUILD.gn @@ -32,7 +32,8 @@ brave_core_public_headers = [ "//brave/ios/browser/api/sync/driver/brave_sync_profile_service.h", "//brave/ios/browser/api/wallet/brave_wallet_api.h", "//brave/ios/browser/api/wallet/hd_keyring_ios.h", - "//brave/ios/browser/api/wallet/keyring_controller_ios.h", + + # "//brave/ios/browser/api/wallet/keyring_controller_ios.h", "//brave/ios/browser/api/ads/brave_ads.h", "//brave/ios/browser/api/ads/ad_notification_ios.h", "//brave/ios/browser/api/ads/inline_content_ad_ios.h", diff --git a/ios/app/brave_core_main.mm b/ios/app/brave_core_main.mm index 1ec4ce03edf8..8291a8e00ae4 100644 --- a/ios/app/brave_core_main.mm +++ b/ios/app/brave_core_main.mm @@ -34,7 +34,6 @@ #if BUILDFLAG(BRAVE_WALLET_ENABLED) #import "brave/ios/browser/api/wallet/brave_wallet_api+private.h" -#import "brave/ios/browser/api/wallet/brave_wallet_service_factory.h" #endif // Chromium logging is global, therefore we cannot link this to the instance in @@ -198,11 +197,9 @@ - (BraveSyncProfileServiceIOS*)syncProfileService { - (nullable BraveWalletAPI*)wallet { #if BUILDFLAG(BRAVE_WALLET_ENABLED) - if (!_wallet) { - auto* service = - BraveWalletServiceFactory::GetForBrowserState(_mainBrowserState); - _wallet = [[BraveWalletAPI alloc] initWithWalletService:service]; - } + // if (!_wallet) { + // _wallet = [[BraveWalletAPI alloc] init]; + // } return _wallet; #else return nil; diff --git a/ios/browser/api/wallet/BUILD.gn b/ios/browser/api/wallet/BUILD.gn index f25542c3755e..d43223a1b0b6 100644 --- a/ios/browser/api/wallet/BUILD.gn +++ b/ios/browser/api/wallet/BUILD.gn @@ -16,14 +16,13 @@ source_set("wallet") { "brave_wallet_api+private.h", "brave_wallet_api.h", "brave_wallet_api.mm", - "brave_wallet_service_factory.cc", - "brave_wallet_service_factory.h", "hd_keyring_ios+private.h", "hd_keyring_ios.h", "hd_keyring_ios.mm", - "keyring_controller_ios+private.h", - "keyring_controller_ios.h", - "keyring_controller_ios.mm", + + # "keyring_controller_ios+private.h", + # "keyring_controller_ios.h", + # "keyring_controller_ios.mm", ] deps = [ diff --git a/ios/browser/api/wallet/brave_wallet_api+private.h b/ios/browser/api/wallet/brave_wallet_api+private.h index fbccef006dee..042a892c7c7f 100644 --- a/ios/browser/api/wallet/brave_wallet_api+private.h +++ b/ios/browser/api/wallet/brave_wallet_api+private.h @@ -17,8 +17,7 @@ class BraveWalletService; } @interface BraveWalletAPI (Private) -- (instancetype)initWithWalletService: - (brave_wallet::BraveWalletService*)service; +- (instancetype)init; @end NS_ASSUME_NONNULL_END diff --git a/ios/browser/api/wallet/brave_wallet_api.h b/ios/browser/api/wallet/brave_wallet_api.h index 134e51ca8a9f..61c9a750de4e 100644 --- a/ios/browser/api/wallet/brave_wallet_api.h +++ b/ios/browser/api/wallet/brave_wallet_api.h @@ -15,8 +15,6 @@ NS_ASSUME_NONNULL_BEGIN OBJC_EXPORT @interface BraveWalletAPI : NSObject -@property(nonatomic, readonly) KeyringControllerIOS* keyringController; - - (instancetype)init NS_UNAVAILABLE; @end diff --git a/ios/browser/api/wallet/brave_wallet_api.mm b/ios/browser/api/wallet/brave_wallet_api.mm index 85a457070e9a..7ae44932a59a 100644 --- a/ios/browser/api/wallet/brave_wallet_api.mm +++ b/ios/browser/api/wallet/brave_wallet_api.mm @@ -4,39 +4,21 @@ * You can obtain one at http://mozilla.org/MPL/2.0/. */ #import "brave/ios/browser/api/wallet/brave_wallet_api.h" -#import "brave/ios/browser/api/wallet/brave_wallet_service_factory.h" -#import "brave/ios/browser/api/wallet/keyring_controller_ios+private.h" +// #import "brave/ios/browser/api/wallet/keyring_controller_ios+private.h" #include "base/strings/sys_string_conversions.h" -#include "brave/components/brave_wallet/browser/brave_wallet_service.h" -#include "brave/components/brave_wallet/browser/keyring_controller.h" +// #include "brave/components/brave_wallet/browser/keyring_controller.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." #endif -@interface BraveWalletAPI () { - brave_wallet::BraveWalletService* _service; // NOT OWNED -} -@property(nonatomic, readwrite) KeyringControllerIOS* keyringController; -@end - @implementation BraveWalletAPI -- (instancetype)initWithWalletService: - (brave_wallet::BraveWalletService*)service { +- (instancetype)init { if ((self = [super init])) { - _service = service; } return self; } -- (KeyringControllerIOS*)keyringController { - if (!_keyringController) { - _keyringController = [[KeyringControllerIOS alloc] - initWithController:_service->keyring_controller()]; - } - return _keyringController; -} - @end diff --git a/ios/browser/api/wallet/brave_wallet_service_factory.cc b/ios/browser/api/wallet/brave_wallet_service_factory.cc deleted file mode 100644 index a39ebcdf5d13..000000000000 --- a/ios/browser/api/wallet/brave_wallet_service_factory.cc +++ /dev/null @@ -1,47 +0,0 @@ -/* 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/ios/browser/api/wallet/brave_wallet_service_factory.h" - -#include "brave/components/brave_wallet/browser/brave_wallet_service.h" -#include "brave/components/brave_wallet/browser/pref_names.h" -#include "components/keyed_service/ios/browser_state_dependency_manager.h" -#include "ios/chrome/browser/browser_state/browser_state_otr_helper.h" -#include "ios/chrome/browser/browser_state/chrome_browser_state.h" -#include "services/network/public/cpp/shared_url_loader_factory.h" - -// static -brave_wallet::BraveWalletService* BraveWalletServiceFactory::GetForBrowserState( - ChromeBrowserState* browser_state) { - return static_cast( - GetInstance()->GetServiceForBrowserState(browser_state, true)); -} - -// static -BraveWalletServiceFactory* BraveWalletServiceFactory::GetInstance() { - return base::Singleton::get(); -} - -BraveWalletServiceFactory::BraveWalletServiceFactory() - : BrowserStateKeyedServiceFactory( - "BraveWalletService", - BrowserStateDependencyManager::GetInstance()) {} - -BraveWalletServiceFactory::~BraveWalletServiceFactory() = default; - -std::unique_ptr -BraveWalletServiceFactory::BuildServiceInstanceFor( - web::BrowserState* context) const { - auto* browser_state = ChromeBrowserState::FromBrowserState(context); - std::unique_ptr wallet_service( - new brave_wallet::BraveWalletService( - browser_state->GetPrefs(), - browser_state->GetSharedURLLoaderFactory())); - return wallet_service; -} - -bool BraveWalletServiceFactory::ServiceIsNULLWhileTesting() const { - return true; -} diff --git a/ios/browser/api/wallet/brave_wallet_service_factory.h b/ios/browser/api/wallet/brave_wallet_service_factory.h deleted file mode 100644 index c7af9a1e0247..000000000000 --- a/ios/browser/api/wallet/brave_wallet_service_factory.h +++ /dev/null @@ -1,43 +0,0 @@ -/* 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/. */ - -#ifndef BRAVE_IOS_BROWSER_API_WALLET_BRAVE_WALLET_SERVICE_FACTORY_H_ -#define BRAVE_IOS_BROWSER_API_WALLET_BRAVE_WALLET_SERVICE_FACTORY_H_ - -#include - -#include "base/memory/singleton.h" -#include "components/keyed_service/ios/browser_state_keyed_service_factory.h" - -class ChromeBrowserState; - -namespace brave_wallet { -class BraveWalletService; -} - -class BraveWalletServiceFactory : public BrowserStateKeyedServiceFactory { - public: - // Creates the service if it doesn't exist already for |browser_state|. - static brave_wallet::BraveWalletService* GetForBrowserState( - ChromeBrowserState* browser_state); - - static BraveWalletServiceFactory* GetInstance(); - - private: - friend struct base::DefaultSingletonTraits; - - BraveWalletServiceFactory(); - ~BraveWalletServiceFactory() override; - - // BrowserContextKeyedServiceFactory: - // BrowserStateKeyedServiceFactory implementation. - std::unique_ptr BuildServiceInstanceFor( - web::BrowserState* context) const override; - bool ServiceIsNULLWhileTesting() const override; - - DISALLOW_COPY_AND_ASSIGN(BraveWalletServiceFactory); -}; - -#endif // BRAVE_IOS_BROWSER_API_WALLET_BRAVE_WALLET_SERVICE_FACTORY_H_ diff --git a/ios/browser/api/wallet/hd_keyring_ios.mm b/ios/browser/api/wallet/hd_keyring_ios.mm index 07b19c77da78..81f7bc6be081 100644 --- a/ios/browser/api/wallet/hd_keyring_ios.mm +++ b/ios/browser/api/wallet/hd_keyring_ios.mm @@ -11,7 +11,6 @@ #include "base/notreached.h" #include "base/strings/sys_string_conversions.h" -#include "brave/components/brave_wallet/browser/brave_wallet_service.h" #include "brave/components/brave_wallet/browser/hd_keyring.h" @interface HDKeyringIOS () {