Skip to content

Commit

Permalink
fix(background): better detection of out-of-funds on Pay now button
Browse files Browse the repository at this point in the history
refactor(background): use Array methods for cleaner code
  • Loading branch information
sidvishnoi authored and raducristianpopa committed Jul 17, 2024
1 parent cb193ea commit 096f04f
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 17 deletions.
3 changes: 3 additions & 0 deletions src/_locales/en/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@
"keyRevoked_action_reconnectBtn": {
"message": "Reconnect"
},
"pay_error_notEnoughFunds": {
"message": "Not enough funds to facilitate payment."
},
"connectWallet_error_invalidClient": {
"message": "Failed to connect. Please make sure you have added the public key to the correct wallet address."
}
Expand Down
43 changes: 26 additions & 17 deletions src/background/services/monetization.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { OpenPaymentsService, StorageService } from '.'
import type {
EventsService,
OpenPaymentsService,
StorageService,
TabState
} from '.'
import { type Browser, type Runtime } from 'webextension-polyfill'
import { Logger } from '@/shared/logger'
import {
Expand All @@ -9,11 +14,14 @@ import {
import { PaymentSession } from './paymentSession'
import { emitToggleWM } from '../lib/messages'
import { computeRate, getCurrentActiveTab, getSender, getTabId } from '../utils'
import { isOkState, removeQueryParams } from '@/shared/helpers'
import { EventsService } from './events'
import { isOutOfBalanceError } from './openPayments'
import {
isOkState,
removeQueryParams,
type Translation
} from '@/shared/helpers'
import { ALLOWED_PROTOCOLS } from '@/shared/defines'
import type { PopupStore } from '@/shared/types'
import { TabState } from './tabState'

export class MonetizationService {
private sessions: {
Expand All @@ -22,6 +30,7 @@ export class MonetizationService {

constructor(
private logger: Logger,
private t: Translation,
private openPaymentsService: OpenPaymentsService,
private storage: StorageService,
private browser: Browser,
Expand Down Expand Up @@ -228,21 +237,21 @@ export class MonetizationService {
throw new Error('This website is not monetized.')
}

let totalSentAmount = BigInt(0)
const splitAmount = Number(amount) / sessions.size
const promises = []

for (const session of sessions.values()) {
promises.push(session.pay(splitAmount))
}

;(await Promise.allSettled(promises)).forEach((p) => {
if (p.status === 'fulfilled') {
totalSentAmount += BigInt(p.value?.value ?? 0)
const results = await Promise.allSettled(
Array.from(sessions.values()).map((session) => session.pay(splitAmount))
)

const totalSentAmount = results
.filter((e) => e.status === 'fulfilled')
.reduce((acc, curr) => acc + BigInt(curr.value?.value ?? 0), 0n)
if (totalSentAmount === 0n) {
const isNotEnoughFunds = results
.filter((e) => e.status === 'rejected')
.some((e) => isOutOfBalanceError(e.reason))
if (isNotEnoughFunds) {
throw new Error(this.t('pay_error_notEnoughFunds'))
}
})

if (totalSentAmount === BigInt(0)) {
throw new Error('Could not facilitate payment for current website.')
}
}
Expand Down
5 changes: 5 additions & 0 deletions src/background/services/openPayments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -639,3 +639,8 @@ export const isTokenInvalidError = (error: OpenPaymentsClientError) => {
export const isTokenInactiveError = (error: OpenPaymentsClientError) => {
return error.status === 403 && error.description === 'Inactive Token'
}

export const isOutOfBalanceError = (error: any) => {
if (!isOpenPaymentsClientError(error)) return false
return error.status === 403 && error.description === 'unauthorized'
}
2 changes: 2 additions & 0 deletions src/background/services/paymentSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,8 @@ export class PaymentSession {
this.events.emit('open_payments.key_revoked')
} else if (isTokenExpiredError(e)) {
await this.openPaymentsService.rotateToken()
} else {
throw e
}
} finally {
if (outgoingPayment) {
Expand Down

0 comments on commit 096f04f

Please sign in to comment.