Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add provider strategy #46

Merged
merged 23 commits into from
Dec 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@
"glob": "10.3.14",
"immer": "^10.1.1",
"jest": "29.7.0",
"jest-environment-jsdom": "29.7.0",
"msw": "1.3.1",
"node-stdlib-browser": "1.2.0",
"prettier": "3.2.5",
Expand Down
6 changes: 3 additions & 3 deletions src/constants/network.constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export const fallbackNetworkConfigurations: Record<
walletConnectBridgeAddresses: ['https://bridge.walletconnect.org'],
walletConnectV2RelayAddresses: ['wss://relay.walletconnect.com'],
walletAddress: 'https://devnet-wallet.multiversx.com',
metamaskSnapWalletAddress: 'https://devnet-snap-wallet.multiversx.com',
iframeWalletAddress: 'https://devnet-snap-wallet.multiversx.com',
xAliasAddress: 'https://devnet.xalias.com',
apiAddress: 'https://devnet-api.multiversx.com',
explorerAddress: 'http://devnet-explorer.multiversx.com',
Expand All @@ -38,7 +38,7 @@ export const fallbackNetworkConfigurations: Record<
walletConnectBridgeAddresses: ['https://bridge.walletconnect.org'],
walletConnectV2RelayAddresses: ['wss://relay.walletconnect.com'],
walletAddress: 'https://testnet-wallet.multiversx.com',
metamaskSnapWalletAddress: 'https://testnet-snap-wallet.multiversx.com',
iframeWalletAddress: 'https://testnet-snap-wallet.multiversx.com',
xAliasAddress: 'https://testnet.xalias.com',
apiAddress: 'https://testnet-api.multiversx.com',
explorerAddress: 'http://testnet-explorer.multiversx.com',
Expand All @@ -58,7 +58,7 @@ export const fallbackNetworkConfigurations: Record<
walletConnectBridgeAddresses: ['https://bridge.walletconnect.org'],
walletConnectV2RelayAddresses: ['wss://relay.walletconnect.com'],
walletAddress: 'https://wallet.multiversx.com',
metamaskSnapWalletAddress: 'https://snap-wallet.multiversx.com',
iframeWalletAddress: 'https://snap-wallet.multiversx.com',
xAliasAddress: 'https://xalias.com',
apiAddress: 'https://api.multiversx.com',
explorerAddress: 'https://explorer.multiversx.com',
Expand Down
14 changes: 13 additions & 1 deletion src/core/methods/initApp/initApp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@ import { ProviderFactory } from 'core/providers/ProviderFactory';
import { getDefaultNativeAuthConfig } from 'services/nativeAuth/methods/getDefaultNativeAuthConfig';
import { NativeAuthConfigType } from 'services/nativeAuth/nativeAuth.types';
import { initializeNetwork } from 'store/actions';
import { setNativeAuthConfig } from 'store/actions/config/configActions';
import {
setCrossWindowConfig,
setNativeAuthConfig,
setWalletConnectConfig
} from 'store/actions/config/configActions';
import { defaultStorageCallback } from 'store/storage';
import { initStore } from 'store/store';
import { InitAppType } from './initApp.types';
Expand Down Expand Up @@ -54,6 +58,14 @@ export async function initApp({
setNativeAuthConfig(nativeAuthConfig);
}

if (dAppConfig?.providers?.walletConnect) {
setWalletConnectConfig(dAppConfig.providers.walletConnect);
}

if (dAppConfig?.providers?.crossWindow) {
setCrossWindowConfig(dAppConfig.providers.crossWindow);
}

if (shouldEnableTransactionTracker) {
trackTransactions();
}
Expand Down
6 changes: 6 additions & 0 deletions src/core/methods/initApp/initApp.types.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { CrossWindowConfig } from 'core/providers/helpers/crossWindow/crossWindow.type';
import { WalletConnectConfig } from 'core/providers/helpers/walletConnect/walletConnect.types';
import { ICustomProvider } from 'core/providers/types/providerFactory.types';
import { NativeAuthConfigType } from 'services/nativeAuth/nativeAuth.types';
import { StorageCallback } from 'store/storage';
Expand All @@ -16,6 +18,10 @@ type BaseDappConfigType = {
* default: `true`
*/
enableTansactionTracker?: boolean;
providers?: {
crossWindow?: CrossWindowConfig;
walletConnect?: WalletConnectConfig;
};
};

export type EnvironmentDappConfigType = BaseDappConfigType & {
Expand Down
162 changes: 162 additions & 0 deletions src/core/providers-strategy/CrossWindowProviderStrategy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
import { Message, Transaction } from '@multiversx/sdk-core/out';
import { isBrowserWithPopupConfirmation } from 'constants/browser.constants';
import { getAccount } from 'core/methods/account/getAccount';
import { getAddress } from 'core/methods/account/getAddress';
import { IProvider } from 'core/providers/types/providerFactory.types';
import { CrossWindowProvider } from 'lib/sdkWebWalletCrossWindowProvider';
import { crossWindowConfigSelector } from 'store/selectors';
import { networkSelector } from 'store/selectors/networkSelectors';
import { getState } from 'store/store';
import { ProviderErrorsEnum } from 'types';

type CrossWindowProviderProps = {
address?: string;
walletAddress?: string;
};

export class CrossWindowProviderStrategy {
private provider: CrossWindowProvider | null = null;
private address: string;
private walletAddress?: string;
private _signTransactions:
| ((transactions: Transaction[]) => Promise<Transaction[]>)
| null = null;
private _signMessage: ((messageToSign: Message) => Promise<Message>) | null =
null;

constructor(config?: CrossWindowProviderProps) {
this.address = config?.address || '';
this.walletAddress = config?.walletAddress;
}

public createProvider = async (): Promise<IProvider> => {
this.initialize();
const network = networkSelector(getState());

if (!this.provider) {
this.provider = CrossWindowProvider.getInstance();
this.provider.init();
}

// Bind in order to break reference
this._signTransactions = this.provider.signTransactions.bind(this.provider);
this._signMessage = this.provider.signMessage.bind(this.provider);

this.provider.setWalletUrl(this.walletAddress || network.walletAddress);
this.provider.setAddress(this.address);

this.setPopupConsent();

return this.buildProvider();
};

private buildProvider = () => {
arhtudormorar marked this conversation as resolved.
Show resolved Hide resolved
if (!this.provider) {
throw new Error(ProviderErrorsEnum.notInitialized);
}

const provider = this.provider as unknown as IProvider;

provider.setAccount({ address: this.address });
provider.signTransactions = this.signTransactions;
provider.signMessage = this.signMessage;

return provider;
};

private initialize = () => {
if (this.address) {
return;
}

const address = getAddress();

if (!address) {
return;
}

this.address = address;
};

private signTransactions = async (transactions: Transaction[]) => {
if (!this.provider || !this._signTransactions) {
throw new Error(ProviderErrorsEnum.notInitialized);
}

this.setPopupConsent();

const signedTransactions: Transaction[] =
(await this._signTransactions(transactions)) ?? [];

// Guarded Transactions or Signed Transactions
return this.getTransactions(signedTransactions);
};

private signMessage = async (message: Message) => {
if (!this.provider || !this._signMessage) {
throw new Error(ProviderErrorsEnum.notInitialized);
}

this.setPopupConsent();
return this._signMessage(message);
};

private setPopupConsent = () => {
const crossWindowDappConfig = crossWindowConfigSelector(getState());

if (!this.provider) {
throw new Error(ProviderErrorsEnum.notInitialized);
}

if (
crossWindowDappConfig?.isBrowserWithPopupConfirmation ||
isBrowserWithPopupConfirmation
) {
this.provider.setShouldShowConsentPopup(true);
}
};

private getTransactions = async (transactions: Transaction[]) => {
if (!this.provider) {
throw new Error(ProviderErrorsEnum.notInitialized);
}

const { isGuarded } = getAccount();

const allSignedByGuardian = this.getAreAllTransactionsSignedByGuardian({
isGuarded,
transactions
});

const needs2FAsigning = isGuarded && !allSignedByGuardian;

if (needs2FAsigning) {
const guardedTransactions =
await this.provider.guardTransactions(transactions);

return guardedTransactions;
}

return transactions;
};

private getAreAllTransactionsSignedByGuardian = ({
transactions,
isGuarded
}: {
transactions: Transaction[];
isGuarded?: boolean;
}) => {
if (!isGuarded) {
return true;
}

if (transactions.length === 0) {
return false;
}

return transactions.every((tx) =>
Boolean(tx.getGuardianSignature().toString('hex'))
);
};
}
48 changes: 48 additions & 0 deletions src/core/providers-strategy/ExtensionProviderStrategy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { ExtensionProvider } from '@multiversx/sdk-extension-provider/out/extensionProvider';
import { getAddress } from 'core/methods/account/getAddress';
import { IProvider } from 'core/providers/types/providerFactory.types';
import { ProviderErrorsEnum } from 'types';

export class ExtensionProviderStrategy {
private address: string = '';
private provider: ExtensionProvider | null = null;

constructor(address?: string) {
this.address = address || '';
}

public createProvider = async (): Promise<IProvider> => {
this.initialize();

if (!this.provider) {
this.provider = ExtensionProvider.getInstance();
await this.provider.init();
}

return this.buildProvider();
};

private buildProvider = () => {
arhtudormorar marked this conversation as resolved.
Show resolved Hide resolved
if (!this.provider) {
throw new Error(ProviderErrorsEnum.notInitialized);
}

const provider = this.provider as unknown as IProvider;
provider.setAccount({ address: this.address });
return provider;
};

private initialize = () => {
if (this.address) {
return;
}

const address = getAddress();

if (!address) {
return;
}

this.address = address;
};
}
70 changes: 70 additions & 0 deletions src/core/providers-strategy/IFrameProviderStrategy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { IframeProvider } from '@multiversx/sdk-web-wallet-iframe-provider/out';
import { IframeLoginTypes } from '@multiversx/sdk-web-wallet-iframe-provider/out/constants';
import { getAccount } from 'core/methods/account/getAccount';
import { getAddress } from 'core/methods/account/getAddress';
import { IProvider } from 'core/providers/types/providerFactory.types';
import { networkSelector } from 'store/selectors/networkSelectors';
import { getState } from 'store/store';
import { ProviderErrorsEnum } from 'types';

type IFrameProviderType = {
type: IframeLoginTypes;
address?: string;
};
export class IFrameProviderStrategy {
private provider: IframeProvider | null = null;
private address?: string;
private type: IframeLoginTypes | null = null;

constructor({ type, address }: IFrameProviderType) {
this.type = type;
this.address = address;
}

public createProvider = async (): Promise<IProvider> => {
this.initialize();
const network = networkSelector(getState());

if (!this.type) {
throw new Error(ProviderErrorsEnum.invalidType);
}

if (!this.provider) {
this.provider = IframeProvider.getInstance();
await this.provider.init();
}

this.provider.setLoginType(this.type);
this.provider.setWalletUrl(String(network.iframeWalletAddress));

return this.buildProvider();
};

private buildProvider = () => {
const { address } = getAccount();

if (!this.provider) {
throw new Error(ProviderErrorsEnum.notInitialized);
}

const provider = this.provider as unknown as IProvider;

provider.setAccount({ address: this.address || address });

return provider;
};

private initialize = () => {
if (this.address) {
arhtudormorar marked this conversation as resolved.
Show resolved Hide resolved
return;
}

const address = getAddress();

if (!address) {
return;
}

this.address = address;
};
}
Loading
Loading