Skip to content

Commit

Permalink
fix(clerk-js,clerk-react,types): Optimize Coinbase SDK loading
Browse files Browse the repository at this point in the history
Instead of lazy loading the Coinbase SDK in getEthereumProvider(), move loading when the SignIn/SignUp components mount. This fix avoid the Safari to block the Coinbase popup
  • Loading branch information
nikospapcom committed Dec 17, 2024
1 parent 3f98e14 commit a83056f
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 2 deletions.
7 changes: 7 additions & 0 deletions .changeset/healthy-pears-play.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@clerk/clerk-js': patch
'@clerk/clerk-react': patch
'@clerk/types': patch
---

Introduce new method `prefetchDependencies` to load Coinbase SDK instead of loading the SDK when click the `Coinbase` button in `<SignIn/>` / `<SignUp />`. This change avoid the Safari to block the Coinbase popup
32 changes: 31 additions & 1 deletion packages/clerk-js/src/core/clerk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { logger } from '@clerk/shared/logger';
import { isHttpOrHttps, isValidProxyUrl, proxyUrlToAbsoluteURL } from '@clerk/shared/proxy';
import { eventPrebuiltComponentMounted, TelemetryCollector } from '@clerk/shared/telemetry';
import { addClerkPrefix, stripScheme } from '@clerk/shared/url';
import { handleValueOrFn, noop } from '@clerk/shared/utils';
import { createDeferredPromise, handleValueOrFn, noop } from '@clerk/shared/utils';
import type {
__internal_UserVerificationModalProps,
ActiveSessionResource,
Expand Down Expand Up @@ -65,7 +65,9 @@ import type {
WaitlistProps,
WaitlistResource,
Web3Provider,
Web3Strategy,
} from '@clerk/types';
import type CoinbaseWalletSDK from '@coinbase/wallet-sdk';

import type { MountComponentRenderer } from '../ui/Components';
import { UI } from '../ui/new';
Expand Down Expand Up @@ -138,6 +140,7 @@ declare global {
__clerk_publishable_key?: string;
__clerk_proxy_url?: ClerkInterface['proxyUrl'];
__clerk_domain?: ClerkInterface['domain'];
__clerk_coinbase_sdk: Promise<typeof CoinbaseWalletSDK>;
}
}

Expand Down Expand Up @@ -197,6 +200,7 @@ export class Clerk implements ClerkInterface {
#options: ClerkOptions = {};
#pageLifecycle: ReturnType<typeof createPageLifecycle> | null = null;
#touchThrottledUntil = 0;
#coinbaseSDKResolvers = createDeferredPromise();

public __internal_getCachedResources:
| (() => Promise<{ client: ClientJSONSnapshot | null; environment: EnvironmentJSONSnapshot | null }>)
Expand Down Expand Up @@ -369,6 +373,20 @@ export class Clerk implements ClerkInterface {
return this.#options.experimental?.combinedFlow && this.#options.signInUrl === this.#options.signUpUrl;
}

#isCoinbaseWalletEnabled(): boolean {
const attributes = this.environment?.userSettings.attributes;
if (!attributes) {
return false;
}

const findWeb3Attributes = Object.entries(attributes)
.filter(([name, attr]) => attr.used_for_first_factor && name.startsWith('web3'))
.map(([, desc]) => desc.first_factors)
.flat() as any as Web3Strategy[];

return findWeb3Attributes.includes('web3_coinbase_wallet_signature');
}

public signOut: SignOut = async (callbackOrOptions?: SignOutCallback | SignOutOptions, options?: SignOutOptions) => {
if (!this.client || this.client.sessions.length === 0) {
return;
Expand Down Expand Up @@ -1654,6 +1672,16 @@ export class Clerk implements ClerkInterface {
this.environment = environment;
}

private prefetchDependencies = async (): Promise<void> => {
if (this.#isCoinbaseWalletEnabled()) {
window.__clerk_coinbase_sdk = this.#coinbaseSDKResolvers.promise as Promise<typeof CoinbaseWalletSDK>;

await import('@coinbase/wallet-sdk').then(mod => {
this.#coinbaseSDKResolvers.resolve(mod.CoinbaseWalletSDK);
});
}
};

__internal_setCountry = (country: string | null) => {
if (!this.__internal_country) {
this.__internal_country = country;
Expand Down Expand Up @@ -1907,6 +1935,8 @@ export class Clerk implements ClerkInterface {
return false;
}

void this.prefetchDependencies();

initComponents();

break;
Expand Down
6 changes: 5 additions & 1 deletion packages/clerk-js/src/utils/web3.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,11 @@ export async function generateSignatureWithOKXWallet(params: GenerateSignaturePa

async function getEthereumProvider(provider: Web3Provider) {
if (provider === 'coinbase_wallet') {
const CoinbaseWalletSDK = await import('@coinbase/wallet-sdk').then(mod => mod.CoinbaseWalletSDK);
const CoinbaseWalletSDK = await window.__clerk_coinbase_sdk.catch(() => null);
if (!CoinbaseWalletSDK) {
throw new Error('Coinbase Wallet SDK is not loaded');
}

const sdk = new CoinbaseWalletSDK({});
return sdk.makeWeb3Provider({ options: 'all' });
}
Expand Down

0 comments on commit a83056f

Please sign in to comment.