Skip to content

Commit

Permalink
Merge pull request #248 from radixdlt/fix-extension-options
Browse files Browse the repository at this point in the history
fix: save hex instead of uint8array
  • Loading branch information
dawidsowardx authored Apr 16, 2024
2 parents 10b6574 + 19773e9 commit e1bb37c
Show file tree
Hide file tree
Showing 24 changed files with 192 additions and 287 deletions.
5 changes: 3 additions & 2 deletions src/chrome/background/background.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ import { RadixNetworkConfigById } from '@radixdlt/babylon-gateway-api-sdk'
import { openRadixDevToolsPage } from './open-radix-dev-tools-page'
import { sendMessage } from 'chrome/messages/send-message'
import { Connections } from 'pairing/state/connections'
import { createTab } from 'chrome/helpers/create-tab'
import { getExtensionOptions, setConnectorExtensionOptions } from 'options'

const logger = utilsLogger.getSubLogger({ name: 'background' })
Expand All @@ -38,7 +37,9 @@ const handleOnInstallExtension = async () => {
} catch (err) {}
}

getExtensionOptions().map(setConnectorExtensionOptions)
getExtensionOptions()
.andThen(setConnectorExtensionOptions)
.mapErr(() => logger.error('Failed to set extension options'))
}

const handleStorageChange = (
Expand Down
18 changes: 17 additions & 1 deletion src/chrome/background/message-handler.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { closePopup as closePopupFn } from 'chrome/helpers/close-popup'
import { openParingPopup as openParingPopupFn } from 'chrome/helpers/open-pairing-popup'
import { errAsync, okAsync, ResultAsync } from 'neverthrow'
import { errAsync, ok, okAsync, ResultAsync } from 'neverthrow'
import { AppLogger } from 'utils/logger'
import {
messageDiscriminator,
Expand All @@ -24,6 +24,7 @@ import {
import { getExtensionOptions } from 'options'
import { chromeLocalStore } from 'chrome/helpers/chrome-local-store'
import { RadixNetworkConfigById } from '@radixdlt/babylon-gateway-api-sdk'
import { ConnectionsClient } from 'pairing/state/connections'

export type BackgroundMessageHandler = ReturnType<
typeof BackgroundMessageHandler
Expand Down Expand Up @@ -213,6 +214,21 @@ export const BackgroundMessageHandler =
return okAsync({ sendConfirmation: false })
}

case messageDiscriminator.walletToExtension:
if (message.data?.discriminator === 'accountList') {
return getConnections()
.map((connections) =>
ConnectionsClient(connections).updateAccounts(
message.walletPublicKey,
message.data.accounts,
),
)
.map(() => ({ sendConfirmation: false }))
.mapErr(() => ({ reason: 'failedToUpdateAccounts' }))
}

return okAsync({ sendConfirmation: false })

case messageDiscriminator.walletToLedger:
return ledgerTabWatcher
.restoreInitial()
Expand Down
4 changes: 3 additions & 1 deletion src/chrome/dev-tools/components/WalletSimulator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
getSignEd25519TransactionPayload,
getSignSecp256k1TransactionPayload,
getDeriveAndDisplayPayload,
getAccountListMessage,
} from '../example'
import { getExtensionOptions } from 'options'
import { getConnections } from 'chrome/helpers/get-connections'
Expand All @@ -31,6 +32,7 @@ export const WalletSimulator = () => {
'Sign TX (Curve25519)': getSignEd25519TransactionPayload(),
'Sign Auth (Curve25519)': getSignEd222519ChallengePayload(),
'Sign Auth (Secp256k1)': getSignSecp256k1ChallengePayload(),
'Account List Message': getAccountListMessage(),
}

useEffect(() => {
Expand Down Expand Up @@ -67,7 +69,7 @@ export const WalletSimulator = () => {
})

getConnections().map((connections) => {
const firstConnection = connections && connections?.[0]
const firstConnection = connections && Object.values(connections)[0]
if (firstConnection) {
connectorClient.setConnectionPassword(
Buffer.from(firstConnection.password, 'hex'),
Expand Down
20 changes: 20 additions & 0 deletions src/chrome/dev-tools/example.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,3 +128,23 @@ export const getSignSecp256k1ChallengePayload = () =>
derivationPath: 'm/44H/1022H/10H/525H/1238H',
},
])

export const getAccountListMessage = () => {
return {
discriminator: 'accountList',
accounts: [
{
label: 'My Main Account',
address:
'account_rdx12y4l35lh2543nff9pyyzvsh64ssu0dv6fq20gg8suslwmjvkylejgj',
appearanceId: 0,
},
{
label: 'My Savings Account',
address:
'account_tdx_2_12y9as9p2utmxf9zc9gvsalvd6s69zump236ng3ztvfkjngm757zsa3',
appearanceId: 1,
},
],
}
}
12 changes: 11 additions & 1 deletion src/chrome/messages/_types.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { MessageLifeCycleEvent } from 'chrome/dapp/_types'
import { LedgerRequest, LedgerResponse } from 'ledger/schemas'
import {
AccountListMessage,
LedgerRequest,
LedgerResponse,
} from 'ledger/schemas'
import { ResultAsync } from 'neverthrow'
import { ILogObjMeta } from 'tslog/dist/types/interfaces'
import { ILogObj } from 'tslog'
Expand All @@ -20,6 +24,7 @@ export const messageDiscriminator = {
extensionStatus: 'extensionStatus',
ledgerResponse: 'ledgerResponse',
walletToLedger: 'walletToLedger',
walletToExtension: 'walletToExtension',
walletResponse: 'walletResponse',
toContentScript: 'toContentScript',
openParingPopup: 'openParingPopup',
Expand All @@ -45,6 +50,7 @@ export const messageSource = {
ledger: 'ledger',
wallet: 'wallet',
any: 'any',
popup: 'popup',
} as const

export type MessageSource = keyof typeof messageSource
Expand Down Expand Up @@ -170,6 +176,10 @@ export type Messages = {
MessageDiscriminator['ledgerResponse'],
{ data: LedgerResponse }
>
[messageDiscriminator.walletToExtension]: MessageBuilder<
MessageDiscriminator['walletToExtension'],
{ data: AccountListMessage; walletPublicKey: string }
>
[messageDiscriminator.walletToLedger]: MessageBuilder<
MessageDiscriminator['walletToLedger'],
{ data: LedgerRequest }
Expand Down
17 changes: 16 additions & 1 deletion src/chrome/messages/create-message.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { ConnectorExtensionOptions } from './../../options/index'
import { LedgerRequest, LedgerResponse } from 'ledger/schemas'
import {
AccountListMessage,
LedgerRequest,
LedgerResponse,
} from 'ledger/schemas'
import {
Messages,
ConfirmationMessageError,
Expand Down Expand Up @@ -123,6 +127,17 @@ export const createMessage = {
messageId: crypto.randomUUID(),
data: message,
}),
walletToExtension: (
source: MessageSource,
message: AccountListMessage,
walletPublicKey: string,
): Messages['walletToExtension'] => ({
source,
discriminator: messageDiscriminator.walletToExtension,
messageId: crypto.randomUUID(),
walletPublicKey,
data: message,
}),
ledgerResponse: (message: LedgerResponse): Messages['ledgerResponse'] => ({
source: 'ledger',
discriminator: messageDiscriminator.ledgerResponse,
Expand Down
5 changes: 3 additions & 2 deletions src/chrome/messages/message-client.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { SessionRouter } from 'chrome/offscreen/session-router'
const logger = new Logger()

const dAppRequestQueue = { add: () => okAsync(undefined) } as any
const ledgerToWalletQueue = { add: () => okAsync(undefined) } as any
const extensionToWalletQueue = { add: () => okAsync(undefined) } as any
const incomingWalletMessageQueue = { add: () => okAsync(undefined) } as any

const createInput = (subjects: MessageSubjects) => ({
Expand Down Expand Up @@ -45,7 +45,7 @@ const createTestHelper = ({
walletConnectionMessageClient = MessageClient(
WalletConnectionMessageHandler({
dAppRequestQueue,
ledgerToWalletQueue,
extensionToWalletQueue,
incomingWalletMessageQueue,
messagesRouter,
sessionRouter: SessionRouter(),
Expand All @@ -67,6 +67,7 @@ const createTestHelper = ({
password: '',
walletName: 'Test Mock Wallet',
walletPublicKey: 'mock',
accounts: [],
},
logger,
messagesRouter,
Expand Down
18 changes: 13 additions & 5 deletions src/chrome/offscreen/wallet-connection/message-handler.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { createMessage } from 'chrome/messages/create-message'
import { MessagesRouter } from 'chrome/offscreen/wallet-connection/messages-router'
import { ResultAsync, errAsync, ok, okAsync } from 'neverthrow'
import { ResultAsync, errAsync, okAsync } from 'neverthrow'
import { Queue } from 'queues/queue'
import { AppLogger, logger as appLogger } from 'utils/logger'

import { LedgerResponse, isLedgerRequest } from 'ledger/schemas'
import { sendMessage } from 'chrome/helpers/send-message'
import { WalletInteractionWithOrigin } from '@radixdlt/radix-connect-schemas'
Expand All @@ -22,15 +21,15 @@ export type WalletConnectionMessageHandler = ReturnType<
>
export const WalletConnectionMessageHandler = (input: {
dAppRequestQueue: Queue<WalletInteractionWithOrigin>
ledgerToWalletQueue: Queue<LedgerResponse>
extensionToWalletQueue: Queue<LedgerResponse>
incomingWalletMessageQueue: Queue<any>
messagesRouter: MessagesRouter
sessionRouter: SessionRouter
logger?: AppLogger
walletPublicKey: string
}): MessageHandler => {
const dAppRequestQueue = input.dAppRequestQueue
const ledgerToWalletQueue = input.ledgerToWalletQueue
const extensionToWalletQueue = input.extensionToWalletQueue
const incomingWalletMessageQueue = input.incomingWalletMessageQueue
const messagesRouter = input.messagesRouter
const sessionRouter = input.sessionRouter
Expand All @@ -50,6 +49,15 @@ export const WalletConnectionMessageHandler = (input: {
return sendMessageWithConfirmation(
createMessage.walletToLedger('offScreen', message.data),
).map(() => ({ sendConfirmation: false }))
} else if (['accountList'].includes(message.data.discriminator)) {
logger.debug('wallet to extension', message.data)
return sendMessageWithConfirmation(
createMessage.walletToExtension(
'offScreen',
message.data,
walletPublicKey,
),
).map(() => ({ sendConfirmation: false }))
} else {
incomingWalletMessageQueue.add(
message.data,
Expand Down Expand Up @@ -138,7 +146,7 @@ export const WalletConnectionMessageHandler = (input: {
})

case messageDiscriminator.ledgerResponse:
return ledgerToWalletQueue
return extensionToWalletQueue
.add(message.data, message.data.interactionId)
.map(() => ({ sendConfirmation: false }))

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,8 @@ export const WalletConnectionClient = ({
),
})

const ledgerToWalletQueue = Queue<LedgerResponse>({
key: 'ledgerToWallet',
const extensionToWalletQueue = Queue<LedgerResponse>({
key: 'extensionToWalletQueue',
logger,
worker: Worker((job) =>
connectorClient.sendMessage(job.data, {
Expand Down Expand Up @@ -117,10 +117,10 @@ export const WalletConnectionClient = ({
subscription.add(
connectorClient.connected$.subscribe((connected) => {
if (connected) {
ledgerToWalletQueue.start()
extensionToWalletQueue.start()
dAppRequestQueue.start()
} else {
ledgerToWalletQueue.stop()
extensionToWalletQueue.stop()
dAppRequestQueue.stop()
}
}),
Expand All @@ -144,7 +144,7 @@ export const WalletConnectionClient = ({
const messageClient = MessageClient(
WalletConnectionMessageHandler({
dAppRequestQueue,
ledgerToWalletQueue,
extensionToWalletQueue,
incomingWalletMessageQueue,
messagesRouter,
sessionRouter,
Expand All @@ -163,7 +163,7 @@ export const WalletConnectionClient = ({
subscription.unsubscribe()
connectorClient.destroy()
dAppRequestQueue.destroy()
ledgerToWalletQueue.destroy()
extensionToWalletQueue.destroy()
incomingWalletMessageQueue.destroy()
chrome.runtime.onMessage.removeListener(chromeMessageListener)
},
Expand Down
10 changes: 1 addition & 9 deletions src/components/linked-wallet/linked-wallet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,12 @@ export const LinkedWallet = ({
accounts,
onRenameWalletLink,
onForgetWallet,
onRequestAccountList,
}: {
name: string
accounts: Account[]
onRenameWalletLink: () => void
onForgetWallet: () => void
onRequestAccountList: () => void
}) => {
const sharingAccountsEnabled = false // TODO: enable when wallet ready
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null)
const open = Boolean(anchorEl)
const handleClick = (event: React.MouseEvent<HTMLElement>) => {
Expand Down Expand Up @@ -117,12 +114,7 @@ export const LinkedWallet = ({
</MenuItem>
</Menu>
</Box>
{sharingAccountsEnabled && (
<SharedAccounts
accounts={accounts}
onRequestAccountList={onRequestAccountList}
/>
)}
<SharedAccounts accounts={accounts} />
</Box>
)
}
12 changes: 2 additions & 10 deletions src/components/linked-wallet/shared-accounts.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
import { Button } from 'components/button'
import ChevronDown from './chevron-down.svg'
import { Account as AccountType } from '@radixdlt/radix-connect-schemas'
import { Account } from 'components/account/account'
import { Box, Collapse } from '@mui/material'
import { useState } from 'react'

export const SharedAccounts = (props: {
accounts?: AccountType[]
onRequestAccountList: () => void
}) => {
export const SharedAccounts = (props: { accounts?: AccountType[] }) => {
const [isCollapsed, setIsCollapsed] = useState(true)

return (
Expand All @@ -32,11 +28,7 @@ export const SharedAccounts = (props: {
>
<img src={ChevronDown} />
</button>
) : (
<Button secondary full onClick={props.onRequestAccountList}>
Request Account List
</Button>
)}
) : null}
</Box>
</Box>
)
Expand Down
35 changes: 35 additions & 0 deletions src/components/spinner/spinner.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
.loading-spinner-container {
display: flex;
}

button.gradient > .loading-spinner {
border-right-color: #000;
border-left-color: color-mix(in srgb, #000 30%, transparent);
border-top-color: color-mix(in srgb, #000 30%, transparent);
border-bottom-color: color-mix(in srgb, #000 30%, transparent);
}

.loading-spinner {
width: 22px;
height: 22px;
min-width: 22px;
min-height: 22px;
border: 2px solid #000;
border-left-color: color-mix(in srgb, #000 30%, transparent);
border-top-color: color-mix(in srgb, #000 30%, transparent);
border-bottom-color: color-mix(in srgb, #000 30%, transparent);
border-radius: 50%;
display: inline-block;
box-sizing: border-box;
animation: rotation 1s linear infinite;
align-self: center;
}

@keyframes rotation {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
8 changes: 8 additions & 0 deletions src/components/spinner/spinner.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import './spinner.scss'
export const Spinner = () => {
return (
<div className="loading-spinner-container">
<div className="loading-spinner"></div>
</div>
)
}
Loading

0 comments on commit e1bb37c

Please sign in to comment.