Skip to content

Commit

Permalink
feat: adjust account list message format
Browse files Browse the repository at this point in the history
  • Loading branch information
dawidsowardx committed Apr 12, 2024
1 parent 9072f5a commit 19773e9
Show file tree
Hide file tree
Showing 12 changed files with 31 additions and 170 deletions.
2 changes: 1 addition & 1 deletion src/chrome/background/message-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ export const BackgroundMessageHandler =
}

case messageDiscriminator.walletToExtension:
if (message.data?.discriminator === 'accountListResponse') {
if (message.data?.discriminator === 'accountList') {
return getConnections()
.map((connections) =>
ConnectionsClient(connections).updateAccounts(
Expand Down
6 changes: 2 additions & 4 deletions src/chrome/dev-tools/components/WalletSimulator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@ import {
getSignEd25519TransactionPayload,
getSignSecp256k1TransactionPayload,
getDeriveAndDisplayPayload,
getRejectAccountListRequestPayload,
getAccountListResponsePayload,
getAccountListMessage,
} from '../example'
import { getExtensionOptions } from 'options'
import { getConnections } from 'chrome/helpers/get-connections'
Expand All @@ -33,8 +32,7 @@ export const WalletSimulator = () => {
'Sign TX (Curve25519)': getSignEd25519TransactionPayload(),
'Sign Auth (Curve25519)': getSignEd222519ChallengePayload(),
'Sign Auth (Secp256k1)': getSignSecp256k1ChallengePayload(),
'Reject Account List Request': getRejectAccountListRequestPayload(),
'Account List Response': getAccountListResponsePayload(),
'Account List Message': getAccountListMessage(),
}

useEffect(() => {
Expand Down
20 changes: 9 additions & 11 deletions src/chrome/dev-tools/example.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,24 +129,22 @@ export const getSignSecp256k1ChallengePayload = () =>
},
])

export const getRejectAccountListRequestPayload = () => {
export const getAccountListMessage = () => {
return {
interactionId: '',
discriminator: 'accountListRejectedResponse',
}
}

export const getAccountListResponsePayload = () => {
return {
interactionId: '',
discriminator: 'accountListResponse',
discriminator: 'accountList',
accounts: [
{
label: 'Account 1',
label: 'My Main Account',
address:
'account_rdx12y4l35lh2543nff9pyyzvsh64ssu0dv6fq20gg8suslwmjvkylejgj',
appearanceId: 0,
},
{
label: 'My Savings Account',
address:
'account_tdx_2_12y9as9p2utmxf9zc9gvsalvd6s69zump236ng3ztvfkjngm757zsa3',
appearanceId: 1,
},
],
}
}
5 changes: 2 additions & 3 deletions src/chrome/messages/_types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { MessageLifeCycleEvent } from 'chrome/dapp/_types'
import {
AccountListResponseInteraction,
AccountListMessage,
LedgerRequest,
LedgerResponse,
} from 'ledger/schemas'
Expand All @@ -14,7 +14,6 @@ export const messageDiscriminator = {
getConnections: 'getConnections',
setConnections: 'setConnections',
setRadixConnectConfiguration: 'setRadixConnectConfiguration',
accountListRequestInteraction: 'accountListRequestInteraction',
getExtensionOptions: 'getExtensionOptions',
getSessionRouterData: 'getSessionRouterData',
setSessionRouterData: 'setSessionRouterData',
Expand Down Expand Up @@ -179,7 +178,7 @@ export type Messages = {
>
[messageDiscriminator.walletToExtension]: MessageBuilder<
MessageDiscriminator['walletToExtension'],
{ data: AccountListResponseInteraction; walletPublicKey: string }
{ data: AccountListMessage; walletPublicKey: string }
>
[messageDiscriminator.walletToLedger]: MessageBuilder<
MessageDiscriminator['walletToLedger'],
Expand Down
13 changes: 2 additions & 11 deletions src/chrome/messages/create-message.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { ConnectorExtensionOptions } from './../../options/index'
import {
AccountListResponseInteraction,
AccountListMessage,
LedgerRequest,
LedgerResponse,
} from 'ledger/schemas'
Expand All @@ -26,15 +26,6 @@ export const createMessage = {
discriminator: messageDiscriminator.getSessionRouterData,
source: 'offscreen',
}),
sendAccountListRequest: (walletPublicKey: string, interactionId: string) => ({
discriminator: messageDiscriminator.accountListRequestInteraction,
source: 'popup',
messageId: crypto.randomUUID(),
data: {
walletPublicKey,
interactionId,
},
}),
setSessionRouterData: (data: Record<SessionId, WalletPublicKey>) => ({
discriminator: messageDiscriminator.setSessionRouterData,
data,
Expand Down Expand Up @@ -138,7 +129,7 @@ export const createMessage = {
}),
walletToExtension: (
source: MessageSource,
message: AccountListResponseInteraction,
message: AccountListMessage,
walletPublicKey: string,
): Messages['walletToExtension'] => ({
source,
Expand Down
30 changes: 4 additions & 26 deletions src/chrome/offscreen/wallet-connection/message-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,7 @@ import { MessagesRouter } from 'chrome/offscreen/wallet-connection/messages-rout
import { ResultAsync, errAsync, okAsync } from 'neverthrow'
import { Queue } from 'queues/queue'
import { AppLogger, logger as appLogger } from 'utils/logger'

import {
AccountListRequestInteraction,
LedgerResponse,
isLedgerRequest,
} from 'ledger/schemas'
import { LedgerResponse, isLedgerRequest } from 'ledger/schemas'
import { sendMessage } from 'chrome/helpers/send-message'
import { WalletInteractionWithOrigin } from '@radixdlt/radix-connect-schemas'
import {
Expand All @@ -26,7 +21,7 @@ export type WalletConnectionMessageHandler = ReturnType<
>
export const WalletConnectionMessageHandler = (input: {
dAppRequestQueue: Queue<WalletInteractionWithOrigin>
extensionToWalletQueue: Queue<LedgerResponse | AccountListRequestInteraction>
extensionToWalletQueue: Queue<LedgerResponse>
incomingWalletMessageQueue: Queue<any>
messagesRouter: MessagesRouter
sessionRouter: SessionRouter
Expand Down Expand Up @@ -54,12 +49,8 @@ export const WalletConnectionMessageHandler = (input: {
return sendMessageWithConfirmation(
createMessage.walletToLedger('offScreen', message.data),
).map(() => ({ sendConfirmation: false }))
} else if (
['accountListResponse', 'accountListRejectedResponse'].includes(
message.data.discriminator,
)
) {
logger.debug('🪪 -> 📒: wallet to extension', message.data)
} else if (['accountList'].includes(message.data.discriminator)) {
logger.debug('wallet to extension', message.data)
return sendMessageWithConfirmation(
createMessage.walletToExtension(
'offScreen',
Expand Down Expand Up @@ -159,19 +150,6 @@ export const WalletConnectionMessageHandler = (input: {
.add(message.data, message.data.interactionId)
.map(() => ({ sendConfirmation: false }))

case messageDiscriminator.accountListRequestInteraction:
if (message.data.walletPublicKey === walletPublicKey) {
return extensionToWalletQueue
.add(
{
discriminator: 'accountListRequest',
interactionId: message.data.interactionId,
},
message.data.interactionId,
)
.map(() => ({ sendConfirmation: true }))
}

case messageDiscriminator.closeDappTab: {
const { tabId } = message
return messagesRouter
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
} from '@radixdlt/radix-connect-webrtc'
import { createMessage } from 'chrome/messages/create-message'
import { config } from 'config'
import { AccountListRequestInteraction, LedgerResponse } from 'ledger/schemas'
import { LedgerResponse } from 'ledger/schemas'
import { MessagesRouter } from 'chrome/offscreen/wallet-connection/messages-router'
import { Queue } from 'queues/queue'
import { AppLogger, logger as utilsLogger } from 'utils/logger'
Expand Down Expand Up @@ -76,9 +76,7 @@ export const WalletConnectionClient = ({
),
})

const extensionToWalletQueue = Queue<
LedgerResponse | AccountListRequestInteraction
>({
const extensionToWalletQueue = Queue<LedgerResponse>({
key: 'extensionToWalletQueue',
logger,
worker: Worker((job) =>
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 @@ -11,16 +11,12 @@ export const LinkedWallet = ({
name,
accounts,
onRenameWalletLink,
pendingAccountRequest,
onForgetWallet,
onRequestAccountList,
}: {
name: string
accounts: Account[]
pendingAccountRequest?: boolean | undefined
onRenameWalletLink: () => void
onForgetWallet: () => void
onRequestAccountList: () => void
}) => {
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null)
const open = Boolean(anchorEl)
Expand Down Expand Up @@ -118,11 +114,7 @@ export const LinkedWallet = ({
</MenuItem>
</Menu>
</Box>
<SharedAccounts
accounts={accounts}
pendingAccountRequest={pendingAccountRequest}
onRequestAccountList={onRequestAccountList}
/>
<SharedAccounts accounts={accounts} />
</Box>
)
}
19 changes: 2 additions & 17 deletions src/components/linked-wallet/shared-accounts.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +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'
import { Spinner } from 'components/spinner/spinner'

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

return (
Expand All @@ -34,16 +28,7 @@ export const SharedAccounts = (props: {
>
<img src={ChevronDown} />
</button>
) : (
<Button
secondary
full
onClick={props.onRequestAccountList}
disabled={props.pendingAccountRequest}
>
{props.pendingAccountRequest ? <Spinner /> : 'Request Account List'}
</Button>
)}
) : null}
</Box>
</Box>
)
Expand Down
31 changes: 3 additions & 28 deletions src/ledger/schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,38 +144,13 @@ export const SignatureOfSignerSchema = object({
signature: string(),
})

export type AccountListRequestInteraction = z.infer<
typeof AccountListRequestInteraction
>

export const AccountListRequestInteraction = object({
interactionId: string(),
discriminator: literal('accountListRequest'),
})

export type AccountListResponse = z.infer<typeof AccountListResponse>
export const AccountListResponse = object({
export type AccountListMessage = z.infer<typeof AccountListMessage>
export const AccountListMessage = object({
interactionId: string(),
discriminator: literal('accountListResponse'),
discriminator: literal('accountList'),
accounts: Account.array(),
})

export type AccountListRejectedResponse = z.infer<
typeof AccountListRejectedResponse
>
export const AccountListRejectedResponse = object({
interactionId: string(),
discriminator: literal('accountListRejectedResponse'),
})

export type AccountListResponseInteraction = z.infer<
typeof AccountListResponseInteraction
>
export const AccountListResponseInteraction = z.union([
AccountListResponse,
AccountListRejectedResponse,
])

export type LinkClientInteraction = z.infer<typeof LinkClientInteraction>
export const LinkClientInteraction = object({
discriminator: literal('linkClient'),
Expand Down
52 changes: 2 additions & 50 deletions src/pairing/components/connection-status.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,60 +2,27 @@ import { Box, Button } from '../../components'
import { PairingHeader } from './pairing-header'
import { useEffect, useState } from 'react'
import { LinkedWallet } from 'components/linked-wallet/linked-wallet'
import { Link, useNavigate, useSearchParams } from 'react-router-dom'
import { Link, useNavigate } from 'react-router-dom'
import { useConnectionsClient } from 'pairing/state/connections'
import { ForgetThisWallet } from './forget-this-wallet'
import { RenameWalletLink } from './rename-wallet-link'
import { sendMessage } from 'chrome/messages/send-message'
import { createMessage } from 'chrome/messages/create-message'
import { Message } from 'chrome/messages/_types'

export const ConnectionStatus = () => {
const navigate = useNavigate()
const [searchParams, setSearchParams] = useSearchParams()
const connectionsClient = useConnectionsClient()
const connections = connectionsClient.connections
const [pendingAccountRequest, setPendingAccountRequest] = useState<
Record<string, string>
>({})

const [connectionIdToForget, setConnectionIdToForget] = useState<string>('')
const [connectionIdToChangeName, setConnectionIdToChangeName] =
useState<string>('')

useEffect(() => {
if (searchParams.has('newWallet')) {
sendAccountListRequest(searchParams.get('newWallet') as string)
setSearchParams({})
}
}, [searchParams])

useEffect(() => {
if (connectionsClient.isLoading()) return
if (connectionsClient.hasNoConnections()) {
navigate('/pairing')
}
}, [connections])

useEffect(() => {
const handler = (message: Message) => {
console.log(message)
if (message.discriminator === 'walletToExtension') {
const interactionId = message.data.interactionId
if (pendingAccountRequest[message.walletPublicKey] === interactionId) {
setPendingAccountRequest({
...pendingAccountRequest,
[message.walletPublicKey]: '',
})
}
}
}
chrome.runtime.onMessage.addListener(handler)

return () => {
chrome.runtime.onMessage.removeListener(handler)
}
}, [pendingAccountRequest])

const forgetWallet = () => {
connectionsClient.remove(connectionIdToForget)
setConnectionIdToForget('')
Expand Down Expand Up @@ -89,19 +56,6 @@ export const ConnectionStatus = () => {
)
}

const sendAccountListRequest = (connectionId: string) => {
const interactionId = crypto.randomUUID()
if (pendingAccountRequest[connectionId]) return
setPendingAccountRequest({
...pendingAccountRequest,
[connectionId]: interactionId,
})

sendMessage(
createMessage.sendAccountListRequest(connectionId, interactionId),
)
}

return (
<>
<Box
Expand All @@ -121,9 +75,7 @@ export const ConnectionStatus = () => {
key={id}
accounts={connection.accounts}
name={connection.walletName}
pendingAccountRequest={!!pendingAccountRequest[id]}
onForgetWallet={() => setConnectionIdToForget(id)}
onRequestAccountList={() => sendAccountListRequest(id)}
onRenameWalletLink={() => setConnectionIdToChangeName(id)}
/>
))}
Expand Down
Loading

0 comments on commit 19773e9

Please sign in to comment.