Skip to content

Commit

Permalink
Show unavailable message if balance cannot be fetched
Browse files Browse the repository at this point in the history
  • Loading branch information
zenparsing committed Apr 11, 2022
1 parent 9f0a64a commit 2605cea
Show file tree
Hide file tree
Showing 31 changed files with 148 additions and 134 deletions.
42 changes: 14 additions & 28 deletions browser/extensions/api/brave_rewards_api.cc
Original file line number Diff line number Diff line change
Expand Up @@ -999,46 +999,32 @@ BraveRewardsIsAutoContributeSupportedFunction::Run() {
OneArgument(base::Value(rewards_service->IsAutoContributeSupported())));
}

BraveRewardsFetchBalanceFunction::
~BraveRewardsFetchBalanceFunction() {
}
BraveRewardsGetAvailableBalanceFunction::
~BraveRewardsGetAvailableBalanceFunction() = default;

ExtensionFunction::ResponseAction
BraveRewardsFetchBalanceFunction::Run() {
Profile* profile = Profile::FromBrowserContext(browser_context());
RewardsService* rewards_service =
RewardsServiceFactory::GetForProfile(profile);
BraveRewardsGetAvailableBalanceFunction::Run() {
auto* profile = Profile::FromBrowserContext(browser_context());
auto* rewards_service = RewardsServiceFactory::GetForProfile(profile);

if (!rewards_service) {
base::DictionaryValue balance_value;
return RespondNow(OneArgument(std::move(balance_value)));
return RespondNow(Error("The Rewards service is unavailable"));
}

rewards_service->FetchBalance(
base::BindOnce(
&BraveRewardsFetchBalanceFunction::OnBalance,
this));
rewards_service->FetchBalance(base::BindOnce(
&BraveRewardsGetAvailableBalanceFunction::OnBalanceFetched, this));

return RespondLater();
}

void BraveRewardsFetchBalanceFunction::OnBalance(
const ledger::type::Result result,
void BraveRewardsGetAvailableBalanceFunction::OnBalanceFetched(
ledger::type::Result result,
ledger::type::BalancePtr balance) {
base::Value balance_value(base::Value::Type::DICTIONARY);
if (result == ledger::type::Result::LEDGER_OK && balance) {
balance_value.SetDoubleKey("total", balance->total);

base::Value wallets(base::Value::Type::DICTIONARY);
for (auto const& rate : balance->wallets) {
wallets.SetDoubleKey(rate.first, rate.second);
}
balance_value.SetKey("wallets", std::move(wallets));
Respond(OneArgument(base::Value(balance->total)));
} else {
balance_value.SetDoubleKey("total", 0.0);
base::Value wallets(base::Value::Type::DICTIONARY);
balance_value.SetKey("wallets", std::move(wallets));
Respond(Error("Rewards balance unavailable"));
}

Respond(OneArgument(std::move(balance_value)));
}

BraveRewardsGetExternalWalletFunction::
Expand Down
11 changes: 5 additions & 6 deletions browser/extensions/api/brave_rewards_api.h
Original file line number Diff line number Diff line change
Expand Up @@ -360,19 +360,18 @@ class BraveRewardsIsAutoContributeSupportedFunction : public ExtensionFunction {
ResponseAction Run() override;
};

class BraveRewardsFetchBalanceFunction : public ExtensionFunction {
class BraveRewardsGetAvailableBalanceFunction : public ExtensionFunction {
public:
DECLARE_EXTENSION_FUNCTION("braveRewards.fetchBalance", UNKNOWN)
DECLARE_EXTENSION_FUNCTION("braveRewards.getAvailableBalance", UNKNOWN)

protected:
~BraveRewardsFetchBalanceFunction() override;
~BraveRewardsGetAvailableBalanceFunction() override;

ResponseAction Run() override;

private:
void OnBalance(
const ledger::type::Result result,
ledger::type::BalancePtr balance);
void OnBalanceFetched(ledger::type::Result result,
ledger::type::BalancePtr balance);
};

class BraveRewardsGetExternalWalletFunction : public ExtensionFunction {
Expand Down
2 changes: 2 additions & 0 deletions browser/ui/webui/brave_webui_source.cc
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,7 @@ void CustomizeWebUIHTMLSource(const std::string &name,
// Rewards widget
{ "rewardsAdGrantAmount", IDS_REWARDS_WIDGET_AD_GRANT_AMOUNT },
{ "rewardsAdGrantTitle", IDS_REWARDS_WIDGET_AD_GRANT_TITLE },
{ "rewardsBalanceUnavailable", IDS_REWARDS_WALLET_BALANCE_UNAVAILABLE },
{ "rewardsBraveRewards", IDS_REWARDS_WIDGET_BRAVE_REWARDS },
{ "rewardsClaimRewards", IDS_REWARDS_WIDGET_CLAIM_REWARDS },
{ "rewardsClaimTokens", IDS_REWARDS_WIDGET_CLAIM_TOKENS },
Expand Down Expand Up @@ -776,6 +777,7 @@ void CustomizeWebUIHTMLSource(const std::string &name,
{ "walletAccountLink", IDS_REWARDS_WALLET_ACCOUNT_LINK },
{ "walletAddFunds", IDS_REWARDS_WALLET_ADD_FUNDS },
{ "walletAutoContribute", IDS_REWARDS_WALLET_AUTO_CONTRIBUTE },
{ "walletBalanceUnavailable", IDS_REWARDS_WALLET_BALANCE_UNAVAILABLE },
{ "walletDisconnected", IDS_REWARDS_WALLET_DISCONNECTED },
{ "walletDisconnectLink", IDS_REWARDS_WALLET_DISCONNECT_LINK },
{ "walletEstimatedEarnings", IDS_REWARDS_WALLET_ESTIMATED_EARNINGS },
Expand Down
15 changes: 4 additions & 11 deletions common/extensions/api/brave_rewards.json
Original file line number Diff line number Diff line change
Expand Up @@ -1132,25 +1132,18 @@
]
},
{
"name": "fetchBalance",
"name": "getAvailableBalance",
"type": "function",
"description": "Fetch balance",
"description": "Returns the user's available Rewards balance",
"parameters": [
{
"type": "function",
"name": "callback",
"parameters": [
{
"name": "balance",
"type": "object",
"properties": {
"total": {
"type": "any"
},
"wallets": {
"type": "any"
}
}
"type": "number",
"description": "The user's current available Rewards balance"
}
]
}
Expand Down
2 changes: 1 addition & 1 deletion components/brave_new_tab_ui/actions/rewards_actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export const dismissNotification = (id: string) => action(types.DISMISS_NOTIFICA
id
})

export const onBalance = (balance: NewTab.RewardsBalance) => action(types.ON_BALANCE, {
export const onBalance = (balance?: number) => action(types.ON_BALANCE, {
balance
})

Expand Down
4 changes: 2 additions & 2 deletions components/brave_new_tab_ui/api/initialData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export type PreInitialRewardsData = {

export type InitialRewardsData = {
report: NewTab.RewardsBalanceReport
balance: NewTab.RewardsBalance
balance?: number
adsAccountStatement: NewTab.AdsAccountStatement
parameters: NewTab.RewardsParameters
}
Expand Down Expand Up @@ -139,7 +139,7 @@ export async function getRewardsInitialData (): Promise<InitialRewardsData> {
new Promise(resolve => chrome.braveRewards.getBalanceReport(new Date().getMonth() + 1, new Date().getFullYear(), (report: NewTab.RewardsBalanceReport) => {
resolve(report)
})),
new Promise(resolve => chrome.braveRewards.fetchBalance((balance: NewTab.RewardsBalance) => {
new Promise(resolve => chrome.braveRewards.getAvailableBalance((balance) => {
resolve(balance)
})),
new Promise(resolve => chrome.braveRewards.getRewardsParameters((parameters: NewTab.RewardsParameters) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export function RewardsContextAdapter (props: { children: React.ReactNode }) {
export interface RewardsProps {
rewardsEnabled: boolean
enabledAds: boolean
balance: NewTab.RewardsBalance
balance?: number
report?: NewTab.RewardsBalanceReport
adsAccountStatement: NewTab.AdsAccountStatement
parameters: NewTab.RewardsParameters
Expand Down Expand Up @@ -101,7 +101,7 @@ export const RewardsWidget = createWidget((props: RewardsProps) => {
rewardsEnabled={props.rewardsEnabled}
adsEnabled={props.enabledAds}
adsSupported={Boolean(props.adsSupported)}
rewardsBalance={props.balance.total}
rewardsBalance={typeof props.balance === 'number' ? props.balance : null}
exchangeCurrency='USD'
exchangeRate={props.parameters.rate}
grantInfo={grantInfo}
Expand Down
10 changes: 6 additions & 4 deletions components/brave_new_tab_ui/storage/new_tab_storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,7 @@ export const defaultState: NewTab.State = {
earningsThisMonth: 0,
earningsLastMonth: 0
},
balance: {
total: 0,
wallets: {}
},
balance: 0,
dismissedNotifications: [],
rewardsEnabled: false,
enabledAds: false,
Expand Down Expand Up @@ -257,6 +254,11 @@ const cleanData = (state: NewTab.State) => {
Number(adsAccountStatement.nextPaymentDate) * 1000 || 0
}

// rewardsState.balance updated from object to optional number
if (rewardsState.balance && typeof rewardsState.balance !== 'number') {
rewardsState.balance = defaultState.rewardsState.balance
}

if (!rewardsState.parameters) {
rewardsState.parameters = defaultState.rewardsState.parameters
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -754,7 +754,7 @@ class PageWallet extends React.Component<Props, State> {
pendingContributionTotal
} = this.props.rewardsData
const { total } = balance
const { modalBackup } = ui
const { modalBackup, walletServerProblem } = ui

let externalWalletInfo: ExternalWallet | null = null
const walletStatus = this.getExternalWalletStatus()
Expand All @@ -779,7 +779,7 @@ class PageWallet extends React.Component<Props, State> {
return (
<PageWalletWrapper>
<WalletCard
balance={total}
balance={walletServerProblem ? null : total}
externalWallet={externalWalletInfo}
earningsThisMonth={adsData.adsEarningsThisMonth || 0}
earningsLastMonth={adsData.adsEarningsLastMonth || 0}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ const walletReducer: Reducer<Rewards.State | undefined> = (state: Rewards.State,
} else if (status === 24) { // on ledger::type::Result::EXPIRED_TOKEN
chrome.send('brave_rewards.getExternalWallet')
state.balance.total = action.payload.balance.total || 0
ui.walletServerProblem = true
}

state = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,10 @@
"message": "Auto-Contribute",
"description": ""
},
"walletBalanceUnavailable": {
"message": "N/A",
"description": "Message displayed when balance is unavailable"
},
"walletDisconnected": {
"message": "Logged out",
"description": ""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,6 @@ chrome.braveRewards.onRecurringTipRemoved.addListener((success: boolean) => {

chrome.braveRewards.onReconcileComplete.addListener((result: number, type: number) => {
if (result === 0) {
chrome.braveRewards.fetchBalance((balance: RewardsExtension.Balance) => {
rewardsPanelActions.onBalance(balance)
})

chrome.braveRewards.getBalanceReport(new Date().getMonth() + 1, new Date().getFullYear(),
(report: RewardsExtension.BalanceReport) => {
rewardsPanelActions.onBalanceReport(report)
Expand All @@ -83,19 +79,9 @@ chrome.braveRewards.onDisconnectWallet.addListener((properties: {result: number,
chrome.braveRewards.getExternalWallet((result: number, wallet: RewardsExtension.ExternalWallet) => {
rewardsPanelActions.onExternalWallet(wallet)
})

chrome.braveRewards.fetchBalance((balance: RewardsExtension.Balance) => {
rewardsPanelActions.onBalance(balance)
})
}
})

chrome.braveRewards.onUnblindedTokensReady.addListener(() => {
chrome.braveRewards.fetchBalance((balance: RewardsExtension.Balance) => {
rewardsPanelActions.onBalance(balance)
})
})

chrome.braveRewards.onPromotionFinish.addListener((result: RewardsExtension.Result, promotion: RewardsExtension.Promotion) => {
rewardsPanelActions.promotionFinished(result, promotion)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -754,7 +754,7 @@ class PageWallet extends React.Component<Props, State> {
pendingContributionTotal
} = this.props.rewardsData
const { total } = balance
const { modalBackup } = ui
const { modalBackup, walletServerProblem } = ui

let externalWalletInfo: ExternalWallet | null = null
const walletStatus = this.getExternalWalletStatus()
Expand All @@ -779,7 +779,7 @@ class PageWallet extends React.Component<Props, State> {
return (
<PageWalletWrapper>
<WalletCard
balance={total}
balance={walletServerProblem ? null : total}
externalWallet={externalWalletInfo}
earningsThisMonth={adsData.adsEarningsThisMonth || 0}
earningsLastMonth={adsData.adsEarningsLastMonth || 0}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ const walletReducer: Reducer<Rewards.State | undefined> = (state: Rewards.State,
} else if (status === 24) { // on ledger::type::Result::EXPIRED_TOKEN
chrome.send('brave_rewards.getExternalWallet')
state.balance.total = action.payload.balance.total || 0
ui.walletServerProblem = true
}

state = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,15 @@ import {
// 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<number | null>((resolve) => {
chrome.braveRewards.getAvailableBalance((balance) => {
if (chrome.runtime.lastError) {
console.error(chrome.runtime.lastError.message)
resolve(null)
} else {
resolve(balance || 0)
}
})
})
}

Expand All @@ -52,7 +59,7 @@ export function getExternalWalletProviders () {
// The extension API currently does not support retrieving a list of
// external wallet providers.
chrome.braveRewards.getExternalWallet((_, wallet) => {
const provider = externalWalletProviderFromString(wallet.type)
const provider = wallet && externalWalletProviderFromString(wallet.type)
resolve(provider ? [provider] : [])
})
})
Expand Down Expand Up @@ -120,6 +127,11 @@ export function getExternalWallet () {

return new Promise<ExternalWallet | null>((resolve) => {
chrome.braveRewards.getExternalWallet((_, wallet) => {
if (!wallet) {
resolve(null)
return
}

const provider = externalWalletProviderFromString(wallet.type)
const status = mapStatus(wallet.status)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export interface Options {
export interface HostState {
loading: boolean
rewardsEnabled: boolean
balance: number
balance: number | null
settings: Settings
options: Options
grantCaptchaInfo: GrantCaptchaInfo | null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,10 +87,8 @@ export const balanceTitle = styled.div`
`

export const balanceAmount = styled.div`
.amount {
font-size: 36px;
line-height: 40px;
}
font-size: 36px;
line-height: 40px;
.currency {
font-size: 14px;
Expand Down
Loading

0 comments on commit 2605cea

Please sign in to comment.