Skip to content

Commit

Permalink
Merge pull request #696 from airgap-it/fix/app_switching
Browse files Browse the repository at this point in the history
fix: add app switching
  • Loading branch information
AndreasGassmann authored Jan 11, 2024
2 parents 70ed3c0 + e231b2a commit 2cc82ac
Show file tree
Hide file tree
Showing 5 changed files with 59 additions and 54 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { PeerInfoType, StorageKey } from '@airgap/beacon-types'
import { PeerInfoType } from '@airgap/beacon-types'
import { toHex, getHexHash, sealCryptobox } from '@airgap/beacon-utils'
import { convertPublicKeyToX25519, convertSecretKeyToX25519, KeyPair } from '@stablelib/ed25519'
import { clientSessionKeys, serverSessionKeys, SessionKeys } from '@stablelib/x25519-session'
Expand Down Expand Up @@ -84,19 +84,6 @@ export abstract class CommunicationClient {
return sealCryptobox(message, Buffer.from(recipientPublicKey, 'hex'))
}

protected tryToDeepLink() {
const wallet = JSON.parse(localStorage.getItem(StorageKey.LAST_SELECTED_WALLET) ?? '{}')

if (!this.isMobileOS() || !wallet.key || !wallet.url?.length || wallet.type !== 'mobile') {
return
}

const a = document.createElement('a')
a.setAttribute('href', wallet.url)
a.setAttribute('rel', 'noopener')
a.dispatchEvent(new MouseEvent('click', { view: window, bubbles: true, cancelable: true }))
}

abstract unsubscribeFromEncryptedMessages(): Promise<void>
abstract unsubscribeFromEncryptedMessage(senderPublicKey: string): Promise<void>
// abstract send(message: string, recipient?: string): Promise<void>
Expand Down
77 changes: 44 additions & 33 deletions packages/beacon-dapp/src/dapp-client/DAppClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,9 @@ import {
getExtensionList,
getWebList,
isBrowser,
isDesktop
isDesktop,
isMobileOS,
isIOS
} from '@airgap/beacon-ui'
import { WalletConnectTransport } from '@airgap/beacon-transport-walletconnect'

Expand All @@ -144,6 +146,11 @@ export class DAppClient extends Client {
*/
public readonly blockExplorer: BlockExplorer

/**
* Automatically switch between apps on Mobile Devices (Enabled by Default)
*/
enableAppSwitching: boolean = true

public network: Network

protected readonly events: BeaconEventHandler = new BeaconEventHandler()
Expand Down Expand Up @@ -770,6 +777,28 @@ export class DAppClient extends Client {
}
}

private async tryToAppSwitch() {
if (!isMobileOS(window) || !this.enableAppSwitching) {
return
}

const wallet = await this.getWalletInfo()

if (wallet.type !== 'mobile') {
return
}

const link = isIOS(window)
? wallet.deeplink
: JSON.parse(localStorage.getItem(StorageKey.LAST_SELECTED_WALLET) ?? '{}').url

if (!link?.length) {
return
}

window.location = link
}

/**
* Will remove the account from the local storage and set a new active account if necessary.
*
Expand Down Expand Up @@ -1797,18 +1826,6 @@ export class DAppClient extends Client {
logger.timeLog(messageId, 'init done')
logger.log('makeRequest', 'after init')

const transport = await this.transport

if (
transport instanceof WalletConnectTransport &&
(await this.getActiveAccount()) &&
!(await transport.hasPairings()) &&
!(await transport.hasSessions())
) {
await this.channelClosedHandler()
throw new Error('No active pairing nor session found')
}

if (await this.addRequestAndCheckIfRateLimited()) {
this.events
.emit(BeaconEvent.LOCAL_RATE_LIMIT_REACHED)
Expand Down Expand Up @@ -1860,7 +1877,13 @@ export class DAppClient extends Client {
logger.log('makeRequest', 'sending message', request)
logger.timeLog('makeRequest', messageId, 'sending')
try {
await transport.send(payload, peer)
;(await this.transport).send(payload, peer)
if (
request.type !== BeaconMessageType.PermissionRequest ||
(this._activeAccount.isResolved() && (await this._activeAccount.promise))
) {
this.tryToAppSwitch()
}
} catch (sendError) {
this.events.emit(BeaconEvent.INTERNAL_ERROR, {
text: 'Unable to send message. If this problem persists, please reset the connection and pair your wallet again.',
Expand Down Expand Up @@ -1940,24 +1963,6 @@ export class DAppClient extends Client {
throw new Error('rate limit reached')
}

const transport = await this.transport

if (
transport instanceof WalletConnectTransport &&
(await this.getActiveAccount()) &&
!(await transport.hasPairings()) &&
!(await transport.hasSessions())
) {
await this.channelClosedHandler()
throw new Error('No active pairing nor session found')
}

// if (!(await this.checkPermissions(requestInput.type as BeaconMessageType))) {
// this.events.emit(BeaconEvent.NO_PERMISSIONS).catch((emitError) => console.warn(emitError))

// throw new Error('No permissions to send this request to wallet!')
// }

if (!this.beaconId) {
throw await this.sendInternalError('BeaconID not defined')
}
Expand Down Expand Up @@ -1990,7 +1995,13 @@ export class DAppClient extends Client {
logger.log('makeRequest', 'sending message', request)
logger.timeLog('makeRequest', messageId, 'sending')
try {
await transport.send(payload, peer)
;(await this.transport).send(payload, peer)
if (
request.message.type !== BeaconMessageType.PermissionRequest ||
(this._activeAccount.isResolved() && (await this._activeAccount.promise))
) {
this.tryToAppSwitch()
}
} catch (sendError) {
this.events.emit(BeaconEvent.INTERNAL_ERROR, {
text: 'Unable to send message. If this problem persists, please reset the connection and pair your wallet again.',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -192,10 +192,6 @@ export class WalletConnectCommunicationClient extends CommunicationClient {
switch (message.type) {
case BeaconMessageType.PermissionRequest:
this.requestPermissions(message)

if (this.messageIds.length) {
this.tryToDeepLink()
}
break
case BeaconMessageType.OperationRequest:
this.sendOperations(message)
Expand Down
2 changes: 1 addition & 1 deletion packages/beacon-ui/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,4 @@ export type { ToastAction } from './ui/toast'

export { getColorMode, setColorMode } from './utils/colorMode'

export { isMobile, isMobileOS, isBrowser, isDesktop } from './utils/platform'
export { isMobile, isMobileOS, isBrowser, isDesktop, isAndroid, isIOS } from './utils/platform'
15 changes: 13 additions & 2 deletions packages/beacon-ui/src/ui/alert/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -480,6 +480,15 @@ const openAlert = async (config: AlertConfig): Promise<string> => {
analytics()?.track('click', 'ui', 'opened wallet', { key: wallet.key })
}

localStorage.setItem(
StorageKey.LAST_SELECTED_WALLET,
JSON.stringify({
key: wallet?.key,
type: 'mobile',
icon: currentWallet()?.image
})
)

if (
wallet?.types.includes('web') &&
!(
Expand Down Expand Up @@ -550,11 +559,13 @@ const openAlert = async (config: AlertConfig): Promise<string> => {
isIOS(window) && wallet.deepLink
? wallet.deepLink
: isAndroid(window)
? 'tezos://'
: wallet.links[OSLink.IOS],
? wallet.links[OSLink.IOS]
: 'tezos://',
code
)

updateSelectedWalletWithURL(link)

if (isAndroid(window)) window.open(link, '_blank', 'noopener')
else if (isIOS(window)) {
const a = document.createElement('a')
Expand Down

0 comments on commit 2cc82ac

Please sign in to comment.