Skip to content

Commit

Permalink
[ID-2334] Defer preload for magic in Passport SDK (#2110)
Browse files Browse the repository at this point in the history
  • Loading branch information
matthewmuscat committed Aug 27, 2024
1 parent c36c411 commit 7b97078
Show file tree
Hide file tree
Showing 5 changed files with 33 additions and 108 deletions.
1 change: 0 additions & 1 deletion packages/passport/sdk/src/Passport.int.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,6 @@ describe('Passport', () => {
(Magic as jest.Mock).mockImplementation(() => ({
openid: { loginWithOIDC: mockLoginWithOidc },
rpcProvider: { request: mockMagicRequest },
preload: jest.fn(),
}));
});

Expand Down
33 changes: 22 additions & 11 deletions packages/passport/sdk/src/magicAdapter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import MagicAdapter from './magicAdapter';
import { PassportConfiguration } from './config';
import { PassportError, PassportErrorType } from './errors/passportError';

const loginWithOIDCMock:jest.MockedFunction<(args: LoginWithOpenIdParams) => Promise<void>> = jest.fn();
const loginWithOIDCMock: jest.MockedFunction<(args: LoginWithOpenIdParams) => Promise<void>> = jest.fn();

const rpcProvider = {};

Expand All @@ -23,7 +23,6 @@ describe('MagicWallet', () => {
magicProviderId: providerId,
} as PassportConfiguration;
const idToken = 'e30=.e30=.e30=';
const preload = jest.fn();

beforeEach(() => {
jest.resetAllMocks();
Expand All @@ -35,7 +34,6 @@ describe('MagicWallet', () => {
logout: logoutMock,
},
rpcProvider,
preload,
}));
});

Expand All @@ -56,10 +54,9 @@ describe('MagicWallet', () => {
});
it('starts initialising the magicClient', () => {
jest.spyOn(window.document, 'readyState', 'get').mockReturnValue('complete');
preload.mockResolvedValue(Promise.resolve());
const magicAdapter = new MagicAdapter(config);
// @ts-ignore
expect(magicAdapter.lazyMagicClient).toBeDefined();
// @ts-expect-error: client is private
expect(magicAdapter.client).toBeDefined();
});
});

Expand All @@ -75,15 +72,31 @@ describe('MagicWallet', () => {

it('does nothing', () => {
const magicAdapter = new MagicAdapter(config);
// @ts-ignore
expect(magicAdapter.magicClientPromise).toBeUndefined();
// @ts-expect-error: client is private
expect(magicAdapter.client).toBeUndefined();
});

it('should throw a browser error for loginWithOIDC', async () => {
const magicAdapter = new MagicAdapter(config);

let type = '';
let message = '';

try {
await magicAdapter.login(idToken);
} catch (e: any) {
type = e.type;
message = e.message;
}

expect(type).toEqual(PassportErrorType.WALLET_CONNECTION_ERROR);
expect(message).toEqual('Cannot perform this action outside of the browser');
});
});
});

describe('login', () => {
it('should call loginWithOIDC and initialise the provider with the correct arguments', async () => {
preload.mockResolvedValue(Promise.resolve());
const magicAdapter = new MagicAdapter(config);
const magicProvider = await magicAdapter.login(idToken);

Expand All @@ -101,7 +114,6 @@ describe('MagicWallet', () => {
});

it('should throw a PassportError when an error is thrown', async () => {
preload.mockResolvedValue(Promise.resolve());
const magicAdapter = new MagicAdapter(config);

loginWithOIDCMock.mockImplementation(() => {
Expand All @@ -121,7 +133,6 @@ describe('MagicWallet', () => {

describe('logout', () => {
it('calls the logout function', async () => {
preload.mockResolvedValue(Promise.resolve());
const magicAdapter = new MagicAdapter(config);
await magicAdapter.login(idToken);
await magicAdapter.logout();
Expand Down
29 changes: 11 additions & 18 deletions packages/passport/sdk/src/magicAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import { ethers } from 'ethers';
import { trackDuration } from '@imtbl/metrics';
import { PassportErrorType, withPassportError } from './errors/passportError';
import { PassportConfiguration } from './config';
import { lazyDocumentReady } from './utils/lazyLoad';

type MagicClient = InstanceWithExtensions<SDKBase, [OpenIdExtension]>;

Expand All @@ -14,28 +13,24 @@ const MAINNET = 'mainnet';
export default class MagicAdapter {
private readonly config: PassportConfiguration;

private readonly lazyMagicClient?: Promise<MagicClient>;
private readonly client?: MagicClient;

constructor(config: PassportConfiguration) {
this.config = config;
if (typeof window !== 'undefined') {
this.lazyMagicClient = lazyDocumentReady<MagicClient>(() => {
const client = new Magic(this.config.magicPublishableApiKey, {
extensions: [new OpenIdExtension()],
network: MAINNET, // We always connect to mainnet to ensure addresses are the same across envs
});
client.preload();
return client;
this.client = new Magic(this.config.magicPublishableApiKey, {
extensions: [new OpenIdExtension()],
network: MAINNET, // We always connect to mainnet to ensure addresses are the same across envs
});
}
}

private get magicClient(): Promise<MagicClient> {
if (!this.lazyMagicClient) {
private get magicClient(): MagicClient {
if (!this.client) {
throw new Error('Cannot perform this action outside of the browser');
}

return this.lazyMagicClient;
return this.client;
}

async login(
Expand All @@ -44,8 +39,7 @@ export default class MagicAdapter {
return withPassportError<ethers.providers.ExternalProvider>(async () => {
const startTime = performance.now();

const magicClient = await this.magicClient;
await magicClient.openid.loginWithOIDC({
await this.magicClient.openid.loginWithOIDC({
jwt: idToken,
providerId: this.config.magicProviderId,
});
Expand All @@ -56,14 +50,13 @@ export default class MagicAdapter {
Math.round(performance.now() - startTime),
);

return magicClient.rpcProvider as unknown as ethers.providers.ExternalProvider;
return this.magicClient.rpcProvider as unknown as ethers.providers.ExternalProvider;
}, PassportErrorType.WALLET_CONNECTION_ERROR);
}

async logout() {
const magicClient = await this.magicClient;
if (magicClient.user) {
await magicClient.user.logout();
if (this.magicClient.user) {
await this.magicClient.user.logout();
}
}
}
56 changes: 0 additions & 56 deletions packages/passport/sdk/src/utils/lazyLoad.test.ts

This file was deleted.

22 changes: 0 additions & 22 deletions packages/passport/sdk/src/utils/lazyLoad.ts

This file was deleted.

0 comments on commit 7b97078

Please sign in to comment.