Skip to content

Commit

Permalink
feat: init flow
Browse files Browse the repository at this point in the history
  • Loading branch information
isordo committed Sep 19, 2023
1 parent 6a2255f commit 1a679d0
Show file tree
Hide file tree
Showing 5 changed files with 52 additions and 10 deletions.
6 changes: 3 additions & 3 deletions examples/dapp.html
Original file line number Diff line number Diff line change
Expand Up @@ -301,9 +301,9 @@
}

// Initiate a permission request
const requestPermission = (callback, newSession = true) => {
const requestPermission = (callback, sessionUpdate = false) => {
client
.requestPermissions(undefined, newSession)
.requestPermissions(undefined, sessionUpdate)
.then((permissions) => {
console.log('permissions', permissions)
if (callback) {
Expand Down Expand Up @@ -344,7 +344,7 @@
})

document.getElementById('sessionUpdate').addEventListener('click', () => {
requestPermission(undefined, false)
requestPermission(undefined, true)
})

// Add event listener to the button
Expand Down
20 changes: 16 additions & 4 deletions packages/beacon-dapp/src/dapp-client/DAppClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ import {
getiOSList
} from '@airgap/beacon-ui'
import { signMessage } from '@airgap/beacon-utils'
import { WalletConnectTransport } from '@airgap/beacon-transport-walletconnect'

const logger = new Logger('DAppClient')

Expand Down Expand Up @@ -186,6 +187,8 @@ export class DAppClient extends Client {

private readonly featuredWallets: string[] | undefined

private isSessionUpdatingEnabled: boolean = false

constructor(config: DAppClientOptions) {
super({
storage: config && config.storage ? config.storage : new LocalStorage(),
Expand Down Expand Up @@ -952,7 +955,7 @@ export class DAppClient extends Client {
}

public async sessionUpdate(input?: RequestPermissionInput) {
await this.requestPermissions(input, false)
await this.requestPermissions(input, true)
}

/**
Expand All @@ -964,7 +967,7 @@ export class DAppClient extends Client {
*/
public async requestPermissions(
input?: RequestPermissionInput,
sessionUpdate: boolean = true
sessionUpdate: boolean = false
): Promise<PermissionResponseOutput> {
// Add error message for deprecation of network
// TODO: Remove when we remove deprecated preferredNetwork
Expand All @@ -982,11 +985,12 @@ export class DAppClient extends Client {
input && input.scopes
? input.scopes
: [PermissionScope.OPERATION_REQUEST, PermissionScope.SIGN],
sessionUpdate
}

this.analytics.track('event', 'DAppClient', 'Permission requested')

this.isSessionUpdatingEnabled = sessionUpdate;

const { message, connectionInfo } = await this.makeRequest<
PermissionRequest,
PermissionResponse
Expand Down Expand Up @@ -1556,6 +1560,14 @@ export class DAppClient extends Client {
logger.timeLog(messageId, 'init done')
logger.log('makeRequest', 'after init')

const transport = await this.transport;

if (transport instanceof WalletConnectTransport) {
this.isSessionUpdatingEnabled ? transport.enableSessionUpdating() : transport.disableSessionUpdating()
}

console.log("transport: ", transport);

if (await this.addRequestAndCheckIfRateLimited()) {
this.events
.emit(BeaconEvent.LOCAL_RATE_LIMIT_REACHED)
Expand Down Expand Up @@ -1603,7 +1615,7 @@ export class DAppClient extends Client {
logger.log('makeRequest', 'sending message', request)
logger.timeLog('makeRequest', messageId, 'sending')
try {
await (await this.transport).send(payload, peer)
await transport.send(payload, peer)
} 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 @@ -88,6 +88,14 @@ export class WalletConnectTransport<
return super.disconnect()
}

async enableSessionUpdating() {
this.client.updateExistingSession = true
}

async disableSessionUpdating() {
this.client.updateExistingSession = false
}

public async startOpenChannelListener(): Promise<void> {
//
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@ export interface PermissionScopeParam {
export enum PermissionScopeMethods {
GET_ACCOUNTS = 'tezos_getAccounts',
OPERATION_REQUEST = 'tezos_send',
SIGN = 'tezos_sign'
SIGN = 'tezos_sign',
SESSION_UPDATE = 'tezos_sessionUpdate'
}

export enum PermissionScopeEvents {
Expand Down Expand Up @@ -77,6 +78,7 @@ export class WalletConnectCommunicationClient extends CommunicationClient {
private activeNetwork: string | undefined

private currentMessageId: string | undefined // TODO JGD we shouldn't need this
updateExistingSession: boolean = false

constructor(private wcOptions: { network: NetworkType; opts: SignClientTypes.Options }) {
super()
Expand Down Expand Up @@ -179,7 +181,7 @@ export class WalletConnectCommunicationClient extends CommunicationClient {
throw new MissingRequiredScope(PermissionScopeMethods.GET_ACCOUNTS)
}

if (this.activeAccount && message.sessionUpdate) {
if (this.activeAccount && !this.updateExistingSession) {
try {
await this.openSession()
} catch (error: any) {
Expand All @@ -191,8 +193,21 @@ export class WalletConnectCommunicationClient extends CommunicationClient {
this.setDefaultAccountAndNetwork()

const session = this.getSession()
const signClient = await this.getSignClient()

let publicKey: string | undefined

if (this.updateExistingSession && !signClient?.pairing.getAll().length) {
console.log("dispatching session_update")
await signClient.request({
topic: session.topic,
chainId: `${TEZOS_PLACEHOLDER}:${this.wcOptions.network}`,
request: { method: PermissionScopeMethods.SESSION_UPDATE, params: {} }
})

return
}

if (
session.sessionProperties?.pubkey &&
session.sessionProperties?.algo &&
Expand Down Expand Up @@ -429,10 +444,18 @@ export class WalletConnectCommunicationClient extends CommunicationClient {
})

signClient.core.pairing.events.on('pairing_delete', (event) => {
if (this.updateExistingSession) {
return
}

this.disconnect(signClient, { type: 'pairing', topic: event.topic })
})

signClient.core.pairing.events.on('pairing_expire', (event) => {
if (this.updateExistingSession) {
return
}

this.disconnect(signClient, { type: 'pairing', topic: event.topic })
})
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,4 @@ export interface PermissionRequest extends BeaconBaseMessage {
appMetadata: AppMetadata // Some additional information about the DApp
network: Network // Network on which the permissions are requested. Only one network can be specified. In case you need permissions on multiple networks, you need to request permissions multiple times
scopes: PermissionScope[] // The permission scopes that the DApp is asking for
sessionUpdate: boolean // true when you want to open a new session, false otherwise
}

0 comments on commit 1a679d0

Please sign in to comment.