From 8a56419d268566630f171b9d3ee76b6ef5386c15 Mon Sep 17 00:00:00 2001 From: Mohamed Arbani Date: Fri, 14 Feb 2025 21:41:14 +0100 Subject: [PATCH] feat: enhance openModal to handle user rejection with error feedback Signed-off-by: Mohamed Arbani --- demos/react-dapp/src/App.tsx | 3 ++- src/lib/dapp/index.ts | 28 +++++++++++++++++++++++++--- 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/demos/react-dapp/src/App.tsx b/demos/react-dapp/src/App.tsx index 67e90d84..c8a58234 100644 --- a/demos/react-dapp/src/App.tsx +++ b/demos/react-dapp/src/App.tsx @@ -292,7 +292,8 @@ const App: React.FC = () => { let session: SessionTypes.Struct setIsLoading(true) if (extensionId) session = await dAppConnector.connectExtension(extensionId) - else session = await dAppConnector.openModal() + // Open modal with throwErrorOnReject set to true + else session = await dAppConnector.openModal(undefined, true) setNewSession(session) } finally { diff --git a/src/lib/dapp/index.ts b/src/lib/dapp/index.ts index ef62f91d..9e41139d 100644 --- a/src/lib/dapp/index.ts +++ b/src/lib/dapp/index.ts @@ -202,14 +202,36 @@ export class DAppConnector { /** * Initiates the WalletConnect connection flow using a QR code. * @param pairingTopic - The pairing topic for the connection (optional). + * @param throwErrorOnReject - Whether to show an error when the user rejects the pairing (default: false). * @returns {Promise} - A Promise that resolves when the connection process is complete. */ - public async openModal(pairingTopic?: string): Promise { + public async openModal( + pairingTopic?: string, + throwErrorOnReject: boolean = false, + ): Promise { try { const { uri, approval } = await this.connectURI(pairingTopic) this.walletConnectModal.openModal({ uri }) - const session = await approval() - await this.onSessionConnected(session) + + const session = await new Promise(async (resolve, reject) => { + if (throwErrorOnReject) { + this.walletConnectModal.subscribeModal((state: { open: boolean }) => { + // the modal was closed so reject the promise + if (!state.open) { + reject(new Error('User rejected pairing')) + } + }) + } + + try { + const approvedSession = await approval() + await this.onSessionConnected(approvedSession) + resolve(approvedSession) + } catch (error) { + reject(error) + } + }) + return session } finally { this.walletConnectModal.closeModal()