Skip to content

Commit

Permalink
wc: improvements (#5616)
Browse files Browse the repository at this point in the history
* singleton + perf reporting

* bump wc packages

* Revert "bump wc packages"

This reverts commit 9f5d2ac.

---------

Co-authored-by: Ibrahim Taveras <[email protected]>
  • Loading branch information
skylarbarrera and ibrahimtaveras00 committed Apr 12, 2024
1 parent 9c68d60 commit 961ec58
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 12 deletions.
1 change: 1 addition & 0 deletions src/performance/tracking/types/PerformanceMetrics.ts
Expand Up @@ -8,6 +8,7 @@ export const PerformanceMetrics = {
loadRootAppComponent: 'Performance Time To Load Root App Component',
timeToInteractive: 'Performance Time To Interactive',
useInitializeWallet: 'Performance Wallet Initialize Time',
initializeWalletconnect: 'Performance WalletConnect Initialize Time',
} as const;

export type PerformanceMetricsType = (typeof PerformanceMetrics)[keyof typeof PerformanceMetrics];
47 changes: 35 additions & 12 deletions src/walletConnect/index.tsx
Expand Up @@ -43,6 +43,8 @@ import { uniq } from 'lodash';
import { fetchDappMetadata } from '@/resources/metadata/dapp';
import { DAppStatus } from '@/graphql/__generated__/metadata';
import { handleWalletConnectRequest } from '@/utils/requestNavigationHandlers';
import { PerformanceMetrics } from '@/performance/tracking/types/PerformanceMetrics';
import { PerformanceTracking } from '@/performance/tracking';

const SUPPORTED_EVM_CHAIN_IDS = RainbowNetworks.filter(({ features }) => features.walletconnect).map(({ id }) => id);

Expand Down Expand Up @@ -95,7 +97,7 @@ let syncWeb3WalletClient: Awaited<ReturnType<(typeof Web3Wallet)['init']>> | und

const walletConnectCore = new Core({ projectId: WC_PROJECT_ID });

export const web3WalletClient = Web3Wallet.init({
const web3WalletClient = Web3Wallet.init({
core: walletConnectCore,
metadata: {
name: '🌈 Rainbow',
Expand All @@ -109,6 +111,24 @@ export const web3WalletClient = Web3Wallet.init({
},
});

let initPromise: ReturnType<(typeof Web3Wallet)['init']> | null = null;

// this function ensures we only initialize the client once
export async function getWeb3WalletClient() {
if (!syncWeb3WalletClient) {
if (!initPromise) {
initPromise = web3WalletClient.then(client => {
syncWeb3WalletClient = client;
return client;
});
}
// Wait for the initialization promise to resolve
return initPromise;
} else {
return syncWeb3WalletClient;
}
}

/**
* For RPC requests that have [address, message] tuples (order may change),
* return { address, message } and JSON.parse the value if it's from a typed
Expand Down Expand Up @@ -285,7 +305,7 @@ async function rejectProposal({
proposal,
});

const client = await web3WalletClient;
const client = await getWeb3WalletClient();
const { id, proposer } = proposal.params;

await client.rejectSession({ id, reason: getSdkError(reason) });
Expand All @@ -304,7 +324,7 @@ export async function pair({ uri, connector }: { uri: string; connector?: string
*/

const { topic, ...rest } = parseUri(uri);
const client = await web3WalletClient;
const client = await getWeb3WalletClient();

logger.debug(`WC v2: pair: parsed uri`, { topic, rest });

Expand All @@ -330,7 +350,10 @@ export async function pair({ uri, connector }: { uri: string; connector?: string
}

export async function initListeners() {
const client = await web3WalletClient;
PerformanceTracking.startMeasuring(PerformanceMetrics.initializeWalletconnect);

const client = await getWeb3WalletClient();
PerformanceTracking.finishMeasuring(PerformanceMetrics.initializeWalletconnect);

syncWeb3WalletClient = client;

Expand Down Expand Up @@ -437,7 +460,7 @@ export async function onSessionProposal(proposal: Web3WalletTypes.SessionProposa
verifiedData,
timedOut: false,
callback: async (approved, approvedChainId, accountAddress) => {
const client = await web3WalletClient;
const client = await getWeb3WalletClient();
const { id, proposer, requiredNamespaces } = proposal.params;

if (approved) {
Expand Down Expand Up @@ -561,7 +584,7 @@ export async function onSessionProposal(proposal: Web3WalletTypes.SessionProposa
// For WC v2
export async function onSessionRequest(event: SignClientTypes.EventArguments['session_request']) {
setHasPendingDeeplinkPendingRedirect(true);
const client = await web3WalletClient;
const client = await getWeb3WalletClient();

logger.debug(`WC v2: session_request`, {}, logger.DebugContext.walletconnect);

Expand Down Expand Up @@ -775,7 +798,7 @@ export async function handleSessionRequestResponse(
success: Boolean(result),
});

const client = await web3WalletClient;
const client = await getWeb3WalletClient();
const { topic, id } = sessionRequestEvent;
if (result) {
const payload = {
Expand All @@ -797,7 +820,7 @@ export async function handleSessionRequestResponse(
}

export async function onAuthRequest(event: Web3WalletTypes.AuthRequest) {
const client = await web3WalletClient;
const client = await getWeb3WalletClient();

logger.debug(`WC v2: auth_request`, { event }, logger.DebugContext.walletconnect);

Expand Down Expand Up @@ -915,7 +938,7 @@ export async function onAuthRequest(event: Web3WalletTypes.AuthRequest) {
* Returns all active settings in a type-safe manner.
*/
export async function getAllActiveSessions() {
const client = await web3WalletClient;
const client = await getWeb3WalletClient();
return Object.values(client?.getActiveSessions() || {}) || [];
}

Expand All @@ -932,7 +955,7 @@ export function getAllActiveSessionsSync() {
*/
export async function addAccountToSession(session: SessionTypes.Struct, { address }: { address?: string }) {
try {
const client = await web3WalletClient;
const client = await getWeb3WalletClient();

const namespaces: Parameters<typeof client.updateSession>[0]['namespaces'] = {};

Expand Down Expand Up @@ -993,7 +1016,7 @@ export async function addAccountToSession(session: SessionTypes.Struct, { addres

export async function changeAccount(session: SessionTypes.Struct, { address }: { address?: string }) {
try {
const client = await web3WalletClient;
const client = await getWeb3WalletClient();

/*
* Before we can effectively switch accounts, we need to add the account to
Expand Down Expand Up @@ -1041,7 +1064,7 @@ export async function changeAccount(session: SessionTypes.Struct, { address }: {
* within a dapp is handled internally by WC v2.
*/
export async function disconnectSession(session: SessionTypes.Struct) {
const client = await web3WalletClient;
const client = await getWeb3WalletClient();

await client.disconnectSession({
topic: session.topic,
Expand Down

0 comments on commit 961ec58

Please sign in to comment.