Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: add ping ack #655

Merged
merged 4 commits into from
Nov 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions packages/beacon-core/src/transports/clients/ClientEvents.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
export const enum ClientEvents {
CLOSE_ALERT = 'CLOSE_ALERT',
RESET_STATE = 'RESET_STATE',
WC_ACK_NOTIFICATION = 'WC_ACK_NOTIFICATION',
UPDATE_ACCOUNT = 'UPDATE_ACCOUNT'
}
18 changes: 0 additions & 18 deletions packages/beacon-dapp/src/dapp-client/DAppClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -454,24 +454,6 @@ export class DAppClient extends Client {
ClientEvents.RESET_STATE,
this.channelClosedHandler.bind(this)
)
this.walletConnectTransport.setEventHandler(
ClientEvents.WC_ACK_NOTIFICATION,
this.wcToastHandler.bind(this)
)
}

private async wcToastHandler() {
const walletInfo = await (async (): Promise<WalletInfo> => {
try {
return await this.getWalletInfo()
} catch {
return { name: 'wallet' }
}
})()

await this.events.emit(BeaconEvent.HIDE_UI, ['alert'])

await this.events.emit(BeaconEvent.WC_ACKNOWLEDGE_PENDING, { walletInfo })
}

private async channelClosedHandler() {
Expand Down
14 changes: 0 additions & 14 deletions packages/beacon-dapp/src/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,6 @@ export enum BeaconEvent {
BROADCAST_REQUEST_SENT = 'BROADCAST_REQUEST_SENT',
BROADCAST_REQUEST_SUCCESS = 'BROADCAST_REQUEST_SUCCESS',
BROADCAST_REQUEST_ERROR = 'BROADCAST_REQUEST_ERROR',
WC_ACKNOWLEDGE_PENDING = 'WC_ACKNOWLEDGE_PENDING',
ACKNOWLEDGE_RECEIVED = 'ACKNOWLEDGE_RECEIVED',

LOCAL_RATE_LIMIT_REACHED = 'LOCAL_RATE_LIMIT_REACHED',
Expand Down Expand Up @@ -171,9 +170,6 @@ export interface BeaconEventType {
walletInfo: WalletInfo
}
[BeaconEvent.BROADCAST_REQUEST_ERROR]: { errorResponse: ErrorResponse; walletInfo: WalletInfo }
[BeaconEvent.WC_ACKNOWLEDGE_PENDING]: {
walletInfo: WalletInfo
}
[BeaconEvent.ACKNOWLEDGE_RECEIVED]: {
message: AcknowledgeResponse
extraInfo: ExtraInfo
Expand Down Expand Up @@ -652,14 +648,6 @@ const showBroadcastSuccessAlert = async (
})
}

const showWCPendingAck = async (data: { walletInfo: WalletInfo }): Promise<void> => {
openToast({
body: 'Awaiting acknowledgment from\u00A0 {{wallet}}',
state: 'loading',
walletInfo: data.walletInfo
}).catch((toastError) => console.error(toastError))
}

const emptyHandler = (): BeaconEventHandlerFunction => async (): Promise<void> => {
//
}
Expand Down Expand Up @@ -694,7 +682,6 @@ export const defaultEventCallbacks: {
[BeaconEvent.BROADCAST_REQUEST_SENT]: showSentToast,
[BeaconEvent.BROADCAST_REQUEST_SUCCESS]: showBroadcastSuccessAlert,
[BeaconEvent.BROADCAST_REQUEST_ERROR]: showErrorToast,
[BeaconEvent.WC_ACKNOWLEDGE_PENDING]: showWCPendingAck,
[BeaconEvent.ACKNOWLEDGE_RECEIVED]: showAcknowledgedToast,
[BeaconEvent.LOCAL_RATE_LIMIT_REACHED]: showRateLimitReached,
[BeaconEvent.NO_PERMISSIONS]: showNoPermissionAlert,
Expand Down Expand Up @@ -737,7 +724,6 @@ export class BeaconEventHandler {
[BeaconEvent.SIGN_REQUEST_SENT]: [defaultEventCallbacks.SIGN_REQUEST_SENT],
[BeaconEvent.SIGN_REQUEST_SUCCESS]: [defaultEventCallbacks.SIGN_REQUEST_SUCCESS],
[BeaconEvent.SIGN_REQUEST_ERROR]: [defaultEventCallbacks.SIGN_REQUEST_ERROR],
[BeaconEvent.WC_ACKNOWLEDGE_PENDING]: [defaultEventCallbacks.WC_ACKNOWLEDGE_PENDING],
// TODO: ENCRYPTION
// [BeaconEvent.ENCRYPT_REQUEST_SENT]: [defaultEventCallbacks.ENCRYPT_REQUEST_SENT],
// [BeaconEvent.ENCRYPT_REQUEST_SUCCESS]: [defaultEventCallbacks.ENCRYPT_REQUEST_SUCCESS],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ import {
SignPayloadResponseInput,
StorageKey
} from '@airgap/beacon-types'
import { ExposedPromise, generateGUID, getAddressFromPublicKey } from '@airgap/beacon-utils'
import { generateGUID, getAddressFromPublicKey } from '@airgap/beacon-utils'

const TEZOS_PLACEHOLDER = 'tezos'
const logger = new Logger('WalletConnectCommunicationClient')
Expand All @@ -58,8 +58,7 @@ export interface PermissionScopeParam {
export enum PermissionScopeMethods {
GET_ACCOUNTS = 'tezos_getAccounts',
OPERATION_REQUEST = 'tezos_send',
SIGN = 'tezos_sign',
REQUEST_NEW_ACCOUNT = 'tezos_requestNewAccount'
SIGN = 'tezos_sign'
}

export enum PermissionScopeEvents {
Expand Down Expand Up @@ -87,8 +86,6 @@ export class WalletConnectCommunicationClient extends CommunicationClient {
private activeAccount: string | undefined
private activeNetwork: string | undefined

private requestAccountNamespacePromise: ExposedPromise | undefined = undefined

private currentMessageId: string | undefined // TODO JGD we shouldn't need this

constructor(private wcOptions: { network: NetworkType; opts: SignClientTypes.Options }) {
Expand Down Expand Up @@ -140,6 +137,15 @@ export class WalletConnectCommunicationClient extends CommunicationClient {
// implementation
}

private checkWalletReadiness(topic: string) {
this.signClient?.core.pairing
.ping({ topic })
.then(() => {
this.currentMessageId && this.acknowledgeRequest(this.currentMessageId)
})
.catch((error) => logger.error(error.message))
}

async sendMessage(_message: string, _peer?: any): Promise<void> {
const serializer = new Serializer()
const message = (await serializer.deserialize(_message)) as any
Expand Down Expand Up @@ -185,10 +191,6 @@ export class WalletConnectCommunicationClient extends CommunicationClient {
})
}

private checkTezosMethods(method: PermissionScopeMethods) {
return this.session?.namespaces.tezos.methods.includes(method)
}

private async notifyListenersWithPermissionResponse(
session: SessionTypes.Struct,
network: Network
Expand Down Expand Up @@ -260,28 +262,7 @@ export class WalletConnectCommunicationClient extends CommunicationClient {
throw new MissingRequiredScope(PermissionScopeMethods.GET_ACCOUNTS)
}

if (
this.activeAccount &&
this.session &&
this.checkTezosMethods(PermissionScopeMethods.REQUEST_NEW_ACCOUNT)
) {
const client = await this.getSignClient()
try {
await client.request({
topic: this.session.topic,
chainId: `${TEZOS_PLACEHOLDER}:${this.getActiveNetwork()}`,
request: {
method: PermissionScopeMethods.REQUEST_NEW_ACCOUNT,
params: {
id: this.currentMessageId!
}
}
})
return
} catch (error: any) {
logger.warn(error.message)
}
}
const session = this.getSession()

if (this.activeAccount) {
try {
Expand All @@ -293,18 +274,6 @@ export class WalletConnectCommunicationClient extends CommunicationClient {
}

this.setDefaultAccountAndNetwork()

let session = this.getSession()

const accounts = session.namespaces.tezos.accounts ?? []
if (accounts.length > 0 && accounts[0].split(':')[2] === '?') {
const fun = this.eventHandlers.get(ClientEvents.WC_ACK_NOTIFICATION)
fun && fun()
this.requestAccountNamespacePromise = new ExposedPromise()
await this.requestAccountNamespacePromise?.promise
session = this.getSession()
}

this.notifyListenersWithPermissionResponse(session, message.network)
}

Expand All @@ -322,6 +291,8 @@ export class WalletConnectCommunicationClient extends CommunicationClient {
const account = await this.getPKH()
this.validateNetworkAndAccount(network, account)

this.checkWalletReadiness(session.pairingTopic)

// TODO: Type
signClient
.request<{ signature: string }>({
Expand Down Expand Up @@ -371,6 +342,8 @@ export class WalletConnectCommunicationClient extends CommunicationClient {
const account = await this.getPKH()
this.validateNetworkAndAccount(network, account)

this.checkWalletReadiness(session.pairingTopic)

signClient
.request<{
// The `operationHash` field should be provided to specify the operation hash,
Expand Down Expand Up @@ -434,16 +407,7 @@ export class WalletConnectCommunicationClient extends CommunicationClient {
// therefore we must immediately open a session
// to get data required in the pairing response
try {
let session = await this.openSession(topic)
const accounts = session.namespaces.tezos.accounts ?? []

if (accounts.length > 0 && accounts[0].split(':')[2] === '?') {
const fun = this.eventHandlers.get(ClientEvents.WC_ACK_NOTIFICATION)
fun && fun()
this.requestAccountNamespacePromise = new ExposedPromise()
await this.requestAccountNamespacePromise?.promise
session = this.getSession()
}
const session = await this.openSession(topic)

const pairingResponse: ExtendedWalletConnectPairingResponse =
new ExtendedWalletConnectPairingResponse(
Expand Down Expand Up @@ -486,15 +450,10 @@ export class WalletConnectCommunicationClient extends CommunicationClient {
signClient.on('session_update', (event) => {
this.session = signClient.session.get(event.topic)

if (this.requestAccountNamespacePromise) {
this.requestAccountNamespacePromise?.resolve(true)
this.requestAccountNamespacePromise = undefined
} else {
this.updateActiveAccount(event.params.namespaces)
this.notifyListenersWithPermissionResponse(this.session!, {
type: this.wcOptions.network
})
}
this.updateActiveAccount(event.params.namespaces)
this.notifyListenersWithPermissionResponse(this.session!, {
type: this.wcOptions.network
})
})

signClient.on('session_delete', (event) => {
Expand Down Expand Up @@ -713,7 +672,7 @@ export class WalletConnectCommunicationClient extends CommunicationClient {
const optionalPermissionScopeParams: PermissionScopeParam = {
networks: [this.wcOptions.network],
events: [PermissionScopeEvents.REQUEST_ACKNOWLEDGED],
methods: [PermissionScopeMethods.REQUEST_NEW_ACCOUNT]
methods: []
}

const connectParams = {
Expand All @@ -726,6 +685,8 @@ export class WalletConnectCommunicationClient extends CommunicationClient {
pairingTopic: pairingTopic ?? signClient.core.pairing.getPairings()[0]?.topic
}

this.checkWalletReadiness(connectParams.pairingTopic)

const { approval } = await signClient.connect(connectParams)

try {
Expand Down