Skip to content

Commit

Permalink
Merge pull request #17294 from brave/sszaloki-28549-balance-spinner
Browse files Browse the repository at this point in the history
Shows spinner if balance (vBAT/custodian) cannot be fetched.
  • Loading branch information
szilardszaloki authored Feb 25, 2023
2 parents b060f92 + 03fbc95 commit adb9830
Show file tree
Hide file tree
Showing 27 changed files with 269 additions and 102 deletions.
50 changes: 32 additions & 18 deletions browser/extensions/api/brave_rewards_api.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1192,30 +1192,44 @@ ExtensionFunction::ResponseAction BraveRewardsFetchBalanceFunction::Run() {
return RespondNow(Error("Rewards service is not available"));
}

rewards_service->FetchBalance(
base::BindOnce(&BraveRewardsFetchBalanceFunction::OnBalance, this));
rewards_service->GetExternalWallet(base::BindOnce(
&BraveRewardsFetchBalanceFunction::OnGetExternalWallet, this));

return RespondLater();
}

void BraveRewardsFetchBalanceFunction::OnBalance(
const ledger::mojom::Result result,
ledger::mojom::BalancePtr balance) {
base::Value::Dict balance_value;
if (result == ledger::mojom::Result::LEDGER_OK && balance) {
balance_value.Set("total", balance->total);
void BraveRewardsFetchBalanceFunction::OnGetExternalWallet(
base::expected<ledger::mojom::ExternalWalletPtr,
ledger::mojom::GetExternalWalletError> result) {
std::string connected_wallet_type;
if (auto wallet = std::move(result).value_or(nullptr);
wallet && wallet->status == ledger::mojom::WalletStatus::kConnected) {
connected_wallet_type = std::move(wallet->type);
}

base::Value::Dict wallets;
for (auto const& rate : balance->wallets) {
wallets.Set(rate.first, rate.second);
}
balance_value.Set("wallets", std::move(wallets));
} else {
balance_value.Set("total", 0.0);
base::Value::Dict wallets;
balance_value.Set("wallets", std::move(wallets));
Profile* profile = Profile::FromBrowserContext(browser_context());
RewardsService* rewards_service =
RewardsServiceFactory::GetForProfile(profile);
if (!rewards_service) {
return Release();
}

rewards_service->FetchBalance(
base::BindOnce(&BraveRewardsFetchBalanceFunction::OnFetchBalance, this,
std::move(connected_wallet_type)));
}

void BraveRewardsFetchBalanceFunction::OnFetchBalance(
const std::string& connected_wallet_type,
ledger::mojom::Result,
ledger::mojom::BalancePtr balance) {
if (!balance || !balance->wallets.contains("blinded") ||
(!connected_wallet_type.empty() &&
!balance->wallets.contains(connected_wallet_type))) {
return Respond(NoArguments());
}

Respond(WithArguments(std::move(balance_value)));
Respond(WithArguments(balance->total));
}

BraveRewardsGetExternalWalletProvidersFunction::
Expand Down
9 changes: 7 additions & 2 deletions browser/extensions/api/brave_rewards_api.h
Original file line number Diff line number Diff line change
Expand Up @@ -467,8 +467,13 @@ class BraveRewardsFetchBalanceFunction : public ExtensionFunction {
ResponseAction Run() override;

private:
void OnBalance(const ledger::mojom::Result result,
ledger::mojom::BalancePtr balance);
void OnGetExternalWallet(
base::expected<ledger::mojom::ExternalWalletPtr,
ledger::mojom::GetExternalWalletError> result);

void OnFetchBalance(const std::string& connected_wallet_type,
ledger::mojom::Result result,
ledger::mojom::BalancePtr balance);
};

class BraveRewardsGetExternalWalletProvidersFunction
Expand Down
1 change: 1 addition & 0 deletions browser/ui/webui/brave_rewards/rewards_panel_ui.cc
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ static constexpr webui::LocalizedString kStrings[] = {
{"includeInAutoContribute", IDS_REWARDS_PANEL_INCLUDE_IN_AUTO_CONTRIBUTE},
{"learnMore", IDS_REWARDS_LEARN_MORE},
{"learnMoreAboutBAT", IDS_REWARDS_PANEL_LEARN_MORE_ABOUT_BAT},
{"loading", IDS_BRAVE_REWARDS_LOADING_LABEL},
{"monthlyTip", IDS_REWARDS_PANEL_MONTHLY_TIP},
{"notificationAdGrantAmount", IDS_REWARDS_NOTIFICATION_AD_GRANT_AMOUNT},
{"notificationAdGrantTitle", IDS_REWARDS_NOTIFICATION_AD_GRANT_TITLE},
Expand Down
14 changes: 9 additions & 5 deletions browser/ui/webui/brave_rewards_internals_ui.cc
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ class RewardsInternalsDOMHandler : public content::WebUIMessageHandler {
void HandleGetRewardsInternalsInfo(const base::Value::List& args);
void OnGetRewardsInternalsInfo(ledger::mojom::RewardsInternalsInfoPtr info);
void GetBalance(const base::Value::List& args);
void OnGetBalance(const ledger::mojom::Result result,
void OnGetBalance(ledger::mojom::Result result,
ledger::mojom::BalancePtr balance);
void GetContributions(const base::Value::List& args);
void OnGetContributions(
Expand Down Expand Up @@ -204,25 +204,29 @@ void RewardsInternalsDOMHandler::GetBalance(const base::Value::List& args) {
}

void RewardsInternalsDOMHandler::OnGetBalance(
const ledger::mojom::Result result,
ledger::mojom::Result,
ledger::mojom::BalancePtr balance) {
if (!IsJavascriptAllowed()) {
return;
}

base::Value::Dict balance_value;

if (result == ledger::mojom::Result::LEDGER_OK && balance) {
if (balance) {
balance_value.Set("total", balance->total);

base::Value::Dict wallets;
for (auto const& wallet : balance->wallets) {
for (const auto& wallet : balance->wallets) {
wallets.Set(wallet.first, wallet.second);
}
balance_value.Set("wallets", std::move(wallets));
} else {
balance_value.Set("total", 0.0);
balance_value.Set("wallets", base::Value::Dict());
}

CallJavascriptFunction("brave_rewards_internals.balance", balance_value);
CallJavascriptFunction("brave_rewards_internals.balance",
std::move(balance_value));
}

void RewardsInternalsDOMHandler::GetContributions(
Expand Down
6 changes: 6 additions & 0 deletions browser/ui/webui/brave_webui_source.cc
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,8 @@ void CustomizeWebUIHTMLSource(content::WebUI* web_ui,
{"rewardsVBATNoticeTitle1", IDS_REWARDS_VBAT_NOTICE_TITLE1},
{"rewardsVBATNoticeTitle2", IDS_REWARDS_VBAT_NOTICE_TITLE2},

{ "loading", IDS_BRAVE_REWARDS_LOADING_LABEL },

// Brave Talk Widget
{ "braveTalkWidgetTitle", IDS_BRAVE_TALK_WIDGET_TITLE },
{ "braveTalkWidgetWelcomeTitle", IDS_BRAVE_TALK_WIDGET_WELCOME_TITLE },
Expand Down Expand Up @@ -689,6 +691,8 @@ void CustomizeWebUIHTMLSource(content::WebUI* web_ui,
{ "walletViewStatement", IDS_REWARDS_WALLET_VIEW_STATEMENT },
{ "walletVerified", IDS_REWARDS_WALLET_VERIFIED },
{ "walletYourBalance", IDS_REWARDS_WALLET_YOUR_BALANCE },

{ "loading", IDS_BRAVE_REWARDS_LOADING_LABEL },
}
}, {
std::string("adblock"), {
Expand Down Expand Up @@ -898,6 +902,8 @@ void CustomizeWebUIHTMLSource(content::WebUI* web_ui,
{ "walletStatusDisconnectedVerified", IDS_BRAVE_REWARDS_INTERNALS_WALLET_STATUS_DISCONNECTED_VERIFIED }, // NOLINT
{ "walletCreationEnvironment", IDS_BRAVE_REWARDS_INTERNALS_WALLET_CREATION_ENVIRONMENT }, // NOLINT
{ "currentEnvironment", IDS_BRAVE_REWARDS_INTERNALS_CURRENT_ENVIRONMENT}, // NOLINT

{ "loading", IDS_BRAVE_REWARDS_LOADING_LABEL },
}
}, {
#if BUILDFLAG(ENABLE_TOR)
Expand Down
11 changes: 2 additions & 9 deletions common/extensions/api/brave_rewards.json
Original file line number Diff line number Diff line change
Expand Up @@ -1368,15 +1368,8 @@
"parameters": [
{
"name": "balance",
"type": "object",
"properties": {
"total": {
"type": "any"
},
"wallets": {
"type": "any"
}
}
"type": "number",
"optional": true
}
]
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
/* Copyright (c) 2023 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 https://mozilla.org/MPL/2.0/. */

Expand All @@ -13,6 +14,9 @@ import { getProviderPayoutStatus } from '../../../../brave_rewards/resources/sha
import { WithThemeVariables } from '../../../../brave_rewards/resources/shared/components/with_theme_variables'
import { GrantInfo } from '../../../../brave_rewards/resources/shared/lib/grant_info'
import { userTypeFromString } from '../../../../brave_rewards/resources/shared/lib/user_type'
import {
optional
} from '../../../../brave_rewards/resources/shared/lib/optional'

import {
externalWalletFromExtensionData,
Expand Down Expand Up @@ -138,7 +142,7 @@ export const RewardsWidget = createWidget((props: RewardsProps) => {
adsEnabled={props.enabledAds}
adsSupported={Boolean(props.adsSupported)}
needsBrowserUpgradeToServeAds={props.needsBrowserUpgradeToServeAds}
rewardsBalance={props.balance.total}
rewardsBalance={optional(props.balance)}
exchangeCurrency='USD'
exchangeRate={props.parameters.rate}
providerPayoutStatus={providerPayoutStatus()}
Expand Down
5 changes: 1 addition & 4 deletions components/brave_new_tab_ui/storage/new_tab_storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,7 @@ export const defaultState: NewTab.State = {
earningsThisMonth: 0,
earningsLastMonth: 0
},
balance: {
total: 0,
wallets: {}
},
balance: undefined,
externalWallet: undefined,
externalWalletProviders: [],
dismissedNotifications: [],
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
/* Copyright (c) 2023 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 https://mozilla.org/MPL/2.0/. */

import * as React from 'react'

// Utils
import { getLocale } from '../../../../common/locale'
import { LoadingIcon } from '../../shared/components/icons/loading_icon'
import * as mojom from '../../shared/lib/mojom'

interface Props {
info: RewardsInternals.Balance
balance: RewardsInternals.Balance
externalWallet: RewardsInternals.ExternalWallet
}

const getWalletName = (walletKey: string) => {
Expand All @@ -30,26 +34,40 @@ const getWalletName = (walletKey: string) => {
return 'Missing wallet'
}

const getWalletBalance = (wallets: Record<string, number>) => {
const getBalances = (
balances: Record<string, number>,
externalWallet: RewardsInternals.ExternalWallet
) => {
const walletKeys = Object.keys(balances)

const getBalance = (wallet: string) => {
return <div key={'wallet-' + wallet}>
{getWalletName(wallet)}: {walletKeys.includes(wallet)
? balances[wallet] + ' ' + getLocale('bat')
: <><LoadingIcon />{getLocale('loading')}</>}
</div>
}

let items = []
for (const key in wallets) {
items.push(<div key={'wallet-' + key}> {getWalletName(key)}: {wallets[key]} {getLocale('bat')} </div>)
items.push(getBalance('blinded'))
if (externalWallet.status === mojom.WalletStatus.kConnected) {
items.push(getBalance(externalWallet.type))
}

return items
}

export const Balance = (props: Props) => {
if (!props.info) {
if (!props.balance) {
return null
}

return (
<>
<h3>{getLocale('balanceInfo')}</h3>
<div>
{getLocale('totalBalance')} {props.info.total} {getLocale('bat')}
{getLocale('totalBalance')} {props.balance.total} {getLocale('bat')}
</div>
{getWalletBalance(props.info.wallets)}
{getBalances(props.balance.wallets, props.externalWallet)}
</>)
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
/* Copyright (c) 2023 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 https://mozilla.org/MPL/2.0/. */

Expand All @@ -9,7 +10,7 @@ import { WalletHistory } from './walletHistory'
import { Balance } from './balance'
import { ExternalWallet } from './externalWallet'
import { Button } from 'brave-ui/components'
import { ButtonWrapper } from '../style'
import { BalanceWrapper, ButtonWrapper } from '../style'

// Utils
import { getLocale } from '../../../../common/locale'
Expand All @@ -36,7 +37,11 @@ export class General extends React.Component<Props, {}> {
paymentId={this.props.data.info.walletPaymentId}
logEntries={this.props.data.eventLogs}
/>
<Balance info={this.props.data.balance} />
<BalanceWrapper>
<Balance
balance={this.props.data.balance}
externalWallet={this.props.data.externalWallet} />
</BalanceWrapper>
<ExternalWallet info={this.props.data.externalWallet} />
</>
)
Expand Down
11 changes: 10 additions & 1 deletion components/brave_rewards/resources/internals/style.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
/* Copyright (c) 2023 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 https://mozilla.org/MPL/2.0/. */

Expand Down Expand Up @@ -104,3 +105,11 @@ export const Input = styled.input`
export const DiagnosticsHeader = styled.h3`
margin: 20px 0px 10px;
`

export const BalanceWrapper = styled('div')<{}>`
.icon {
height: 16px;
vertical-align: bottom;
margin-right: 2px;
}
`
12 changes: 10 additions & 2 deletions components/brave_rewards/resources/page/components/pageWallet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import { PendingContributionsModal } from './pending_contributions_modal'

import * as mojom from '../../shared/lib/mojom'
import { isPublisherVerified } from '../../shared/lib/publisher_status'
import { optional } from '../../shared/lib/optional'

interface State {
modalActivity: boolean
Expand Down Expand Up @@ -530,7 +531,6 @@ class PageWallet extends React.Component<Props, State> {
pendingContributions,
userType
} = this.props.rewardsData
const { total } = balance
const { modalReset, modalConnect } = ui

let externalWalletInfo: ExternalWallet | null = null
Expand All @@ -553,12 +553,20 @@ class PageWallet extends React.Component<Props, State> {
pendingTips: pendingContributionTotal || 0
}

const walletKeys = Object.keys(balance.wallets)
const totalBalance =
!walletKeys.includes('blinded')
? undefined
: externalWallet && !walletKeys.includes(externalWallet.type)
? undefined
: balance.total

return (
<>
{
userType !== 'unconnected' &&
<WalletCard
balance={total}
balance={optional(totalBalance)}
externalWallet={externalWalletInfo}
providerPayoutStatus={'off'}
earningsThisMonth={adsData.adsEarningsThisMonth || 0}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
/* Copyright (c) 2023 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 https://mozilla.org/MPL/2.0/. */

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,16 @@ import {
Settings
} from './interfaces'

import { optional, Optional } from '../../shared/lib/optional'

// The functions exported from this module wrap the existing |braveRewards|
// and |rewardsNotifications| extension API functions in order to reduce the
// amount of mapping/adapter code found in |extension_host|. As the extension
// APIs are improved, the need for this adapter will diminish.

export function getRewardsBalance () {
return new Promise<number>((resolve) => {
chrome.braveRewards.fetchBalance((balance) => { resolve(balance.total) })
return new Promise<Optional<number>>((resolve) => {
chrome.braveRewards.fetchBalance((balance) => { resolve(optional(balance)) })
})
}

Expand Down
Loading

0 comments on commit adb9830

Please sign in to comment.