Skip to content

Commit

Permalink
Merge pull request #263 from radixdlt/develop
Browse files Browse the repository at this point in the history
1.4.1
  • Loading branch information
dawidsowardx authored Jun 20, 2024
2 parents aee11a2 + 9d7722e commit c183056
Show file tree
Hide file tree
Showing 11 changed files with 145 additions and 30 deletions.
1 change: 1 addition & 0 deletions src/chrome/background/background.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@ chrome.notifications.onClicked.addListener(handleNotificationClick)
chrome.notifications.onButtonClicked.addListener(handleNotificationClick)
chrome.storage.onChanged.addListener(handleStorageChange)
chrome.action.onClicked.addListener(openParingPopup)

chrome.runtime.onInstalled.addListener(handleOnInstallExtension)

createOffscreen()
Expand Down
38 changes: 18 additions & 20 deletions src/chrome/content-script/content-script.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { ContentScriptMessageHandler } from './message-handler'
import { createMessage } from '../messages/create-message'
import { MessageClient } from '../messages/message-client'
import { ConfirmationMessageError, Message } from '../messages/_types'
import { errAsync, okAsync, ResultAsync } from 'neverthrow'
import { err, errAsync, okAsync, ResultAsync } from 'neverthrow'
import { logger } from 'utils/logger'
import { MessageLifeCycleEvent } from 'chrome/dapp/_types'
import { sendMessage } from 'chrome/helpers/send-message'
Expand Down Expand Up @@ -56,58 +56,56 @@ const messageHandler = MessageClient(
{ logger: appLogger },
)

const handleWalletInteraction = async (
walletInteraction: WalletInteraction,
) => {
const handleWalletInteraction = (walletInteraction: WalletInteraction) =>
sendMessage(createMessage.dAppRequest('contentScript', walletInteraction))
}

const handleExtensionInteraction = async (
const handleExtensionInteraction = (
extensionInteraction: ExtensionInteraction,
) => {
switch (extensionInteraction.discriminator) {
case 'openPopup':
await sendMessage(createMessage.openParingPopup())
break
return sendMessage(createMessage.openParingPopup())

case 'extensionStatus':
await hasConnections().map((hasConnections) => {
sendMessageToDapp(createMessage.extensionStatus(hasConnections))
})
break
return hasConnections().map((hasConnections) =>
sendMessageToDapp(createMessage.extensionStatus(hasConnections)),
)

case 'cancelWalletInteraction':
sendMessage(
return sendMessage(
createMessage.cancelWalletInteraction(
addOriginToCancelInteraction(extensionInteraction),
),
)
break

case 'walletInteraction':
sendMessage(
return sendMessage(
createMessage.walletInteraction({
...extensionInteraction,
interaction: addOriginToWalletInteraction(
extensionInteraction.interaction,
),
}),
)
break

default:
logger.error({
return err({
reason: 'InvalidExtensionRequest',
interaction: extensionInteraction,
})
break
}
}

// incoming messages from dApps
chromeDAppClient.messageListener(
handleWalletInteraction,
handleExtensionInteraction,
(p) =>
handleWalletInteraction(p).mapErr((e) => {
appLogger.error('handleWalletInteraction', e)
}),
(p) =>
handleExtensionInteraction(p).mapErr((e) => {
appLogger.error('handleExtensionInteraction', e)
}),
)

// incoming messages from extension
Expand Down
4 changes: 3 additions & 1 deletion src/chrome/helpers/send-message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { ResultAsync } from 'neverthrow'

export const sendMessage = (message: Message) =>
ResultAsync.fromPromise(
chrome.runtime.sendMessage(message),
chrome.runtime.id
? chrome.runtime.sendMessage(message)
: Promise.reject({ reason: 'NoChromeRuntimeId' }),
(error) => error as Error,
)
2 changes: 1 addition & 1 deletion src/chrome/messages/message-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ export const MessageClient = (
mergeMap(({ message, tabId }) =>
handler(message, sendMessageAndWaitForConfirmation, tabId)
.andThen((result) =>
result.sendConfirmation
result?.sendConfirmation
? sendConfirmationSuccess({
origin,
messageId: message.messageId,
Expand Down
4 changes: 1 addition & 3 deletions src/chrome/offscreen/wallet-connection/message-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,6 @@ export const WalletConnectionMessageHandler = (input: {
// Message from wallet to extension (incldues ledger, dApp and accountList message)
case messageDiscriminator.walletMessage: {
if (isLedgerRequest(message.data)) {
logger.debug('🪪 -> 📒: walletToLedgerSubject', message.data)

return sendMessageWithConfirmation(
createMessage.walletToLedger(
'offScreen',
Expand All @@ -68,7 +66,6 @@ export const WalletConnectionMessageHandler = (input: {
),
).map(() => ({ sendConfirmation: false }))
} else if (isExtensionMessage(message.data)) {
logger.debug('Wallet to extension', message.data)
return sendMessageWithConfirmation(
createMessage.walletToExtension(
'offScreen',
Expand Down Expand Up @@ -100,6 +97,7 @@ export const WalletConnectionMessageHandler = (input: {
tabId,
),
)
.map(() => ({ sendConfirmation: true }))
}

// Message from dApp to wallet
Expand Down
26 changes: 25 additions & 1 deletion src/components/account/account.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { Account as AccountType } from '@radixdlt/radix-dapp-toolkit'
import { RefObject, createRef, useEffect } from 'react'

declare global {
namespace JSX {
interface IntrinsicElements {
'radix-account': {
ref: RefObject<HTMLElement>
label: string
address: string
appearanceId: number
Expand All @@ -12,9 +14,31 @@ declare global {
}
}

export const Account = ({ account }: { account: AccountType }) => {
export const Account = ({
account,
onLinkClick,
}: {
account: AccountType
onLinkClick?: (ev: CustomEvent) => void
}) => {
const ref = createRef<HTMLElement>()

useEffect(() => {
if (!ref.current || !onLinkClick) return

ref.current.addEventListener('onLinkClick', onLinkClick as EventListener)

return () => {
if (!ref.current || !onLinkClick) return
ref.current.removeEventListener(
'onLinkClick',
onLinkClick as EventListener,
)
}
}, [])
return (
<radix-account
ref={ref}
label={account.label}
address={account.address}
appearanceId={account.appearanceId}
Expand Down
21 changes: 19 additions & 2 deletions src/components/linked-wallet/shared-accounts.tsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,38 @@
import ChevronDown from './chevron-down.svg'
import { Account as AccountType } from '@radixdlt/radix-dapp-toolkit'
import {
Account as AccountType,
RadixNetworkConfigById,
} from '@radixdlt/radix-dapp-toolkit'
import { Account } from 'components/account/account'
import { Box, Collapse } from '@mui/material'
import { useState } from 'react'
import { parseAddress } from 'utils/parse-address'

export const SharedAccounts = (props: {
accounts?: AccountType[]
isJustLinked?: boolean
}) => {
const [isCollapsed, setIsCollapsed] = useState(!props.isJustLinked)

const onLinkClick = async (e: CustomEvent) => {
if (e.detail.type === 'account' && e.detail.data) {
const { networkId } = parseAddress(e.detail.data)
const dashboardUrl = RadixNetworkConfigById[networkId].dashboardUrl

window.open([dashboardUrl, 'account', e.detail.data].join('/'), '_blank')
}
}

return (
<Box>
<Collapse in={!isCollapsed}>
<Box display="flex" flexDirection="column" gap="8px">
{props.accounts?.map((account) => (
<Account key={account.address} account={account} />
<Account
key={account.address}
account={account}
onLinkClick={onLinkClick}
/>
))}
</Box>
</Collapse>
Expand Down
1 change: 0 additions & 1 deletion src/pairing/state/connections.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,6 @@ export const useConnectionsClient = () => {
)

useEffect(() => {
logger.debug('Connections updated', connections)
setConnectionsClient(ConnectionsClient(connections))
}, [connections])

Expand Down
6 changes: 5 additions & 1 deletion src/utils/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,9 @@ export const logger = new Logger({
})

logger.attachTransport((logObj) => {
sendMessage(createMessage.log(logObj))
try {
sendMessage(createMessage.log(logObj))
} catch (error) {
console.error('Error sending log message', error)
}
})
53 changes: 53 additions & 0 deletions src/utils/parse-address.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { parseAddress } from './parse-address'

describe('parse address', () => {
const tests: [string, { networkId: number; type: string }][] = [
[
'account_tdx_2_129449mktvws4ww6wyww0dt85fn7md383cdq58307ayfz7g0n9vznfa',
{ networkId: 2, type: 'account' },
],
[
'account_tdx_2_128ex28rgvj4nqsqs7vtha0upknrpspzanfr95t6j6nss225dc47nu4',
{ networkId: 2, type: 'account' },
],
[
'resource_rdx1tknxxxxxxxxxradxrdxxxxxxxxx009923554798xxxxxxxxxradxrd',
{
networkId: 1,
type: 'resource',
},
],
[
'account_rdx12xezaw0gn9yhld6kplkk3ah7h6y48qgrmjr5e76krxq9hgws4junpr',
{
networkId: 1,
type: 'account',
},
],
[
'account_tdx_21_128wkep7c2mtdv5d0vvj23kp0rreud09384gru64w992pkmqga0nr87',
{
type: 'account',
networkId: 21,
},
],
[
'account_sim1cyyavav59dl55jur4eyxqz9wqyjycp2aua9dzduflfeefrfl623wgc',
{
networkId: 242,
type: 'account',
},
],
]
it('should parse address', () => {
tests.forEach(([address, expected]) => {
expect(parseAddress(address)).toEqual(expected)
})
})

it('should throw error on invalid address', () => {
expect(() => parseAddress('invalid')).toThrowError(
'Invalid address invalid',
)
})
})
19 changes: 19 additions & 0 deletions src/utils/parse-address.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
export const parseAddress = (
address: string,
): { networkId: number; type: string } => {
const match = address.match(/^([a-z]+)_(rdx|sim|tdx_[\d]+_)1(?:[a-z0-9]+)$/)

if (!match) {
throw new Error(`Invalid address ${address}`)
}

const [, type, network] = match

const networkId =
network === 'rdx' ? 1 : network === 'sim' ? 242 : network.split('_')[1]

return {
networkId: Number(networkId),
type,
}
}

0 comments on commit c183056

Please sign in to comment.