Skip to content

Commit

Permalink
refactoring, add initDapp function, set nativeAuthCofig at init
Browse files Browse the repository at this point in the history
  • Loading branch information
CiprianDraghici committed Jul 25, 2024
1 parent 6ec1ba6 commit 3611c64
Show file tree
Hide file tree
Showing 25 changed files with 197 additions and 151 deletions.
7 changes: 2 additions & 5 deletions esbuild.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const executeBuild = () =>
format: 'esm',
outdir: 'out',
treeShaking: true,
minify: true,
minify: false,
bundle: true,
sourcemap: true,
chunkNames: '__chunks__/[name]-[hash]',
Expand All @@ -38,10 +38,7 @@ const executeBuild = () =>
process: 'process',
Buffer: 'Buffer'
},
plugins: [
plugin(stdLibBrowser),
nodeExternalsPlugin(),
]
plugins: [plugin(stdLibBrowser), nodeExternalsPlugin()]
})
.then(() => {
console.log(
Expand Down
2 changes: 1 addition & 1 deletion src/core/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export * from './ProviderFactory';
export * from './providers/ProviderFactory';
export * from './Logger';
30 changes: 30 additions & 0 deletions src/core/methods/init/init.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { initStore } from 'store/store';
import { defaultStorageCallback, StorageCallback } from 'store/storage';
import { setTokenLoginNativeAuthTokenConfig } from 'store/actions/loginInfo/loginInfoActions';
import { NativeAuthConfigType } from 'services/nativeAuth/nativeAuth.types';
import { getDefaultNativeAuthConfig } from 'services/nativeAuth/methods/getDefaultNativeAuthConfig';

type InitAppType = {
storage?: {
getStorageCallback: StorageCallback;
};
nativeAuth?: boolean | NativeAuthConfigType;
};
const defaultInitAppProps = {
storage: {
getStorageCallback: defaultStorageCallback
}
};
export const initializeDApp = (props?: InitAppType) => {
const { storage, nativeAuth } = { ...defaultInitAppProps, ...props };
initStore(storage.getStorageCallback);

if (nativeAuth) {
const nativeAuthConfig: NativeAuthConfigType =
typeof nativeAuth === 'boolean'
? getDefaultNativeAuthConfig()
: nativeAuth;

setTokenLoginNativeAuthTokenConfig(nativeAuthConfig);
}
};
6 changes: 3 additions & 3 deletions src/core/methods/login/helpers/getLoginService.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { Address, SignableMessage } from '@multiversx/sdk-core';
import { nativeAuth } from 'services/nativeAuth';
import { getNativeAuthConfig } from 'services/nativeAuth/methods';
import { buildNativeAuthConfig } from 'services/nativeAuth/methods';
import { networkSelector, tokenLoginSelector } from 'store/selectors';
import { getState } from 'store/store';
import { OnProviderLoginType } from 'types/login.types';
import { getAccount } from '../../account/getAccount';
import { setTokenLogin } from 'store/actions/loginInfo/loginInfoActions';
import { NativeAuthConfigType } from 'types/nativeAuth.types';
import { NativeAuthConfigType } from 'services/nativeAuth/nativeAuth.types';

const getApiAddress = (
apiAddress: string,
Expand All @@ -29,7 +29,7 @@ export const getLoginService = (config?: OnProviderLoginType['nativeAuth']) => {

const apiAddress = getApiAddress(network.apiAddress, config);

const configuration = getNativeAuthConfig({
const configuration = buildNativeAuthConfig({
...(config === true ? {} : config),
...(apiAddress ? { apiAddress } : {})
});
Expand Down
62 changes: 38 additions & 24 deletions src/core/methods/login/login.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,20 @@
import { IProvider, IProviderFactory, ProviderFactory } from 'core/ProviderFactory';
import { NativeAuthConfigType } from 'types/nativeAuth.types';
import { nativeAuth } from 'services/nativeAuth';
import { setAddress } from 'store/actions/account';
import { setLoginMethod, setTokenLogin } from 'store/actions/loginInfo/loginInfoActions';
import {
setProviderType,
setTokenLogin
} from 'store/actions/loginInfo/loginInfoActions';
import { setAccountProvider } from 'core/providers/accountProvider';
import { getNativeAuthConfig } from 'services/nativeAuth/methods';
import {
IProvider,
IProviderFactory
} from 'core/providers/types/providerFactory.types';
import { ProviderFactory } from 'core/providers/ProviderFactory';
import { tokenLoginSelector } from 'store/selectors';
import { getState } from 'store/store';
import { NativeAuthConfigType } from 'services/nativeAuth/nativeAuth.types';
import { isLoggedIn } from 'utils/account/isLoggedIn';
import { getAddress } from '../../../utils/account/getAddress';

async function normalLogin(provider: IProvider) {
await provider.login();
Expand All @@ -22,8 +32,11 @@ async function normalLogin(provider: IProvider) {
};
}

async function loginWithNativeToken(provider: IProvider, nativeAuthConfig: NativeAuthConfigType) {
const nativeAuthClient = nativeAuth(nativeAuthConfig);
async function loginWithNativeToken(
provider: IProvider,
nativeAuthConfig: NativeAuthConfigType
) {
const nativeAuthClient = nativeAuth(nativeAuthConfig);

const loginToken = await nativeAuthClient.initialize({
noCache: true
Expand All @@ -34,11 +47,11 @@ async function loginWithNativeToken(provider: IProvider, nativeAuthConfig: Nativ
const address = provider.getAddress?.();
const signature = provider.getTokenLoginSignature?.();

if(!address) {
if (!address) {
throw new Error('Address not found');
}

if(!signature) {
if (!signature) {
throw new Error('Signature not found');
}

Expand All @@ -62,36 +75,37 @@ async function loginWithNativeToken(provider: IProvider, nativeAuthConfig: Nativ
nativeAuthToken,
loginToken,
nativeAuthConfig
}
};
}

export const login = async ({
providerConfig,
withNativeAuth
providerConfig
}: {
providerConfig: IProviderFactory,
withNativeAuth?: boolean | NativeAuthConfigType,
providerConfig: IProviderFactory;
}) => {
const loggedIn = isLoggedIn();

if (loggedIn) {
console.warn('Already logged in with:', getAddress());
return;
}

const factory = new ProviderFactory();
const provider = await factory.create(providerConfig);

if(!provider) {
if (!provider) {
throw new Error('Provider not found');
}

await provider.init?.();
setAccountProvider(provider);
setLoginMethod(providerConfig.type);
setProviderType(providerConfig.type);

if(withNativeAuth) {
if(typeof withNativeAuth === 'boolean') {
withNativeAuth = getNativeAuthConfig(true);
}

const nativeAuthConfig = withNativeAuth as NativeAuthConfigType;
const nativeAuthConfig = tokenLoginSelector(getState())?.nativeAuthConfig;

if (nativeAuthConfig) {
return await loginWithNativeToken(provider, nativeAuthConfig);
} else {
return await normalLogin(provider);
}
}

return await normalLogin(provider);
};
4 changes: 2 additions & 2 deletions src/core/methods/login/webWalletLogin.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { LoginMethodsEnum } from 'types/enums.types';
import { OnProviderLoginType } from 'types/login.types';
import { getWindowLocation } from 'utils/window/getWindowLocation';
import { getLoginService } from './helpers/getLoginService';
Expand All @@ -14,6 +13,7 @@ import { setAccount } from 'store/actions/account/accountActions';
import { getLatestNonce } from 'utils/account/getLatestNonce';
import { AccountType } from 'types/account.types';
import { CrossWindowProvider } from 'lib/sdkWebWalletCrossWindowProvider';
import { ProviderTypeEnum } from '../../providers/types/providerFactory.types';

export const webWalletLogin = async ({
token: tokenToSign,
Expand Down Expand Up @@ -100,7 +100,7 @@ export const webWalletLogin = async ({

loginAction({
address: account.address,
loginMethod: LoginMethodsEnum.crossWindow
providerType: ProviderTypeEnum.crossWindow
});

const newAccount: AccountType = {
Expand Down
4 changes: 2 additions & 2 deletions src/core/methods/logout/logout.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { storage } from 'storage';
import { localStorageKeys } from 'storage/local';
import { LoginMethodsEnum } from 'types';
import { getAddress } from '../account/getAddress';
import { CrossWindowProvider } from 'lib/sdkWebWalletCrossWindowProvider';
import { logoutAction } from 'store/actions/sharedActions/sharedActions';
import { getAccountProvider } from 'core/providers/accountProvider';
import { getProviderType } from 'core/providers/helpers/utils';
import { ProviderTypeEnum } from 'core/providers/types/providerFactory.types';

const broadcastLogoutAcrossTabs = (address: string) => {
const storedData = storage.local?.getItem(localStorageKeys.logoutEvent);
Expand Down Expand Up @@ -52,7 +52,7 @@ export async function logout(

if (
options.hasConsentPopup &&
providerType === LoginMethodsEnum.crossWindow
providerType === ProviderTypeEnum.crossWindow
) {
(provider as unknown as CrossWindowProvider).setShouldShowConsentPopup(
true
Expand Down
Original file line number Diff line number Diff line change
@@ -1,36 +1,11 @@
import { CrossWindowProvider } from 'lib/sdkWebWalletCrossWindowProvider';
import { ExtensionProvider } from '@multiversx/sdk-extension-provider';
import type { IDAppProviderBase } from '@multiversx/sdk-dapp-utils';
import { LoginMethodsType, LoginMethodsEnum } from '../types';

export interface IProvider extends IDAppProviderBase {
init: () => Promise<boolean>;
// TODO change return type to { address: string, signature: string } and also change the return type in IDAppProviderBase.
login: (options?: { token?: string }) => Promise<string | boolean>;
logout: () => Promise<boolean>;
setAddress: (address: string) => IProvider;
setShouldShowConsentPopup?: (shouldShow: boolean) => void;
getAddress(): string | undefined;
getTokenLoginSignature(): string | undefined;
}

export interface IProviderConfig {
network: {
walletAddress: string;
};
}

export type ProviderType = LoginMethodsType;

export interface IProviderFactory {
type: ProviderType;
config: IProviderConfig;
customProvider?: IProvider;
}

export const ProviderTypeEnum = {
...LoginMethodsEnum
} as const;
import {
IProvider,
IProviderConfig,
IProviderFactory,
ProviderTypeEnum
} from './types/providerFactory.types';

export class ProviderFactory {
public async create({
Expand All @@ -55,11 +30,11 @@ export class ProviderFactory {

createdProvider.getAddress = () => {
return provider.account.address;
}
};

createdProvider.getTokenLoginSignature = () => {
return provider.account.signature;
}
};

break;
}
Expand Down
2 changes: 1 addition & 1 deletion src/core/providers/accountProvider.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { emptyProvider } from './helpers/emptyProvider';
import { CrossWindowProvider } from 'lib/sdkWebWalletCrossWindowProvider';
import { IProvider } from 'core/ProviderFactory';
import { IProvider } from 'core/providers/types/providerFactory.types';

export type ProvidersType = IProvider | CrossWindowProvider;

Expand Down
10 changes: 3 additions & 7 deletions src/core/providers/helpers/emptyProvider.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { SignableMessage, Transaction } from '@multiversx/sdk-core';
import { EngineTypes } from 'utils/walletconnect/__sdkWalletconnectProvider';
import { IProvider } from 'core/ProviderFactory';
import { IProvider } from 'core/providers/types/providerFactory.types';

export const DAPP_INIT_ROUTE = '/dapp/init';

Expand Down Expand Up @@ -55,13 +55,9 @@ export class EmptyProvider implements IProvider {
);
}

signTransactions<T>(
transactions: T[]
): Promise<T[]> {
signTransactions<T>(transactions: T[]): Promise<T[]> {
throw new Error(
notInitializedError(
`signTransactions with transactions: ${transactions}`
)
notInitializedError(`signTransactions with transactions: ${transactions}`)
);
}

Expand Down
20 changes: 10 additions & 10 deletions src/core/providers/helpers/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,31 +3,31 @@ import { HWProvider } from '@multiversx/sdk-hw-provider';
import { MetamaskProvider } from '@multiversx/sdk-metamask-provider/out/metamaskProvider';
import { OperaProvider } from '@multiversx/sdk-opera-provider';
import { WalletProvider } from '@multiversx/sdk-web-wallet-provider';
import { LoginMethodsType, LoginMethodsEnum } from 'types/enums.types';
import { WalletConnectV2Provider } from 'utils/walletconnect/__sdkWalletconnectProvider';
import { EmptyProvider } from './emptyProvider';
import { CrossWindowProvider } from 'lib/sdkWebWalletCrossWindowProvider';
import { ProviderTypeEnum } from 'core/providers/types/providerFactory.types';

export const getProviderType = <TProvider extends object>(
provider?: TProvider | null
): LoginMethodsType => {
): ProviderTypeEnum => {
switch (provider?.constructor) {
case WalletProvider:
return LoginMethodsEnum.webhook;
return ProviderTypeEnum.webhook;
case WalletConnectV2Provider:
return LoginMethodsEnum.walletConnect;
return ProviderTypeEnum.walletConnect;
case HWProvider:
return LoginMethodsEnum.hardware;
return ProviderTypeEnum.hardware;
case ExtensionProvider:
return LoginMethodsEnum.extension;
return ProviderTypeEnum.extension;
case MetamaskProvider:
return LoginMethodsEnum.metamask;
return ProviderTypeEnum.metamask;
case OperaProvider:
return LoginMethodsEnum.opera;
return ProviderTypeEnum.opera;
case CrossWindowProvider:
return LoginMethodsEnum.crossWindow;
return ProviderTypeEnum.crossWindow;
case EmptyProvider:
default:
return LoginMethodsEnum.none;
return ProviderTypeEnum.none;
}
};
Loading

0 comments on commit 3611c64

Please sign in to comment.