Skip to content

Commit

Permalink
fix: fix bug of duplicate modals for wallet connect
Browse files Browse the repository at this point in the history
  • Loading branch information
RanGojo committed May 30, 2023
1 parent 6efb523 commit efb5482
Show file tree
Hide file tree
Showing 11 changed files with 81 additions and 50 deletions.
2 changes: 0 additions & 2 deletions .prettierrc.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
{
"semi": true,
"tabWidth": 2,
"printWidth": 100,
"singleQuote": true,
"trailingComma": "all",
"jsxBracketSameLine": true
}
62 changes: 34 additions & 28 deletions queue-manager/rango-preset/src/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ export function claimQueue() {
* map of transactions hash to the TransactionResponse
*
*/
let swapTransactionToResponseMap: { [id: string]: any } = {};
const swapTransactionToResponseMap: { [id: string]: any } = {};
export function useTransactionsResponse() {
return {
getTransactionResponseByHash: (hash: string) =>
Expand Down Expand Up @@ -286,7 +286,7 @@ export function updateSwapStatus({
const currentStep = getCurrentStep(swap);
if (!!nextStepStatus && !!currentStep) currentStep.status = nextStepStatus;

if (!!nextStatus) swap.status = nextStatus;
if (nextStatus) swap.status = nextStatus;
swap.hasAlreadyProceededToSign = hasAlreadyProceededToSign;
if (!!nextStatus && ['failed', 'success'].includes(nextStatus))
swap.finishTime = new Date().getTime().toString();
Expand Down Expand Up @@ -354,7 +354,7 @@ export function setStepTransactionIds(
const currentStep = getCurrentStep(swap)!;
currentStep.executedTransactionId = txId;
currentStep.executedTransactionTime = new Date().getTime().toString();
if (!!explorerUrl?.url)
if (explorerUrl?.url)
currentStep.explorerUrl = [
...(currentStep.explorerUrl || []),
{
Expand All @@ -376,7 +376,7 @@ export function setStepTransactionIds(
...getStorage(),
swapDetails: swap,
});
if (!!eventType)
if (eventType)
notifier({ eventType: eventType, swap: swap, step: currentStep });
}

Expand Down Expand Up @@ -613,7 +613,7 @@ export async function isNetworkMatchedForTransaction(
if (!fromBlockChain) return false;

if (
!!meta.evmBasedChains.find(
meta.evmBasedChains.find(
(evmBlochain) => evmBlochain.name === fromBlockChain
)
) {
Expand Down Expand Up @@ -783,16 +783,18 @@ export function onBlockForChangeNetwork(
// Try to auto switch
const { type, network } = getRequiredWallet(swap);
if (!!type && !!network) {
const result = context.switchNetwork(type, network);
if (result) {
result
.then(() => {
queue.unblock();
})
.catch((error) => {
// ignore switch network errors
console.log({ error });
});
if (context.canSwitchNetworkTo(type, network)) {
const result = context.switchNetwork(type, network);
if (result) {
result
.then(() => {
queue.unblock();
})
.catch((error) => {
// ignore switch network errors
console.log({ error });
});
}
}
}
}
Expand Down Expand Up @@ -860,7 +862,12 @@ export function onDependsOnOtherQueues(
resetClaimedBy: () => {
reset();
// TODO: Use key generator
retryOn(`${type}-${network}:${address}`, context.notifier, manager);
retryOn(
`${type}-${network}:${address}`,
context.notifier,
manager,
context.canSwitchNetworkTo
);
},
});
}
Expand Down Expand Up @@ -1147,7 +1154,7 @@ export function checkWaitingForNetworkChange(manager?: Manager): void {
*/
export function getRunningSwaps(manager: Manager): PendingSwap[] {
const queues = manager?.getAll() || new Map<QueueName, QueueInfo>();
let result: PendingSwap[] = [];
const result: PendingSwap[] = [];
queues.forEach((q) => {
// retry only on affected queues
const queueStorage = q.list.getStorage() as SwapStorage | undefined;
Expand Down Expand Up @@ -1204,6 +1211,7 @@ export function retryOn(
wallet_network: string,
notifier: SwapQueueContext['notifier'],
manager?: Manager,
canSwitchNetworkTo?: (type: WalletType, network: Network) => boolean,
options = { fallbackToOnlyWallet: true }
): void {
const [wallet, network] = splitWalletNetwork(wallet_network);
Expand Down Expand Up @@ -1258,7 +1266,9 @@ export function retryOn(
finalQueueToBeRun = onlyWalletMatched[0];
}

finalQueueToBeRun?.checkBlock();
if (!canSwitchNetworkTo?.(wallet, network as Network))
finalQueueToBeRun?.unblock();
else finalQueueToBeRun?.checkBlock();
}

/*
Expand All @@ -1276,17 +1286,13 @@ For backward compatibilty with server and sdk, we use this wrapper to reject the
export async function throwOnOK(
rawResponse: Promise<CreateTransactionResponse>
): Promise<CreateTransactionResponse> {
try {
const responseBody = await rawResponse;
if (!responseBody.ok || !responseBody.transaction) {
throw PrettyError.CreateTransaction(
responseBody.error || 'bad response from create tx endpoint'
);
}
return responseBody;
} catch (e) {
throw e;
const responseBody = await rawResponse;
if (!responseBody.ok || !responseBody.transaction) {
throw PrettyError.CreateTransaction(
responseBody.error || 'bad response from create tx endpoint'
);
}
return responseBody;
}

export function cancelSwap(
Expand Down
7 changes: 6 additions & 1 deletion queue-manager/rango-preset/src/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,12 @@ function useQueueManager(params: UseQueueManagerParams): void {
manager,
notifier: params.notifier,
});
retryOn(params.lastConnectedWallet, params.notifier, manager);
retryOn(
params.lastConnectedWallet,
params.notifier,
manager,
params.canSwitchNetworkTo
);
}
}, [params.lastConnectedWallet]);

Expand Down
2 changes: 2 additions & 0 deletions queue-manager/rango-preset/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ export interface SwapQueueContext extends QueueContext {
wallet: WalletType,
network: Network
) => Promise<ConnectResult> | undefined;
canSwitchNetworkTo: (type: WalletType, network: Network) => boolean;
connect: (
wallet: WalletType,
network: Network
Expand All @@ -74,4 +75,5 @@ export interface UseQueueManagerParams {
clearDisconnectedWallet: () => void;
evmChains: EvmBlockchainMeta[];
notifier: SwapQueueContext['notifier'];
canSwitchNetworkTo: (type: WalletType, network: Network) => boolean;
}
3 changes: 3 additions & 0 deletions wallets/core/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,9 @@ export type GetInstanceOptions = {
currentProvider: any;
meta: BlockchainMeta[];
force?: boolean;
updateChainId: (chainId: number | string) => void;
};

export type GetInstance =
| (() => any)
| ((options: GetInstanceOptions) => Promise<any>);
Expand Down Expand Up @@ -91,6 +93,7 @@ export type SwitchNetwork = (options: {
export type CanSwitchNetwork = (options: {
network: Network;
meta: BlockchainMeta[];
// instance: any;
}) => boolean;

export interface WalletActions {
Expand Down
18 changes: 13 additions & 5 deletions wallets/core/src/wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ class Wallet<InstanceType = any> {
const requestedNetwork =
network || currentNetwork || this.options.config.defaultNetwork;

if (!!eagerConnection) {
if (eagerConnection) {
const networkChanged =
currentNetwork !== requestedNetwork && !!requestedNetwork;

Expand All @@ -105,6 +105,7 @@ class Wallet<InstanceType = any> {
instance: this.provider,
meta: this.meta,
// TODO: Fix type error
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
network: requestedNetwork,
newInstance: this.tryGetInstance.bind(this),
Expand Down Expand Up @@ -219,10 +220,12 @@ class Wallet<InstanceType = any> {
canSwitchNetworkTo(network: Network) {
const switchTo = this.actions.canSwitchNetworkTo;
if (!switchTo) return false;
// const instance = this.tryGetInstance({ network });

return switchTo({
network,
meta: this.meta,
// instance,
});
}

Expand All @@ -237,7 +240,6 @@ class Wallet<InstanceType = any> {

setProvider(value: any) {
this.provider = value;

if (!!value && !!this.actions.subscribe) {
this.actions.subscribe({
instance: value,
Expand All @@ -260,7 +262,7 @@ class Wallet<InstanceType = any> {
}
},
updateChainId: (chainId) => {
const network = !!chainId
const network = chainId
? getBlockChainNameFromId(chainId, this.meta)
: Network.Unknown;
this.updateState({
Expand Down Expand Up @@ -353,19 +355,25 @@ class Wallet<InstanceType = any> {
// We only kill the session (and not restting the whole state)
// So we are relying on this.provider for achieving this functionality.
this.setProvider(null);

if (this.options.config.isAsyncInstance) {
// Trying to connect
const instanceOptions: GetInstanceOptions = {
currentProvider: this.provider,
meta: this.meta,
force: force || false,
updateChainId: (chainId) => {
const network = chainId
? getBlockChainNameFromId(chainId, this.meta)
: Network.Unknown;
this.updateState({
network,
});
},
};

if (network) {
instanceOptions.network = network;
}

instance = await this.actions.getInstance(instanceOptions);
} else {
instance = this.actions.getInstance();
Expand Down
6 changes: 4 additions & 2 deletions wallets/provider-walletconnect/src/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const BRIDGE_URL = 'https://bridge.walletconnect.org';

export function supportsForSwitchNetworkRequest(provider: any): boolean {
const wallets = ['metamask'];
const connectedWallet = provider.peerMeta ? provider.peerMeta.name : '';
const connectedWallet = provider?.peerMeta?.name || '';

return wallets.some((wallet) => {
return connectedWallet.toLowerCase().includes(wallet);
Expand Down Expand Up @@ -38,7 +38,9 @@ export function makeConnection(options: {
// If `force` is true, Creating a new instance,
// Otherwise try to use old connection if availabe
// (returns null if there is no old connection)
let currentProvider = force ? new WalletConnectClient(clientOptions) : provider;
let currentProvider = force
? new WalletConnectClient(clientOptions)
: provider;
const hasProvider = !!currentProvider;
const onCloseModal = () => {
reject(new Error('QRCode modal has been closed.'));
Expand Down
16 changes: 8 additions & 8 deletions wallets/provider-walletconnect/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import {
SwitchNetwork,
WalletConfig,
convertEvmBlockchainMetaToEvmChainInfo,
canSwitchNetworkToEvm,
switchOrAddNetworkForMetamaskCompatibleWallets,
WalletInfo,
} from '@rango-dev/wallets-shared';
Expand All @@ -30,11 +29,8 @@ export const config: WalletConfig = {
isAsyncInstance: true,
};

export const getInstance: GetInstance = async ({
network,
currentProvider,
meta,
}) => {
export const getInstance: GetInstance = async (options) => {
const { network, currentProvider, meta, updateChainId } = options;
// If `network` is provided, trying to get chainId
const evm_chain_info = convertEvmBlockchainMetaToEvmChainInfo(
meta as EvmBlockchainMeta[]
Expand All @@ -47,6 +43,8 @@ export const getInstance: GetInstance = async ({
chainId: requestedChainId,
});

if (options.force && requestedChainId) updateChainId?.(requestedChainId);

return nextInstance;
};

Expand Down Expand Up @@ -142,13 +140,15 @@ export const switchNetwork: SwitchNetwork = async ({

await instance.killSession();

if (!!newInstance) {
if (newInstance) {
await newInstance({ force: true, network });
}
}
};

export const canSwitchNetworkTo: CanSwitchNetwork = canSwitchNetworkToEvm;
export const canSwitchNetworkTo: CanSwitchNetwork = () => {
return false;
};

export const disconnect: Disconnect = async ({ instance, destroyInstance }) => {
if (instance && instance.peerMeta) {
Expand Down
1 change: 1 addition & 0 deletions wallets/shared/src/rango.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,7 @@ export type GetInstanceOptions = {
currentProvider: any;
meta: BlockchainMeta[];
force?: boolean;
updateChainId: (chainId: number | string) => void;
};

export type TryGetInstance =
Expand Down
7 changes: 4 additions & 3 deletions widget/embedded/src/QueueManager.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { walletAndSupportedChainsNames } from './utils/wallets';
import { isEvmBlockchain } from 'rango-sdk';
import { getConfig } from './utils/configs';

function QueueManager(props: PropsWithChildren<{}>) {
function QueueManager(props: PropsWithChildren) {
const {
providers,
getSigners,
Expand Down Expand Up @@ -103,10 +103,12 @@ function QueueManager(props: PropsWithChildren<{}>) {
},
getSigners,
//todo: remove Network type
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore
wallets,
providers: allProviders,
switchNetwork,
canSwitchNetworkTo,
connect,
state,
isMobileWallet,
Expand All @@ -120,8 +122,7 @@ function QueueManager(props: PropsWithChildren<{}>) {
onPersistedDataLoaded={(manager) => {
checkWaitingForNetworkChange(manager);
}}
isPaused={false}
>
isPaused={false}>
{props.children}
</ManagerProvider>
);
Expand Down
Loading

0 comments on commit efb5482

Please sign in to comment.