Skip to content

Commit

Permalink
chore: export types & logics from useWidget
Browse files Browse the repository at this point in the history
  • Loading branch information
samobasquiat committed Dec 2, 2023
1 parent cb30d14 commit 7c73814
Show file tree
Hide file tree
Showing 12 changed files with 225 additions and 106 deletions.
1 change: 1 addition & 0 deletions queue-manager/core/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './manager';
export { default as Persistor, DB_NAME } from './persistor';
export * from './types';
export type { QueueContext } from './queue';
1 change: 0 additions & 1 deletion queue-manager/rango-preset/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
"peerDependencies": {
"@rango-dev/queue-manager-core": "*",
"@rango-dev/queue-manager-react": "*",
"@rango-dev/wallets-react": "*",
"@rango-dev/wallets-shared": "*",
"@sentry/browser": "*",
"bignumber.js": "*",
Expand Down
54 changes: 8 additions & 46 deletions queue-manager/rango-preset/src/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@ import type {
QueueName,
QueueType,
} from '@rango-dev/queue-manager-core';
import type { Providers } from '@rango-dev/wallets-react';
import type {
Meta,
Network,
Providers,
WalletState,
WalletType,
} from '@rango-dev/wallets-shared';
Expand All @@ -34,11 +34,15 @@ import type {
EvmBlockchainMeta,
Transaction,
} from 'rango-sdk';
import type { APIErrorCode, SignerErrorCode } from 'rango-types/lib';
import type { APIErrorCode, SignerErrorCode } from 'rango-types';

import { Status } from '@rango-dev/queue-manager-core';
import { readAccountAddress } from '@rango-dev/wallets-react';
import { getBlockChainNameFromId, Networks } from '@rango-dev/wallets-shared';
import { readAccountAddress } from '@rango-dev/wallets-core';
import {
getBlockChainNameFromId,
getEvmProvider,
splitWalletNetwork,
} from '@rango-dev/wallets-shared';
import { TransactionType } from 'rango-sdk';

import {
Expand Down Expand Up @@ -128,29 +132,6 @@ export function inMemoryTransactionsData() {
};
}

/**
* Sample inputs are:
* - "metamask-ETH"
* - "metamask-BSC-BSC:0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
* - "token-pocket-BSC-BSC:0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
* Returns "wallet and network" separately, even if the wallet is dashed inside.
*
*/

export function splitWalletNetwork(input: string): string[] {
const removedAddressInput = input?.split(':')[0] || '';
const splittedInput = removedAddressInput.split('-');
const network = splittedInput[splittedInput.length - 1];
const walletNetwork = splittedInput.slice(0, -1);

if (walletNetwork[walletNetwork.length - 1] === network) {
walletNetwork.pop();
}
const wallet = walletNetwork.join('-');

return [wallet, network];
}

/**
*
* Returns `steps`, if it's a `running` swap.
Expand Down Expand Up @@ -624,25 +605,6 @@ export function isWalletNull(wallet: Wallet | null): boolean {
);
}

/**
* On our implementation for `wallets` package, We keep the instance in 2 ways
* If it's a single chain wallet, it returns the instance directly,
* If it's a multichain wallet, it returns a `Map` of instances.
* This function will get the `ETHEREUM` instance in both types.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function getEvmProvider(providers: Providers, type: WalletType): any {
if (type && providers[type]) {
// we need this because provider can return an instance or a map of instances, so what you are doing here is try to detect that.
if (providers[type].size) {
return providers[type].get(Networks.ETHEREUM);
}

return providers[type];
}
return null;
}

/**
* In a `PendingSwap`, each step needs a wallet to proceed,
* By using this function we can access what wallet exactly we need to run current step.
Expand Down
2 changes: 0 additions & 2 deletions queue-manager/rango-preset/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,9 @@ export {
updateSwapStatus,
checkWaitingForNetworkChange,
getCurrentStep,
getEvmProvider,
cancelSwap,
getRequiredWallet,
getRunningSwaps,
splitWalletNetwork,
resetRunningSwapNotifsOnPageLoad,
isApprovalTX,
getLastSuccessfulStep,
Expand Down
10 changes: 7 additions & 3 deletions queue-manager/rango-preset/src/types.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import type { PendingSwap, PendingSwapStep, Wallet } from './shared';
import type { QueueDef, QueueStorage } from '@rango-dev/queue-manager-core';
import type { QueueContext } from '@rango-dev/queue-manager-core/dist/queue';
import type { ConnectResult, Providers } from '@rango-dev/wallets-react';
import type {
QueueContext,
QueueDef,
QueueStorage,
} from '@rango-dev/queue-manager-core';
import type { ConnectResult } from '@rango-dev/wallets-core';
import type {
Meta,
Network,
Providers,
WalletState,
WalletType,
} from '@rango-dev/wallets-shared';
Expand Down
104 changes: 72 additions & 32 deletions wallets/shared/src/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import type { EvmBlockchainMeta } from 'rango-types';
import {
EvmNetworksChainInfo,
import type {
AddEthereumChainParameter,
Network,
Networks,
Connect,
Wallet,
EvmNetworksChainInfo,
InstallObjects,
Network,
Wallet,
} from './rango';
import type { EvmBlockchainMeta } from 'rango-types';

import { Networks } from './rango';

export { isAddress as isEvmAddress } from 'ethers/lib/utils.js';

Expand All @@ -16,7 +17,9 @@ export function deepCopy(obj: any): any {
let copy;

// Handle the 3 simple types, and null or undefined
if (null == obj || 'object' != typeof obj) return obj;
if (null == obj || 'object' != typeof obj) {
return obj;
}

// Handle Date
if (obj instanceof Date) {
Expand All @@ -38,8 +41,9 @@ export function deepCopy(obj: any): any {
if (obj instanceof Object) {
copy = {} as any;
for (const attr in obj) {
if (Object.prototype.hasOwnProperty.call(obj, attr))
if (Object.prototype.hasOwnProperty.call(obj, attr)) {
copy[attr] = deepCopy(obj[attr]);
}
}
return copy;
}
Expand All @@ -61,17 +65,22 @@ export async function switchOrAddNetworkForMetamaskCompatibleWallets(
});
} catch (switchError) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
// To resolve this error: Catch clause variable type annotation must be any or unknown if specified
/*
* @ts-ignore
* To resolve this error: Catch clause variable type annotation must be any or unknown if specified
*/
const error = switchError as { code: number };

if (!targetChain) {
throw new Error(
`It seems you don't have ${network} network on your wallet. Please add it manually.`
);
/* eslint-disable @typescript-eslint/no-magic-numbers */
} else if (error.code === 4902 || !error.code) {
// Note: on WalletConnect `code` is undefined so we have to use !switchError.code as fallback.
// This error code indicates that the chain has not been added to wallet.
/*
* Note: on WalletConnect `code` is undefined so we have to use !switchError.code as fallback.
* This error code indicates that the chain has not been added to wallet.
*/
await instance.request({
method: 'wallet_addEthereumChain',
params: [targetChain],
Expand All @@ -81,7 +90,7 @@ export async function switchOrAddNetworkForMetamaskCompatibleWallets(
}
}

export function timeout<T = any>(
export async function timeout<T = any>(
forPromise: Promise<any>,
time: number
): Promise<T> {
Expand Down Expand Up @@ -122,9 +131,11 @@ export const evmChainsToRpcMap = (
Object.keys(evmNetworkChainInfo).map((chainName) => {
const info = evmNetworkChainInfo[chainName];

// This `if` is only used for satisfying typescript,
// Because we iterating over Object.keys(EVM_NETWORKS_CHAIN_INFO)
// And obviously it cannot be `undefined` and always has a value.
/*
* This `if` is only used for satisfying typescript,
* Because we iterating over Object.keys(EVM_NETWORKS_CHAIN_INFO)
* And obviously it cannot be `undefined` and always has a value.
*/
if (info) {
return [parseInt(info.chainId), info.rpcUrls[0]];
}
Expand Down Expand Up @@ -166,12 +177,17 @@ export function getCoinbaseInstance(
instances.set(Networks.ETHEREUM, ethInstance);
}
}
if (!!coinbaseSolana && lookingFor === 'coinbase')
if (!!coinbaseSolana && lookingFor === 'coinbase') {
instances.set(Networks.SOLANA, coinbaseSolana);
}

if (instances.size === 0) return null;
if (instances.size === 0) {
return null;
}

if (lookingFor === 'metamask') return instances.get(Networks.ETHEREUM);
if (lookingFor === 'metamask') {
return instances.get(Networks.ETHEREUM);
}

return instances;
}
Expand All @@ -189,7 +205,9 @@ function isBrave() {
const nav: any = navigator;
if (nav.brave && nav.brave.isBrave) {
nav.brave.isBrave().then((res: boolean) => {
if (res) isBrave = true;
if (res) {
isBrave = true;
}
});
}

Expand All @@ -199,23 +217,45 @@ function isBrave() {
export function detectInstallLink(install: InstallObjects | string): string {
if (typeof install !== 'object') {
return install;
} else {
let link;
if (isBrave()) {
link = install.BRAVE;
} else if (navigator.userAgent?.toLowerCase().indexOf('chrome') !== -1) {
link = install.CHROME;
} else if (navigator.userAgent?.toLowerCase().indexOf('firefox') !== -1) {
link = install.FIREFOX;
} else if (navigator.userAgent?.toLowerCase().indexOf('edge') !== -1) {
link = install.EDGE;
}
return link || install.DEFAULT;
}
let link;
if (isBrave()) {
link = install.BRAVE;
} else if (navigator.userAgent?.toLowerCase().indexOf('chrome') !== -1) {
link = install.CHROME;
} else if (navigator.userAgent?.toLowerCase().indexOf('firefox') !== -1) {
link = install.FIREFOX;
} else if (navigator.userAgent?.toLowerCase().indexOf('edge') !== -1) {
link = install.EDGE;
}
return link || install.DEFAULT;
}

export function detectMobileScreens(): boolean {
return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
navigator.userAgent
);
}

/**
* Sample inputs are:
* - "metamask-ETH"
* - "metamask-BSC-BSC:0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
* - "token-pocket-BSC-BSC:0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
* Returns "wallet and network" separately, even if the wallet is dashed inside.
*
*/

export function splitWalletNetwork(input: string): string[] {
const removedAddressInput = input?.split(':')[0] || '';
const splittedInput = removedAddressInput.split('-');
const network = splittedInput[splittedInput.length - 1];
const walletNetwork = splittedInput.slice(0, -1);

if (walletNetwork[walletNetwork.length - 1] === network) {
walletNetwork.pop();
}
const wallet = walletNetwork.join('-');

return [wallet, network];
}
Loading

0 comments on commit 7c73814

Please sign in to comment.