Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: use message.send() directly, move message to container #534

Merged
merged 14 commits into from
Aug 23, 2024
Merged
6 changes: 6 additions & 0 deletions src/background/container.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ import {
import { createLogger, Logger } from '@/shared/logger'
import { LOG_LEVEL } from '@/shared/defines'
import { tFactory, type Translation } from '@/shared/helpers'
import {
MessageManager,
type BackgroundToContentMessage
} from '@/shared/messages'

export interface Cradle {
logger: Logger
Expand All @@ -24,6 +28,7 @@ export interface Cradle {
storage: StorageService
openPaymentsService: OpenPaymentsService
monetizationService: MonetizationService
message: MessageManager<BackgroundToContentMessage>
sendToPopup: SendToPopup
tabEvents: TabEvents
background: Background
Expand Down Expand Up @@ -64,6 +69,7 @@ export const configureContainer = () => {
.inject(() => ({
logger: logger.getLogger('monetization')
})),
message: asClass(MessageManager<BackgroundToContentMessage>).singleton(),
tabEvents: asClass(TabEvents).singleton(),
sendToPopup: asClass(SendToPopup).singleton(),
background: asClass(Background)
Expand Down
35 changes: 0 additions & 35 deletions src/background/lib/messages.ts

This file was deleted.

32 changes: 14 additions & 18 deletions src/background/services/background.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
import type { Browser } from 'webextension-polyfill'
import {
type ToBackgroundMessage,
PopupToBackgroundAction,
ContentToBackgroundAction
} from '@/shared/messages'
import type { ToBackgroundMessage } from '@/shared/messages'
import {
failure,
getNextOccurrence,
Expand Down Expand Up @@ -135,81 +131,81 @@ export class Background {
this.logger.debug('Received message', message)
try {
switch (message.action) {
case PopupToBackgroundAction.GET_CONTEXT_DATA:
case 'GET_CONTEXT_DATA':
return success(await this.monetizationService.getPopupData())

case PopupToBackgroundAction.CONNECT_WALLET:
case 'CONNECT_WALLET':
await this.openPaymentsService.connectWallet(message.payload)
if (message.payload.recurring) {
this.scheduleResetOutOfFundsState()
}
return

case PopupToBackgroundAction.RECONNECT_WALLET: {
case 'RECONNECT_WALLET': {
await this.openPaymentsService.reconnectWallet()
await this.monetizationService.resumePaymentSessionActiveTab()
await this.updateVisualIndicatorsForCurrentTab()
return success(undefined)
}

case PopupToBackgroundAction.ADD_FUNDS:
case 'ADD_FUNDS':
await this.openPaymentsService.addFunds(message.payload)
await this.browser.alarms.clear(ALARM_RESET_OUT_OF_FUNDS)
if (message.payload.recurring) {
this.scheduleResetOutOfFundsState()
}
return

case PopupToBackgroundAction.DISCONNECT_WALLET:
case 'DISCONNECT_WALLET':
await this.openPaymentsService.disconnectWallet()
await this.browser.alarms.clear(ALARM_RESET_OUT_OF_FUNDS)
await this.updateVisualIndicatorsForCurrentTab()
this.sendToPopup.send('SET_STATE', { state: {}, prevState: {} })
return

case PopupToBackgroundAction.TOGGLE_WM: {
case 'TOGGLE_WM': {
await this.monetizationService.toggleWM()
await this.updateVisualIndicatorsForCurrentTab()
return
}

case PopupToBackgroundAction.PAY_WEBSITE:
case 'PAY_WEBSITE':
return success(
await this.monetizationService.pay(message.payload.amount)
)

case ContentToBackgroundAction.CHECK_WALLET_ADDRESS_URL:
case 'CHECK_WALLET_ADDRESS_URL':
return success(
await getWalletInformation(message.payload.walletAddressUrl)
)

case ContentToBackgroundAction.START_MONETIZATION:
case 'START_MONETIZATION':
await this.monetizationService.startPaymentSession(
message.payload,
sender
)
return

case ContentToBackgroundAction.STOP_MONETIZATION:
case 'STOP_MONETIZATION':
await this.monetizationService.stopPaymentSession(
message.payload,
sender
)
return

case ContentToBackgroundAction.RESUME_MONETIZATION:
case 'RESUME_MONETIZATION':
await this.monetizationService.resumePaymentSession(
message.payload,
sender
)
return

case PopupToBackgroundAction.UPDATE_RATE_OF_PAY:
case 'UPDATE_RATE_OF_PAY':
return success(
await this.storage.updateRate(message.payload.rateOfPay)
)

case ContentToBackgroundAction.IS_WM_ENABLED:
case 'IS_WM_ENABLED':
return success(await this.storage.getWMState())

default:
Expand Down
13 changes: 8 additions & 5 deletions src/background/services/monetization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import {
StopMonetizationPayload
} from '@/shared/messages'
import { PaymentSession } from './paymentSession'
import { emitToggleWM } from '../lib/messages'
import { computeRate, getCurrentActiveTab, getSender, getTabId } from '../utils'
import { isOutOfBalanceError } from './openPayments'
import { isOkState, removeQueryParams } from '@/shared/helpers'
Expand All @@ -21,6 +20,7 @@ export class MonetizationService {
private browser: Cradle['browser']
private events: Cradle['events']
private tabState: Cradle['tabState']
private message: Cradle['message']

constructor({
logger,
Expand All @@ -29,7 +29,8 @@ export class MonetizationService {
storage,
events,
openPaymentsService,
tabState
tabState,
message
}: Cradle) {
Object.assign(this, {
logger,
Expand All @@ -38,7 +39,8 @@ export class MonetizationService {
storage,
browser,
events,
tabState
tabState,
message
})

this.registerEventListeners()
Expand Down Expand Up @@ -98,7 +100,8 @@ export class MonetizationService {
this.events,
this.tabState,
removeQueryParams(url!),
this.logger
this.logger,
this.message
)

sessions.set(requestId, session)
Expand Down Expand Up @@ -236,7 +239,7 @@ export class MonetizationService {
async toggleWM() {
const { enabled } = await this.storage.get(['enabled'])
await this.storage.set({ enabled: !enabled })
emitToggleWM({ enabled: !enabled })
await this.message.sendToActiveTab('EMIT_TOGGLE_WM', { enabled: !enabled })
}

async pay(amount: string) {
Expand Down
68 changes: 35 additions & 33 deletions src/background/services/paymentSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import {
type OutgoingPayment,
type WalletAddress
} from '@interledger/open-payments/dist/types'
import { sendMonetizationEvent } from '../lib/messages'
import { bigIntMax, convert } from '@/shared/helpers'
import { transformBalance } from '@/popup/lib/utils'
import {
Expand All @@ -16,7 +15,12 @@ import {
} from './openPayments'
import { getNextSendableAmount } from '@/background/utils'
import type { EventsService, OpenPaymentsService, TabState } from '.'
import type { MonetizationEventDetails } from '@/shared/messages'
import type {
BackgroundToContentMessage,
MessageManager,
MonetizationEventDetails,
MonetizationEventPayload
} from '@/shared/messages'
import type { AmountValue } from '@/shared/types'
import type { Logger } from '@/shared/logger'

Expand Down Expand Up @@ -54,7 +58,8 @@ export class PaymentSession {
private events: EventsService,
private tabState: TabState,
private url: string,
private logger: Logger
private logger: Logger,
private message: MessageManager<BackgroundToContentMessage>
) {}

async adjustAmount(rate: AmountValue): Promise<void> {
Expand Down Expand Up @@ -223,13 +228,9 @@ export class PaymentSession {
this.debug(`Overpaying: waitTime=${waitTime}`)

if (monetizationEvent && source !== 'tab-change') {
sendMonetizationEvent({
tabId: this.tabId,
frameId: this.frameId,
payload: {
requestId: this.requestId,
details: monetizationEvent
}
this.sendMonetizationEvent({
requestId: this.requestId,
details: monetizationEvent
})
}

Expand Down Expand Up @@ -278,6 +279,15 @@ export class PaymentSession {
}
}

private async sendMonetizationEvent(payload: MonetizationEventPayload) {
await this.message.sendToTab(
this.tabId,
this.frameId,
'MONETIZATION_EVENT',
payload
)
}

private get canContinuePayment() {
return this.active && !this.isDisabled && !this.isInvalid
}
Expand Down Expand Up @@ -392,22 +402,18 @@ export class PaymentSession {
if (outgoingPayment) {
const { receiveAmount, receiver: incomingPayment } = outgoingPayment

sendMonetizationEvent({
tabId: this.tabId,
frameId: this.frameId,
payload: {
requestId: this.requestId,
details: {
amountSent: {
currency: receiveAmount.assetCode,
value: transformBalance(
receiveAmount.value,
receiveAmount.assetScale
)
},
incomingPayment,
paymentPointer: this.receiver.id
}
this.sendMonetizationEvent({
requestId: this.requestId,
details: {
amountSent: {
currency: receiveAmount.assetCode,
value: transformBalance(
receiveAmount.value,
receiveAmount.assetScale
)
},
incomingPayment,
paymentPointer: this.receiver.id
}
})
}
Expand Down Expand Up @@ -439,13 +445,9 @@ export class PaymentSession {
paymentPointer: this.receiver.id
}

sendMonetizationEvent({
tabId: this.tabId,
frameId: this.frameId,
payload: {
requestId: this.requestId,
details: monetizationEventDetails
}
this.sendMonetizationEvent({
requestId: this.requestId,
details: monetizationEventDetails
})

// TO DO: find a better source of truth for deciding if overpaying is applicable
Expand Down
6 changes: 6 additions & 0 deletions src/content/container.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,17 @@ import { ContentScript } from './services/contentScript'
import { MonetizationTagManager } from './services/monetizationTagManager'
import { LOG_LEVEL } from '@/shared/defines'
import { FrameManager } from './services/frameManager'
import {
type ContentToBackgroundMessage,
MessageManager
} from '@/shared/messages'

export interface Cradle {
logger: Logger
browser: Browser
document: Document
window: Window
message: MessageManager<ContentToBackgroundMessage>
monetizationTagManager: MonetizationTagManager
frameManager: FrameManager
contentScript: ContentScript
Expand All @@ -28,6 +33,7 @@ export const configureContainer = () => {
browser: asValue(browser),
document: asValue(document),
window: asValue(window),
message: asClass(MessageManager<ContentToBackgroundMessage>).singleton(),
frameManager: asClass(FrameManager)
.singleton()
.inject(() => ({
Expand Down
Loading
Loading