diff --git a/CHANGELOG.md b/CHANGELOG.md index 60c08f12..5d64c9fb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- [Generic login + ExtensionProvider login](https://github.com/multiversx/mx-sdk-dapp-core/pull/12) - [Make middlewares registration more scalable](https://github.com/multiversx/mx-sdk-dapp-core/pull/11) - [Fix Node Polyfills](https://github.com/multiversx/mx-sdk-dapp-core/pull/10) - [Removed chain id from network slice & added esbuild and absolute imports](https://github.com/multiversx/mx-sdk-dapp-core/pull/3) diff --git a/esbuild.js b/esbuild.js index 632b424c..4e22a75d 100644 --- a/esbuild.js +++ b/esbuild.js @@ -38,10 +38,7 @@ const executeBuild = () => process: 'process', Buffer: 'Buffer' }, - plugins: [ - plugin(stdLibBrowser), - nodeExternalsPlugin(), - ] + plugins: [plugin(stdLibBrowser), nodeExternalsPlugin()] }) .then(() => { console.log( diff --git a/src/core/ProviderFactory.ts b/src/core/ProviderFactory.ts deleted file mode 100644 index 66791cab..00000000 --- a/src/core/ProviderFactory.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { Transaction } from '@multiversx/sdk-core'; -import { CrossWindowProvider } from 'lib/sdkWebWalletCrossWindowProvider'; - -export interface IProvider { - login: (options?: { token?: string }) => Promise; - logout: () => Promise; - signTransactions: (transaction: Transaction[]) => Promise; - setAddress: (address: string) => IProvider; - setShouldShowConsentPopup?: (shouldShow: boolean) => void; -} -export interface IProviderConfig { - network: { - walletAddress: string; - }; -} -export interface IProviderFactory { - type: ProviderTypeEnum; - config: IProviderConfig; - address?: string; -} - -export interface IProviderRecreateFactory extends IProviderFactory { - address: string; -} - -export enum ProviderTypeEnum { - iframe = 'iframe', - crossWindow = 'crossWindow' -} - -export class ProviderFactory { - public static async create({ - type, - config: { - network: { walletAddress } - }, - address - }: IProviderFactory): Promise { - let createdProvider: IProvider; - - switch (type) { - // case ProviderTypeEnum.iframe: { - // const provider = await ProviderFactory.getIframeProvider({ - // walletAddress, - // }); - // createdProvider = provider as unknown as IProvider; - // break; - // } - - case ProviderTypeEnum.crossWindow: { - const provider = await ProviderFactory.getCrossWindowProvider({ - walletAddress - }); - createdProvider = provider as unknown as IProvider; - break; - } - - default: - const provider = await ProviderFactory.getCrossWindowProvider({ - walletAddress - }); - createdProvider = provider as unknown as IProvider; - break; - } - - if (address) { - createdProvider.setAddress(address); - } - - return createdProvider; - } - - public static async reCreate( - config: IProviderRecreateFactory - ): Promise { - return await ProviderFactory.create(config); - } - - private static async getCrossWindowProvider({ - walletAddress - }: Partial) { - // CrossWindowProvider.getInstance().clearInstance(); - const provider = CrossWindowProvider.getInstance(); - await provider.init(); - provider.setWalletUrl(String(walletAddress)); - return provider; - } -} diff --git a/src/core/index.ts b/src/core/index.ts index 864b2dfd..95a1e567 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -1,2 +1,2 @@ -export * from './ProviderFactory'; +export * from './providers/ProviderFactory'; export * from './Logger'; diff --git a/src/core/methods/init/init.ts b/src/core/methods/init/init.ts new file mode 100644 index 00000000..1e7c369d --- /dev/null +++ b/src/core/methods/init/init.ts @@ -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); + } +}; diff --git a/src/core/methods/login/helpers/getLoginService.ts b/src/core/methods/login/helpers/getLoginService.ts index 0d8f3c5f..6cf47f3a 100644 --- a/src/core/methods/login/helpers/getLoginService.ts +++ b/src/core/methods/login/helpers/getLoginService.ts @@ -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, @@ -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 } : {}) }); diff --git a/src/core/methods/login/login.ts b/src/core/methods/login/login.ts new file mode 100644 index 00000000..b3e0ffa9 --- /dev/null +++ b/src/core/methods/login/login.ts @@ -0,0 +1,111 @@ +import { nativeAuth } from 'services/nativeAuth'; +import { setAddress } from 'store/actions/account'; +import { + setProviderType, + setTokenLogin +} from 'store/actions/loginInfo/loginInfoActions'; +import { setAccountProvider } from 'core/providers/accountProvider'; +import { + IProvider, + IProviderFactory +} from 'core/providers/types/providerFactory.types'; +import { ProviderFactory } from 'core/providers/ProviderFactory'; +import { nativeAuthConfigSelector } from 'store/selectors'; +import { getState } from 'store/store'; +import { NativeAuthConfigType } from 'services/nativeAuth/nativeAuth.types'; +import { getIsLoggedIn } from 'utils/account/getIsLoggedIn'; +import { getAddress } from 'utils/account/getAddress'; + +async function loginWithoutNativeToken(provider: IProvider) { + await provider.login(); + + const address = provider.getAddress?.(); + + if (!address) { + throw new Error('Address not found'); + } + + setAddress(address); + + return { + address + }; +} + +async function loginWithNativeToken( + provider: IProvider, + nativeAuthConfig: NativeAuthConfigType +) { + const nativeAuthClient = nativeAuth(nativeAuthConfig); + + const loginToken = await nativeAuthClient.initialize({ + noCache: true + }); + + await provider.login({ token: loginToken }); + + const address = provider.getAddress?.(); + const signature = provider.getTokenLoginSignature?.(); + + if (!address) { + throw new Error('Address not found'); + } + + if (!signature) { + throw new Error('Signature not found'); + } + + const nativeAuthToken = nativeAuthClient.getToken({ + address, + token: loginToken, + signature + }); + + setAddress(address); + setTokenLogin({ + loginToken, + signature, + nativeAuthToken, + nativeAuthConfig + }); + + return { + address, + signature, + nativeAuthToken, + loginToken, + nativeAuthConfig + }; +} + +export const login = async ({ + providerConfig +}: { + providerConfig: IProviderFactory; +}) => { + const loggedIn = getIsLoggedIn(); + + if (loggedIn) { + console.warn('Already logged in with:', getAddress()); + return; + } + + const factory = new ProviderFactory(); + const provider = await factory.create(providerConfig); + + if (!provider) { + throw new Error('Provider not found'); + } + + await provider.init?.(); + setAccountProvider(provider); + setProviderType(providerConfig.type); + + const nativeAuthConfig = nativeAuthConfigSelector(getState()); + + if (nativeAuthConfig) { + return await loginWithNativeToken(provider, nativeAuthConfig); + } + + return await loginWithoutNativeToken(provider); +}; diff --git a/src/core/methods/login/webWalletLogin.ts b/src/core/methods/login/webWalletLogin.ts index 8875f0ea..4112087a 100644 --- a/src/core/methods/login/webWalletLogin.ts +++ b/src/core/methods/login/webWalletLogin.ts @@ -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'; @@ -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, @@ -100,7 +100,7 @@ export const webWalletLogin = async ({ loginAction({ address: account.address, - loginMethod: LoginMethodsEnum.crossWindow + providerType: ProviderTypeEnum.crossWindow }); const newAccount: AccountType = { @@ -112,7 +112,7 @@ export const webWalletLogin = async ({ return newAccount; } catch (error) { - console.error('error loging in', error); + console.error('error logging in', error); throw error; } }; diff --git a/src/core/methods/logout/logout.ts b/src/core/methods/logout/logout.ts index acfd0dbe..b29a2bc5 100644 --- a/src/core/methods/logout/logout.ts +++ b/src/core/methods/logout/logout.ts @@ -1,12 +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 { getWebviewToken } from '../account/getWebviewToken'; 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); @@ -35,7 +34,6 @@ export type LogoutPropsType = { }; export async function logout( - shouldAttemptReLogin = Boolean(getWebviewToken()), options = { shouldBroadcastLogoutAcrossTabs: true, hasConsentPopup: false @@ -45,10 +43,6 @@ export async function logout( const provider = getAccountProvider(); const providerType = getProviderType(provider); - if (shouldAttemptReLogin && provider?.relogin != null) { - return provider.relogin(); - } - if (options.shouldBroadcastLogoutAcrossTabs) { broadcastLogoutAcrossTabs(address); } @@ -58,7 +52,7 @@ export async function logout( if ( options.hasConsentPopup && - providerType === LoginMethodsEnum.crossWindow + providerType === ProviderTypeEnum.crossWindow ) { (provider as unknown as CrossWindowProvider).setShouldShowConsentPopup( true diff --git a/src/core/providers/ProviderFactory.ts b/src/core/providers/ProviderFactory.ts new file mode 100644 index 00000000..d11d1c03 --- /dev/null +++ b/src/core/providers/ProviderFactory.ts @@ -0,0 +1,80 @@ +import { CrossWindowProvider } from 'lib/sdkWebWalletCrossWindowProvider'; +import { ExtensionProvider } from '@multiversx/sdk-extension-provider'; +import { + IProvider, + IProviderConfig, + IProviderFactory, + ProviderTypeEnum +} from './types/providerFactory.types'; + +export class ProviderFactory { + public async create({ + type, + config, + customProvider + }: IProviderFactory): Promise { + let createdProvider: IProvider | undefined; + + switch (type) { + // case ProviderTypeEnum.iframe: { + // const provider = await ProviderFactory.getIframeProvider({ + // walletAddress, + // }); + // createdProvider = provider as unknown as IProvider; + // break; + // } + + case ProviderTypeEnum.extension: { + const provider = await this.getExtensionProvider(); + createdProvider = provider as unknown as IProvider; + + createdProvider.getAddress = () => { + return provider.account.address; + }; + + createdProvider.getTokenLoginSignature = () => { + return provider.account.signature; + }; + + break; + } + + case ProviderTypeEnum.crossWindow: { + const { walletAddress } = config.network; + + const provider = await this.getCrossWindowProvider({ + walletAddress + }); + createdProvider = provider as unknown as IProvider; + + break; + } + + case ProviderTypeEnum.custom: { + createdProvider = customProvider; + break; + } + + default: + break; + } + + return createdProvider; + } + + private async getCrossWindowProvider({ + walletAddress + }: Partial) { + // CrossWindowProvider.getInstance().clearInstance(); + const provider = CrossWindowProvider.getInstance(); + await provider.init(); + provider.setWalletUrl(String(walletAddress)); + return provider; + } + + private async getExtensionProvider() { + const provider = ExtensionProvider.getInstance(); + await provider.init(); + return provider; + } +} diff --git a/src/core/providers/accountProvider.ts b/src/core/providers/accountProvider.ts index 44f1ba10..bdce2ab0 100644 --- a/src/core/providers/accountProvider.ts +++ b/src/core/providers/accountProvider.ts @@ -1,8 +1,8 @@ -import { IDappProvider } from 'types/dappProvider.types'; import { emptyProvider } from './helpers/emptyProvider'; import { CrossWindowProvider } from 'lib/sdkWebWalletCrossWindowProvider'; +import { IProvider } from 'core/providers/types/providerFactory.types'; -export type ProvidersType = IDappProvider | CrossWindowProvider; +export type ProvidersType = IProvider | CrossWindowProvider; let accountProvider: ProvidersType = emptyProvider; @@ -12,6 +12,6 @@ export function setAccountProvider( accountProvider = provider; } -export function getAccountProvider(): IDappProvider { - return (accountProvider as IDappProvider) || emptyProvider; +export function getAccountProvider(): IProvider { + return (accountProvider as IProvider) || emptyProvider; } diff --git a/src/core/providers/helpers/emptyProvider.ts b/src/core/providers/helpers/emptyProvider.ts index 45116027..95d81f67 100644 --- a/src/core/providers/helpers/emptyProvider.ts +++ b/src/core/providers/helpers/emptyProvider.ts @@ -1,6 +1,6 @@ import { SignableMessage, Transaction } from '@multiversx/sdk-core'; -import { IDappProvider } from 'types'; import { EngineTypes } from 'utils/walletconnect/__sdkWalletconnectProvider'; +import { IProvider } from 'core/providers/types/providerFactory.types'; export const DAPP_INIT_ROUTE = '/dapp/init'; @@ -8,7 +8,7 @@ const notInitializedError = (caller: string) => { return `Unable to perform ${caller}, Provider not initialized`; }; -export class EmptyProvider implements IDappProvider { +export class EmptyProvider implements IProvider { init(): Promise { return Promise.resolve(false); } @@ -25,10 +25,6 @@ export class EmptyProvider implements IDappProvider { throw new Error(notInitializedError(`logout with options: ${options}`)); } - getAddress(): Promise { - throw new Error(notInitializedError('getAddress')); - } - isInitialized(): boolean { return false; } @@ -59,14 +55,9 @@ export class EmptyProvider implements IDappProvider { ); } - signTransactions( - transactions: [], - options?: TOptions - ): Promise { + signTransactions(transactions: T[]): Promise { throw new Error( - notInitializedError( - `signTransactions with transactions: ${transactions} options: ${options}` - ) + notInitializedError(`signTransactions with transactions: ${transactions}`) ); } @@ -103,8 +94,12 @@ export class EmptyProvider implements IDappProvider { ); } - ping?(): Promise { - return Promise.resolve(false); + getAddress(): string | undefined { + throw new Error(notInitializedError('getAddress')); + } + + getTokenLoginSignature(): string | undefined { + throw new Error(notInitializedError(`getSignature`)); } } diff --git a/src/core/providers/helpers/utils.ts b/src/core/providers/helpers/utils.ts index db824436..4b0341a7 100644 --- a/src/core/providers/helpers/utils.ts +++ b/src/core/providers/helpers/utils.ts @@ -3,32 +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 { 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 = ( provider?: TProvider | null -): LoginMethodsEnum => { +): ProviderTypeEnum => { switch (provider?.constructor) { case WalletProvider: - return LoginMethodsEnum.wallet; + return ProviderTypeEnum.webhook; case WalletConnectV2Provider: - return LoginMethodsEnum.walletconnectv2; + return ProviderTypeEnum.walletConnect; case HWProvider: - return LoginMethodsEnum.ledger; + 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: - return LoginMethodsEnum.none; default: - return LoginMethodsEnum.extra; + return ProviderTypeEnum.none; } }; diff --git a/src/core/providers/types/providerFactory.types.ts b/src/core/providers/types/providerFactory.types.ts new file mode 100644 index 00000000..4bc2ed79 --- /dev/null +++ b/src/core/providers/types/providerFactory.types.ts @@ -0,0 +1,37 @@ +import type { IDAppProviderBase } from '@multiversx/sdk-dapp-utils'; + +export interface IProvider extends IDAppProviderBase { + init: () => Promise; + // TODO change return type to { address: string, signature: string } and also change the return type in IDAppProviderBase. + login: (options?: { token?: string }) => Promise; + logout: () => Promise; + setShouldShowConsentPopup?: (shouldShow: boolean) => void; + getAddress(): string | undefined; + // TODO will be removed as soon as the new login method is implemented in the same way for all providers + getTokenLoginSignature(): string | undefined; +} + +export interface IProviderConfig { + network: { + walletAddress: string; + }; +} + +export enum ProviderTypeEnum { + iframe = 'iframe', + crossWindow = 'crossWindow', + extension = 'extension', + walletConnect = 'walletConnect', + hardware = 'hardware', + opera = 'opera', + metamask = 'metamask', + webhook = 'webhook', + custom = 'custom', + none = '' +} + +export interface IProviderFactory { + type: ProviderTypeEnum; + config: IProviderConfig; + customProvider?: IProvider; +} diff --git a/src/services/nativeAuth/methods/getNativeAuthConfig.ts b/src/services/nativeAuth/methods/buildNativeAuthConfig.ts similarity index 50% rename from src/services/nativeAuth/methods/getNativeAuthConfig.ts rename to src/services/nativeAuth/methods/buildNativeAuthConfig.ts index 08bc3e87..51b9ce77 100644 --- a/src/services/nativeAuth/methods/getNativeAuthConfig.ts +++ b/src/services/nativeAuth/methods/buildNativeAuthConfig.ts @@ -1,18 +1,10 @@ -import { getWindowLocation } from 'utils/window/getWindowLocation'; -import { NativeAuthConfigType } from '../../../types/nativeAuth.types'; +import { NativeAuthConfigType } from '../nativeAuth.types'; +import { getDefaultNativeAuthConfig } from './getDefaultNativeAuthConfig'; -const defaultNativeAuthConfig = { - origin: getWindowLocation().origin, - apiAddress: 'https://api.multiversx.com', - expirySeconds: 60 * 60 * 24, // one day - tokenExpirationToastWarningSeconds: 5 * 60 // five minutes -}; +export const buildNativeAuthConfig = (config?: NativeAuthConfigType) => { + const defaultNativeAuthConfig = getDefaultNativeAuthConfig(); -export const getNativeAuthConfig = (config?: NativeAuthConfigType | true) => { - if (config === true) { - return defaultNativeAuthConfig; - } - const nativeAuthConfig = { + return { origin: config?.origin ?? defaultNativeAuthConfig.origin, blockHashShard: config?.blockHashShard, expirySeconds: @@ -25,5 +17,4 @@ export const getNativeAuthConfig = (config?: NativeAuthConfigType | true) => { gatewayUrl: config?.gatewayUrl, extraRequestHeaders: config?.extraRequestHeaders ?? {} }; - return nativeAuthConfig; }; diff --git a/src/services/nativeAuth/methods/getDefaultNativeAuthConfig.ts b/src/services/nativeAuth/methods/getDefaultNativeAuthConfig.ts new file mode 100644 index 00000000..0ae7fe40 --- /dev/null +++ b/src/services/nativeAuth/methods/getDefaultNativeAuthConfig.ts @@ -0,0 +1,10 @@ +import { getWindowLocation } from 'utils/window/getWindowLocation'; + +export const getDefaultNativeAuthConfig = () => { + return { + origin: getWindowLocation().origin, + apiAddress: 'https://api.multiversx.com', + expirySeconds: 60 * 60 * 24, // one day + tokenExpirationToastWarningSeconds: 5 * 60 // five minutes + }; +}; diff --git a/src/services/nativeAuth/methods/index.ts b/src/services/nativeAuth/methods/index.ts index d60dcb4b..8928cf03 100644 --- a/src/services/nativeAuth/methods/index.ts +++ b/src/services/nativeAuth/methods/index.ts @@ -1,2 +1,2 @@ export * from './getTokenExpiration'; -export * from './getNativeAuthConfig'; +export * from './buildNativeAuthConfig'; diff --git a/src/services/nativeAuth/nativeAuth.ts b/src/services/nativeAuth/nativeAuth.ts index 060bc599..00af903b 100644 --- a/src/services/nativeAuth/nativeAuth.ts +++ b/src/services/nativeAuth/nativeAuth.ts @@ -1,12 +1,12 @@ import { NativeAuthClient } from '@multiversx/sdk-native-auth-client'; -import { NativeAuthConfigType } from 'types/nativeAuth.types'; import { getLatestBlockHash, LatestBlockHashType } from './helpers/getLatestBlockHash'; -import { getNativeAuthConfig, getTokenExpiration } from './methods'; +import { buildNativeAuthConfig, getTokenExpiration } from './methods'; +import { NativeAuthConfigType } from './nativeAuth.types'; interface NativeAuthInitType { extraInfo?: { [key: string]: string }; @@ -23,7 +23,7 @@ export const nativeAuth = (config?: NativeAuthConfigType) => { extraInfo: extraInfoFromConfig, gatewayUrl, extraRequestHeaders - } = getNativeAuthConfig(config) as NativeAuthConfigType; + } = buildNativeAuthConfig(config); const nativeAuthClient = new NativeAuthClient({ origin, @@ -76,7 +76,6 @@ export const nativeAuth = (config?: NativeAuthConfigType) => { }): string => nativeAuthClient.getToken(address, token, signature); return { - getNativeAuthConfig, initialize, getToken, getTokenExpiration diff --git a/src/store/actions/loginInfo/loginInfoActions.ts b/src/store/actions/loginInfo/loginInfoActions.ts index 71d6a4f2..887a6702 100644 --- a/src/store/actions/loginInfo/loginInfoActions.ts +++ b/src/store/actions/loginInfo/loginInfoActions.ts @@ -1,4 +1,3 @@ -import { LoginMethodsEnum } from 'types/enums.types'; import { TokenLoginType } from 'types/login.types'; import { LedgerLoginType, @@ -6,10 +5,12 @@ import { WalletConnectLoginType } from 'store/slices/loginInfo/loginInfo.types'; import { getStore } from 'store/store'; +import { ProviderTypeEnum } from 'core/providers/types/providerFactory.types'; +import { NativeAuthConfigType } from 'services/nativeAuth/nativeAuth.types'; -export const setLoginMethod = (loginMethod: LoginMethodsEnum) => +export const setProviderType = (providerType: ProviderTypeEnum) => getStore().setState(({ loginInfo: state }) => { - state.loginMethod = loginMethod; + state.providerType = providerType; }); export const setTokenLogin = (tokenLogin: TokenLoginType) => @@ -24,6 +25,21 @@ export const setTokenLoginSignature = (signature: string) => } }); +export const setTokenLoginNativeAuthTokenConfig = ( + nativeAuthConfig: NativeAuthConfigType +) => + getStore().setState(({ loginInfo: state }) => { + if (state?.tokenLogin != null) { + state.tokenLogin.nativeAuthConfig = nativeAuthConfig; + return; + } + + state.tokenLogin = { + nativeAuthConfig, + loginToken: '' + }; + }); + export const setWalletLogin = (walletLogin: LoginInfoType | null) => getStore().setState(({ loginInfo: state }) => { state.walletLogin = walletLogin; diff --git a/src/store/actions/sharedActions/sharedActions.ts b/src/store/actions/sharedActions/sharedActions.ts index a45bf3b4..e03b1af8 100644 --- a/src/store/actions/sharedActions/sharedActions.ts +++ b/src/store/actions/sharedActions/sharedActions.ts @@ -1,17 +1,20 @@ import { Address } from '@multiversx/sdk-core/out'; import { getStore } from '../../store'; -import { LoginMethodsEnum } from 'types/enums.types'; import { resetStore } from 'store/middleware/logoutMiddleware'; +import { ProviderTypeEnum } from 'core/providers/types/providerFactory.types'; export const logoutAction = () => getStore().setState(resetStore); export interface LoginActionPayloadType { address: string; - loginMethod: LoginMethodsEnum; + providerType: ProviderTypeEnum; } -export const loginAction = ({ address, loginMethod }: LoginActionPayloadType) => +export const loginAction = ({ + address, + providerType +}: LoginActionPayloadType) => getStore().setState(({ account, loginInfo }) => { account.address = address; account.publicKey = new Address(address).hex(); - loginInfo.loginMethod = loginMethod; + loginInfo.providerType = providerType; }); diff --git a/src/store/selectors/loginInfoSelectors.ts b/src/store/selectors/loginInfoSelectors.ts index f8251c93..4453da2d 100644 --- a/src/store/selectors/loginInfoSelectors.ts +++ b/src/store/selectors/loginInfoSelectors.ts @@ -4,3 +4,6 @@ export const loginInfoSelector = ({ loginInfo }: StoreType) => loginInfo; export const tokenLoginSelector = ({ loginInfo }: StoreType) => loginInfo.tokenLogin; + +export const nativeAuthConfigSelector = ({ loginInfo }: StoreType) => + loginInfo.tokenLogin?.nativeAuthConfig; diff --git a/src/store/slices/loginInfo/loginInfo.types.ts b/src/store/slices/loginInfo/loginInfo.types.ts index 42013066..2ff1f3c3 100644 --- a/src/store/slices/loginInfo/loginInfo.types.ts +++ b/src/store/slices/loginInfo/loginInfo.types.ts @@ -1,5 +1,5 @@ -import { LoginMethodsEnum } from 'types/enums.types'; import { TokenLoginType } from 'types/login.types'; +import { ProviderTypeEnum } from 'core/providers/types/providerFactory.types'; export interface WalletConnectLoginType { loginType: string; @@ -18,7 +18,7 @@ export interface LoginInfoType { } export interface LoginInfoSliceType { - loginMethod: LoginMethodsEnum; + providerType: ProviderTypeEnum | null; walletConnectLogin: WalletConnectLoginType | null; ledgerLogin: LedgerLoginType | null; tokenLogin: TokenLoginType | null; diff --git a/src/store/slices/loginInfo/loginInfoSlice.ts b/src/store/slices/loginInfo/loginInfoSlice.ts index fb455d08..42a16769 100644 --- a/src/store/slices/loginInfo/loginInfoSlice.ts +++ b/src/store/slices/loginInfo/loginInfoSlice.ts @@ -1,10 +1,9 @@ -import { LoginMethodsEnum } from 'types/enums.types'; import { StateCreator } from 'zustand/vanilla'; import { StoreType, MutatorsIn } from 'store/store.types'; import { LoginInfoSliceType } from './loginInfo.types'; export const initialState: LoginInfoSliceType = { - loginMethod: LoginMethodsEnum.none, + providerType: null, walletConnectLogin: null, ledgerLogin: null, tokenLogin: null, diff --git a/src/types/dappProvider.types.ts b/src/types/dappProvider.types.ts deleted file mode 100644 index 7260263f..00000000 --- a/src/types/dappProvider.types.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { Transaction } from '@multiversx/sdk-core'; -import type { IDAppProviderBase } from '@multiversx/sdk-dapp-utils/out/models/dappProviderBase'; -import { EngineTypes } from 'utils/walletconnect/__sdkWalletconnectProvider'; -import { Nullable } from './misc.types'; - -export interface DappOptions { - callbackUrl?: string; -} - -export interface IDappProvider extends IDAppProviderBase { - init?(): Promise; - getAddress(): Promise; - isInitialized(): boolean; - isConnected(): Promise; - sendTransaction?( - transaction: Transaction, - options?: DappOptions - ): Promise; - sendCustomMessage?({ - method, - params - }: { - method: string; - params: any; - }): Promise; - sendCustomRequest?(options?: { - request: EngineTypes.RequestParams['request']; - }): Promise; - ping?(): Promise; - relogin?: () => Promise>; - setShouldShowConsentPopup?: (shouldShow: boolean) => void; -} diff --git a/src/types/enums.types.ts b/src/types/enums.types.ts index d3c01488..4af22bda 100644 --- a/src/types/enums.types.ts +++ b/src/types/enums.types.ts @@ -4,19 +4,6 @@ export enum EnvironmentsEnum { mainnet = 'mainnet' } -export enum LoginMethodsEnum { - ledger = 'ledger', - walletconnect = 'walletconnect', - walletconnectv2 = 'walletconnectv2', - wallet = 'wallet', - crossWindow = 'crossWindow', - extension = 'extension', - metamask = 'metamask', - opera = 'opera', - extra = 'extra', - none = '' -} - export enum TypesOfSmartContractCallsEnum { MultiESDTNFTTransfer = 'MultiESDTNFTTransfer', ESDTNFTTransfer = 'ESDTNFTTransfer' diff --git a/src/types/index.ts b/src/types/index.ts index a7a06d63..9d0a1f80 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -1,4 +1,3 @@ export * from './enums.types'; export * from './network.types'; -export * from './misc.types'; -export * from './dappProvider.types'; +export * from './misc.types'; \ No newline at end of file diff --git a/src/types/login.types.ts b/src/types/login.types.ts index 148fe05b..4a5f0535 100644 --- a/src/types/login.types.ts +++ b/src/types/login.types.ts @@ -1,4 +1,4 @@ -import { NativeAuthConfigType } from './nativeAuth.types'; +import { NativeAuthConfigType } from 'services/nativeAuth/nativeAuth.types'; export interface OnProviderLoginType { token?: string; diff --git a/src/types/nativeAuth.types.ts b/src/types/nativeAuth.types.ts deleted file mode 100644 index c0c6b885..00000000 --- a/src/types/nativeAuth.types.ts +++ /dev/null @@ -1,17 +0,0 @@ -export interface NativeAuthConfigType { - origin?: string; - apiAddress?: string; - expirySeconds?: number; - blockHashShard?: number; - gatewayUrl?: string; - extraRequestHeaders?: { [key: string]: string }; - extraInfo?: { - [key: string]: string; - }; - /** - * Displays a logout toast warning before token expiration. Defaults to 5 minutes. - * - * If set to `null`, will not trigger any warning. - */ - tokenExpirationToastWarningSeconds?: number | null; -} diff --git a/src/utils/account/getAddress.ts b/src/utils/account/getAddress.ts new file mode 100644 index 00000000..c65e0a53 --- /dev/null +++ b/src/utils/account/getAddress.ts @@ -0,0 +1,6 @@ +import { addressSelector } from 'store/selectors'; +import { getState } from 'store/store'; + +export const getAddress = () => { + return addressSelector(getState()); +}; diff --git a/src/utils/account/getIsLoggedIn.ts b/src/utils/account/getIsLoggedIn.ts new file mode 100644 index 00000000..722dd1cb --- /dev/null +++ b/src/utils/account/getIsLoggedIn.ts @@ -0,0 +1,5 @@ +import { getAddress } from './getAddress'; + +export const getIsLoggedIn = () => { + return Boolean(getAddress()); +};