Skip to content

Commit

Permalink
adds prettier formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
joshuascan committed Nov 25, 2024
1 parent 05d57a4 commit fc13bd1
Show file tree
Hide file tree
Showing 10 changed files with 260 additions and 311 deletions.
5 changes: 5 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"arrowParens": "avoid",
"printWidth": 120,
"singleQuote": true
}
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,16 @@
"dependencies": {
"@changesets/cli": "^2.24.0",
"@magic-ext/oauth": "^12.3.0",
"@magic-sdk/provider": "^28.6.0",
"@magic-sdk/provider": "^18.3.0",
"@wagmi/connectors": "^4.1.14",
"@wagmi/core": "^2.6.5",
"magic-sdk": "^28.6.0",
"magic-sdk": "^18.3.0",
"tsc-esm-fix": "^2.20.10"
},
"devDependencies": {
"@types/node": "^20.11.24",
"changeset": "^0.2.6",
"prettier": "^3.3.3",
"rome": "12.0.0",
"typescript": "^5.0.4",
"viem": "2.x"
Expand Down
4 changes: 2 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export * from './lib/connectors/dedicatedWalletConnector'
export * from './lib/connectors/universalWalletConnector'
export * from './lib/connectors/dedicatedWalletConnector';
export * from './lib/connectors/universalWalletConnector';
183 changes: 75 additions & 108 deletions src/lib/connectors/dedicatedWalletConnector.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,14 @@
import type { OAuthExtension, OAuthProvider } from '@magic-ext/oauth'
import type {
InstanceWithExtensions,
MagicSDKAdditionalConfiguration,
SDKBase,
} from '@magic-sdk/provider'
import { createConnector, normalizeChainId } from '@wagmi/core'
import {
type MagicConnectorParams,
type MagicOptions,
magicConnector,
} from './magicConnector'
import { UserRejectedRequestError, getAddress } from 'viem'
import { createModal } from '../modal/view'
import type { OAuthExtension, OAuthProvider } from '@magic-ext/oauth';
import type { InstanceWithExtensions, MagicSDKAdditionalConfiguration, SDKBase } from '@magic-sdk/provider';
import { createConnector, normalizeChainId } from '@wagmi/core';
import { type MagicConnectorParams, type MagicOptions, magicConnector } from './magicConnector';
import { UserRejectedRequestError, getAddress } from 'viem';
import { createModal } from '../modal/view';

interface UserDetails {
email: string
phoneNumber: string
oauthProvider: OAuthProvider
email: string;
phoneNumber: string;
oauthProvider: OAuthProvider;
}

/**
Expand All @@ -39,44 +31,29 @@ interface UserDetails {
*/

interface DedicatedWalletOptions extends MagicOptions {
enableEmailLogin?: boolean
enableSMSLogin?: boolean
enableEmailLogin?: boolean;
enableSMSLogin?: boolean;
oauthOptions?: {
providers: OAuthProvider[]
callbackUrl?: string
}
magicSdkConfiguration?: MagicSDKAdditionalConfiguration<
string,
OAuthExtension[]
>
providers: OAuthProvider[];
callbackUrl?: string;
};
magicSdkConfiguration?: MagicSDKAdditionalConfiguration<string, OAuthExtension[]>;
}

export interface DedicatedWalletConnectorParams extends MagicConnectorParams {
options: DedicatedWalletOptions
options: DedicatedWalletOptions;
}

export function dedicatedWalletConnector({
chains,
options,
}: DedicatedWalletConnectorParams) {
let {
id,
name,
type,
isModalOpen,
getAccount,
getMagicSDK,
getProvider,
onAccountsChanged,
} = magicConnector({
export function dedicatedWalletConnector({ chains, options }: DedicatedWalletConnectorParams) {
let { id, name, type, isModalOpen, getAccount, getMagicSDK, getProvider, onAccountsChanged } = magicConnector({
chains,
options: { ...options, connectorType: 'dedicated' },
})
});

const oauthProviders = options.oauthOptions?.providers ?? []
const oauthCallbackUrl = options.oauthOptions?.callbackUrl
const enableSMSLogin = options.enableSMSLogin ?? false
const enableEmailLogin = options.enableEmailLogin ?? true
const oauthProviders = options.oauthOptions?.providers ?? [];
const oauthCallbackUrl = options.oauthOptions?.callbackUrl;
const enableSMSLogin = options.enableSMSLogin ?? false;
const enableEmailLogin = options.enableEmailLogin ?? true;

/**
* This method is used to get user details from the modal UI
Expand All @@ -86,7 +63,7 @@ export function dedicatedWalletConnector({
const getUserDetailsByForm = async (
enableSMSLogin: boolean,
enableEmailLogin: boolean,
oauthProviders: OAuthProvider[],
oauthProviders: OAuthProvider[]
): Promise<UserDetails> => {
const output: UserDetails = (await createModal({
accentColor: options.accentColor,
Expand All @@ -96,159 +73,149 @@ export function dedicatedWalletConnector({
enableSMSLogin: enableSMSLogin,
enableEmailLogin: enableEmailLogin,
oauthProviders,
})) as UserDetails
})) as UserDetails;

isModalOpen = false
return output
}
isModalOpen = false;
return output;
};

return createConnector((config) => ({
return createConnector(config => ({
id,
type,
name,
getProvider,
connect: async function () {
if (!options.apiKey) {
throw new Error('Magic API Key is not provided.')
throw new Error('Magic API Key is not provided.');
}

const provider = await getProvider()
const provider = await getProvider();

if (provider?.on) {
provider.on('accountsChanged', this.onAccountsChanged.bind(this))
provider.on('chainChanged', this.onChainChanged.bind(this))
provider.on('disconnect', this.onDisconnect.bind(this))
provider.on('accountsChanged', this.onAccountsChanged.bind(this));
provider.on('chainChanged', this.onChainChanged.bind(this));
provider.on('disconnect', this.onDisconnect.bind(this));
}

let chainId: number
let chainId: number;
try {
chainId = await this.getChainId()
chainId = await this.getChainId();
} catch {
chainId = 0
chainId = 0;
}

if (await this.isAuthorized()) {
return {
chainId,
accounts: [await getAccount()],
}
};
}

if (!isModalOpen) {
const modalOutput = await getUserDetailsByForm(
enableSMSLogin,
enableEmailLogin,
oauthProviders,
)
const modalOutput = await getUserDetailsByForm(enableSMSLogin, enableEmailLogin, oauthProviders);

const magic = getMagicSDK() as InstanceWithExtensions<
SDKBase,
OAuthExtension[]
>
const magic = getMagicSDK() as InstanceWithExtensions<SDKBase, OAuthExtension[]>;

// LOGIN WITH MAGIC USING OAUTH PROVIDER
if (modalOutput.oauthProvider)
await magic.oauth.loginWithRedirect({
provider: modalOutput.oauthProvider,
redirectURI: oauthCallbackUrl ?? window.location.href,
})
});

// LOGIN WITH MAGIC USING EMAIL
if (modalOutput.email)
await magic.auth.loginWithEmailOTP({
email: modalOutput.email,
})
});

// LOGIN WITH MAGIC USING PHONE NUMBER
if (modalOutput.phoneNumber)
await magic.auth.loginWithSMS({
phoneNumber: modalOutput.phoneNumber,
})
});

if (await magic.user.isLoggedIn())
return {
accounts: [await getAccount()],
chainId,
}
};
}
throw new UserRejectedRequestError(Error('User Rejected Request'))
throw new UserRejectedRequestError(Error('User Rejected Request'));
},

disconnect: async () => {
try {
const magic = getMagicSDK()
await magic?.wallet.disconnect()
localStorage.removeItem('magicRedirectResult')
config.emitter.emit('disconnect')
const magic = getMagicSDK();
await magic?.wallet.disconnect();
localStorage.removeItem('magicRedirectResult');
config.emitter.emit('disconnect');
} catch (error) {
console.error('Error disconnecting from Magic SDK:', error)
console.error('Error disconnecting from Magic SDK:', error);
}
},

getAccounts: async () => {
const provider = await getProvider()
const provider = await getProvider();
const accounts = (await provider?.request({
method: 'eth_accounts',
})) as string[]
return accounts.map((x) => getAddress(x))
})) as string[];
return accounts.map(x => getAddress(x));
},

getChainId: async (): Promise<number> => {
const provider = await getProvider()
const provider = await getProvider();
if (provider) {
const chainId = await provider.request({
method: 'eth_chainId',
params: [],
})
return normalizeChainId(chainId)
});
return normalizeChainId(chainId);
}
const networkOptions = options.magicSdkConfiguration?.network
const networkOptions = options.magicSdkConfiguration?.network;
if (typeof networkOptions === 'object') {
const chainID = networkOptions.chainId
if (chainID) return normalizeChainId(chainID)
const chainID = networkOptions.chainId;
if (chainID) return normalizeChainId(chainID);
}
throw new Error('Chain ID is not defined')
throw new Error('Chain ID is not defined');
},

isAuthorized: async () => {
try {
const magic = getMagicSDK() as InstanceWithExtensions<
SDKBase,
OAuthExtension[]
>
const magic = getMagicSDK() as InstanceWithExtensions<SDKBase, OAuthExtension[]>;

if (!magic) {
return false
return false;
}

const isLoggedIn = await magic.user.isLoggedIn()
const result = await magic.oauth.getRedirectResult()
const isLoggedIn = await magic.user.isLoggedIn();
const result = await magic.oauth.getRedirectResult();
if (result) {
localStorage.setItem('magicRedirectResult', JSON.stringify(result))
localStorage.setItem('magicRedirectResult', JSON.stringify(result));
}

if (isLoggedIn) return true
if (isLoggedIn) return true;

return result !== null
return result !== null;
} catch {}
return false
return false;
},

onAccountsChanged,

onChainChanged(chain) {
const chainId = normalizeChainId(chain)
config.emitter.emit('change', { chainId })
const chainId = normalizeChainId(chain);
config.emitter.emit('change', { chainId });
},

async onConnect(connectInfo) {
const chainId = normalizeChainId(connectInfo.chainId)
const accounts = await this.getAccounts()
config.emitter.emit('connect', { accounts, chainId })
const chainId = normalizeChainId(connectInfo.chainId);
const accounts = await this.getAccounts();
config.emitter.emit('connect', { accounts, chainId });
},

onDisconnect: () => {
config.emitter.emit('disconnect')
config.emitter.emit('disconnect');
},
}))
}));
}
Loading

0 comments on commit fc13bd1

Please sign in to comment.