Skip to content

Commit

Permalink
feat: multi wallet support
Browse files Browse the repository at this point in the history
  • Loading branch information
dawidsowardx committed Mar 8, 2024
1 parent 127716a commit 01c73aa
Show file tree
Hide file tree
Showing 13 changed files with 65 additions and 64 deletions.
8 changes: 4 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
"@mui/material": "^5.14.0",
"@radixdlt/babylon-gateway-api-sdk": "^1.2.7",
"@radixdlt/connect-button": "^1.0.1",
"@radixdlt/radix-connect-schemas": "^1.3.0-cap36.1",
"@radixdlt/radix-connect-schemas": "^1.3.0-cap36.4",
"@radixdlt/radix-connect-webrtc": "^1.2.1",
"@stitches/react": "^1.2.8",
"@types/blake2b": "^2.1.0",
Expand Down
14 changes: 4 additions & 10 deletions src/chrome/background/background.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ 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 { SessionRouter } from 'chrome/offscreen/session-router'
import { createTab } from 'chrome/helpers/create-tab'
import { getExtensionOptions, setConnectorExtensionOptions } from 'options'

const logger = utilsLogger.getSubLogger({ name: 'background' })

Expand All @@ -37,6 +37,8 @@ const handleOnInstallExtension = async () => {
}
} catch (err) {}
}

getExtensionOptions().map(setConnectorExtensionOptions)
}

const handleStorageChange = (
Expand Down Expand Up @@ -123,15 +125,7 @@ chrome.storage.onChanged.addListener(handleStorageChange)
chrome.action.onClicked.addListener(openParingPopup)
chrome.runtime.onInstalled.addListener(handleOnInstallExtension)

if (isDevMode) {
chrome.runtime.onInstalled.addListener(() => {
createTab(
`chrome-extension://${chrome.runtime.id}/src/chrome/offscreen/index.html`,
)
})
} else {
createOffscreen()
}
createOffscreen()

chrome.runtime.onStartup.addListener(() => {
logger.debug('onStartup')
Expand Down
22 changes: 11 additions & 11 deletions src/chrome/background/message-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,6 @@ export const BackgroundMessageHandler =
message: Message,
sendMessageWithConfirmation: SendMessageWithConfirmation,
): MessageHandlerOutput => {
if (message?.discriminator !== 'log')
logger?.debug('incoming bg message', message.discriminator)
switch (message?.discriminator) {
case messageDiscriminator.getExtensionOptions:
return getExtensionOptions()
Expand Down Expand Up @@ -132,11 +130,21 @@ export const BackgroundMessageHandler =
.mapErr(() => ({ reason: 'failedToFocusLedgerTab' }))
}

case messageDiscriminator.removeSessionId: {
chromeLocalStore.getSingleItem('sessionRouter').andThen((data) => {
if (!data) {
return okAsync(undefined)
}

const { [message.sessionId]: _, ...rest } = data
return chromeLocalStore.setSingleItem('sessionRouter', rest)
})
}

case messageDiscriminator.walletResponse: {
const sessionId = message.data?.metadata?.sessionId
const clientId = message.data?.metadata?.clientId

logger?.debug('bg knows about', sessionId, clientId, message.data)
if (
sessionId &&
clientId &&
Expand All @@ -145,7 +153,6 @@ export const BackgroundMessageHandler =
) {
chromeLocalStore.getSingleItem('sessionRouter').map((data) => {
if (!data) {
logger?.debug('adding sessionId->clientId mapping')
return chromeLocalStore.setSingleItem('sessionRouter', {
[sessionId]: clientId,
})
Expand All @@ -156,14 +163,11 @@ export const BackgroundMessageHandler =
`sessionRouter has clientId ${data[sessionId]} for ${sessionId} but we've just had a response from ${clientId}`,
)
} else if (!data[sessionId]) {
logger?.debug('adding sessionId->clientId mapping')
return chromeLocalStore.setSingleItem('sessionRouter', {
...data,
[sessionId]: clientId,
})
}

logger?.debug('not updating clientId nor sessionId')
})
}

Expand Down Expand Up @@ -210,10 +214,6 @@ export const BackgroundMessageHandler =
}))
}

case messageDiscriminator.addToSessionRouter: {
logger?.debug(message)
}

case messageDiscriminator.dAppRequest: {
hasConnections().map((hasConnections) => {
if (hasConnections) {
Expand Down
8 changes: 6 additions & 2 deletions src/chrome/content-script/content-script.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,12 @@ const handleExtensionInteraction = async (
extensionInteraction: ExtensionInteraction,
) => {
switch (extensionInteraction.discriminator) {
case 'removeSessionId':
await sendMessage(
createMessage.removeSessionId(extensionInteraction.sessionId),
)
break

case 'openPopup':
await sendMessage(createMessage.openParingPopup())
break
Expand Down Expand Up @@ -103,8 +109,6 @@ chrome.storage.onChanged.addListener(
},
)

logger.debug('content-script loaded')

hasConnections().map((hasConnections) => {
sendMessageToDapp(createMessage.extensionStatus(hasConnections))
})
4 changes: 2 additions & 2 deletions src/chrome/messages/_types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export const messageDiscriminator = {
getExtensionOptions: 'getExtensionOptions',
getSessionRouterData: 'getSessionRouterData',
setSessionRouterData: 'setSessionRouterData',
addToSessionRouter: 'addToSessionRouter',
removeSessionId: 'removeSessionId',
dAppRequest: 'dAppRequest',
closeLedgerTab: 'closeLedgerTab',
focusLedgerTab: 'focusLedgerTab',
Expand Down Expand Up @@ -156,7 +156,7 @@ export type Messages = {
{ data: Record<string, any> }
>
[messageDiscriminator.dAppRequest]: MessageBuilder<
MessageDiscriminator[typeof messageDiscriminator.dAppRequest],
MessageDiscriminator['dAppRequest'],
{ data: WalletInteractionWithOrigin }
>
[messageDiscriminator.walletMessage]: MessageBuilder<
Expand Down
8 changes: 6 additions & 2 deletions src/chrome/messages/create-message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ export const createMessage = {
discriminator: messageDiscriminator.setSessionRouterData,
data,
}),
removeSessionId: (sessionId: string) => ({
discriminator: messageDiscriminator.removeSessionId,
sessionId,
}),
extensionStatus: (isWalletLinked: boolean) => ({
eventType: 'extensionStatus',
isExtensionAvailable: true,
Expand Down Expand Up @@ -85,9 +89,9 @@ export const createMessage = {
dAppRequest: (
source: MessageSource,
data: WalletInteractionWithOrigin,
): Messages[typeof messageDiscriminator.dAppRequest] => ({
): Messages['dAppRequest'] => ({
source,
discriminator: messageDiscriminator.dAppRequest,
discriminator: 'dAppRequest',
messageId: crypto.randomUUID(),
data,
}),
Expand Down
1 change: 0 additions & 1 deletion src/chrome/offscreen/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,5 @@
<body>
<div id="logs"></div>
<script type="module" src="/src/chrome/offscreen/offscreen.ts"></script>

</body>
</html>
10 changes: 0 additions & 10 deletions src/chrome/offscreen/session-router.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import { ok } from 'neverthrow'

export type SessionRouter = ReturnType<typeof SessionRouter>

export type SessionId = string
Expand All @@ -8,13 +6,6 @@ export type ClientId = string
export const SessionRouter = () => {
const store = new Map<SessionId, ClientId>()

const add = (sessionId: SessionId, clientId: ClientId) => {
store.set(sessionId, clientId)
return ok(undefined)
}

const removeBySessionId = (sessionId: SessionId) => store.delete(sessionId)

const getClientId = (sessionId: SessionId) => store.get(sessionId)

const refreshStore = (data: Record<SessionId, ClientId>) => {
Expand All @@ -28,6 +19,5 @@ export const SessionRouter = () => {
refreshStore,
getClientId,
store,
removeBySessionId,
}
}
1 change: 1 addition & 0 deletions src/chrome/offscreen/wallet-connection/factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export const walletConnectionClientFactory = (input: {
target: 'wallet',
isInitiator: config.webRTC.isInitiator,
logger,
negotiationTimeout: 10_000,
})

const client = WalletConnectionClient({
Expand Down
8 changes: 0 additions & 8 deletions src/chrome/offscreen/wallet-connection/message-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,6 @@ export const WalletConnectionMessageHandler = (input: {
const clientIdForSessionId = sessionRouter.getClientId(
arbitraryData?.sessionId,
)
logger.info('clientIdForSessionId', clientIdForSessionId)
if (walletInteraction.items.discriminator === 'cancelRequest') {
return dAppRequestQueue
.cancel(interactionId)
Expand All @@ -90,14 +89,7 @@ export const WalletConnectionMessageHandler = (input: {
)
}

logger.debug(
'almost adding to request queue',
clientId,
arbitraryData?.sessionId,
)

if ([undefined, clientId].includes(clientIdForSessionId)) {
logger.debug('add')
return dAppRequestQueue.add(
{
items,
Expand Down
15 changes: 14 additions & 1 deletion src/pairing/components/connection-password.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,15 @@ import { Link } from 'react-router-dom'

export const ConnectionPassword = ({
connectionPassword,
clientId,
purpose,
}: {
connectionPassword?: string
clientId?: string
purpose?: 'general'
}) => {
if (!connectionPassword) return null

const connectionsClient = useConnectionsClient()
return (
<>
Expand All @@ -22,8 +27,16 @@ export const ConnectionPassword = ({
Scan the QR code with the Radix Wallet app on your mobile phone to start
using it with dApps in this web browser.
</PairingHeader>

<Box mt="3xl" p="none">
<QrCode value={connectionPassword} data-testid="custom-element" />
<QrCode
value={JSON.stringify({
password: connectionPassword,
clientId,
purpose,
})}
data-testid="custom-element"
/>
</Box>

<Box textAlign="center">
Expand Down
28 changes: 16 additions & 12 deletions src/pairing/pairing.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { logger } from 'utils/logger'
import { config, radixConnectConfig } from 'config'
import { useConnectionsClient } from './state/connections'
import { useConnectorOptions } from './state/options'
import { Subscription, filter, map, tap, withLatestFrom } from 'rxjs'
import { Subscription, filter, map, withLatestFrom } from 'rxjs'
import { useNavigate } from 'react-router-dom'

export const Pairing = () => {
Expand All @@ -15,10 +15,12 @@ export const Pairing = () => {
const connectionsClient = useConnectionsClient()
const connectorOptions = useConnectorOptions()
const navigate = useNavigate()

const [clientId, setClientId] = useState<string>()
useEffect(() => {
if (!connectorOptions) return

setClientId(connectorOptions.clientId)

const connectorClient = ConnectorClient({
source: 'extension',
target: 'wallet',
Expand All @@ -41,12 +43,6 @@ export const Pairing = () => {
filter((message) => message.discriminator === 'linkClient'),
)

const sendLinkClientInteraction = connectorClient.sendMessage({
discriminator: 'linkClient',
clientId: connectorOptions.clientId,
purpose: 'general',
})

const hexConnectionPassword$ = connectorClient.connectionPassword$.pipe(
filter(Boolean),
map((buffer) => buffer.toString('hex')),
Expand All @@ -62,12 +58,12 @@ export const Pairing = () => {
connectorClient.connected$
.pipe(
filter(Boolean),
tap(() => {}),
withLatestFrom(hexConnectionPassword$),
withLatestFrom(linkClientInteraction$),
)
.subscribe(([, password]) => {
.subscribe(([[, password], interaction]) => {
connectionsClient
.addOrUpdate(password, crypto.randomUUID())
.addOrUpdate(password, interaction.clientId)
.map(() => connectorClient.disconnect())
.map(() => navigate('/'))
}),
Expand All @@ -81,5 +77,13 @@ export const Pairing = () => {
}
}, [setConnectionPassword, connectorOptions, connectionsClient])

return <ConnectionPassword connectionPassword={connectionPassword} />
return (
<>
<ConnectionPassword
connectionPassword={connectionPassword}
purpose="general"
clientId={clientId}
/>
</>
)
}

0 comments on commit 01c73aa

Please sign in to comment.