Skip to content

Commit

Permalink
Dev (#47)
Browse files Browse the repository at this point in the history
* chore: prettier & eslint ignore changeset's md files

* fix: No need refresh when open WalletConnect Modal in QRCode page

* chore: Add vconsole for dev demo

* fix: fixed trustwallet losing status after refreshing

* chore: update release info

* style: Update log output styles

* style: Add switchNetwork log

* refactor: update the `installed` field that detect whether wallet is installed to a function

* fix: fixed conflict issue between trustwallet and metaMask

* docs: update release docs
  • Loading branch information
wenty22 authored Dec 1, 2023
1 parent 515de71 commit e418a56
Show file tree
Hide file tree
Showing 28 changed files with 118 additions and 50 deletions.
5 changes: 5 additions & 0 deletions .changeset/happy-hounds-complain.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@totejs/walletkit': patch
---

refactor: update the `installed` field that detect whether wallet is installed to a function
5 changes: 5 additions & 0 deletions .changeset/late-birds-compare.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@totejs/walletkit': patch
---

Fixed `WalletConnect` automatic connection issue in the follow scenario: connect the WalletConnect -> close browser -> reopen browser -> disconnect -> select WalletConnect, will automatically connect.
5 changes: 5 additions & 0 deletions .changeset/modern-comics-smell.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@totejs/walletkit': patch
---

Fixed conflict issue between trustwallet and metaMask.
4 changes: 1 addition & 3 deletions .changeset/pre.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,5 @@
"@totejs/walletkit": "1.0.7-alpha.2",
"website": "0.0.1"
},
"changesets": [
"lovely-months-argue"
]
"changesets": ["lovely-months-argue"]
}
4 changes: 2 additions & 2 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ export function trustWallet(props: TrustWalletProps = {}): WalletProps {
default: 'https://trustwallet.com/',
},
spinnerColor: '#1098FC',
installed: isTrustWallet(),
isInstalled: isTrustWallet,
createConnector: (chains: Chain[]) => {
return new TrustWalletConnector({
chains,
Expand Down Expand Up @@ -163,7 +163,7 @@ export interface WalletProps {
};
spinnerColor?: string;
showQRCode?: boolean;
installed: boolean | undefined;
isInstalled: () => boolean | undefined;
createConnector: (chains: Chain[]) => Connector;
getDeepLink: () => string | undefined;
getQRCodeUri?: (uri: string) => string;
Expand Down
2 changes: 2 additions & 0 deletions examples/nextjs/pages/_document.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { Html, Head, Main, NextScript } from 'next/document';
import { EthereumScript } from '@totejs/walletkit';

export default function Document() {
return (
<Html lang="en">
<Head>
<title>WalletKit Next.js Example</title>
<EthereumScript />
</Head>
<body>
<Main />
Expand Down
27 changes: 27 additions & 0 deletions packages/walletkit/dev/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,33 @@
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>WalletKit Test Demo</title>
<script>
(function () {
try {
const isMobile =
/android|iPhone|iPad|iPod/i.test(navigator.userAgent) ||
(navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);

if (!isMobile && window.ethereum && window.ethereum.isMetaMask && window.trustwallet) {
const originalEthereum = window.ethereum;

Object.defineProperty(window, 'ethereum', {
enumerable: true,
configurable: true,
set(v) {
if (v.isTrust || v.isTrustWallet) return;
this.value = v;
},
get() {
return this.value ?? originalEthereum;
},
});
}
} catch (err) {
console.error('[ethereum script]', err);
}
})();
</script>
</head>

<body>
Expand Down
30 changes: 30 additions & 0 deletions packages/walletkit/src/components/EthereumScript/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
export function EthereumScript() {
const scriptHtml = `
(function() {
try {
const isMobile =
/android|iPhone|iPad|iPod/i.test(navigator.userAgent) ||
(navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
if (!isMobile && window.ethereum && window.ethereum.isMetaMask && window.trustwallet) {
const originalEthereum = window.ethereum;
Object.defineProperty(window, 'ethereum', {
enumerable: true,
configurable: true,
set(v) {
if (v.isTrust || v.isTrustWallet) return;
this.value = v;
},
get() {
return this.value ?? originalEthereum;
},
});
}
} catch (err) {
console.error('[ethereum script]', err);
}
})()
`;
return <script dangerouslySetInnerHTML={{ __html: scriptHtml }} />;
}
7 changes: 4 additions & 3 deletions packages/walletkit/src/hooks/useClickWallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,9 @@ export function useClickWallet() {
const pass = options.onClickWallet?.(connector, e);
if (pass === false) return;

log('[click wallet] connector', connector);
log('[click wallet] ethereum', window.ethereum);
log('[click wallet]', `connector:`, connector);
log('[click wallet]', `ethereum:`, window.ethereum);
log('[click wallet]', `installed:`, connector._wallet.isInstalled());

const gotoQRcodePage = () => {
setSelectedConnector(connector);
Expand All @@ -44,7 +45,7 @@ export function useClickWallet() {
} else {
onOpenWcModal();
}
} else if (!connector._wallet.installed) {
} else if (!connector._wallet.isInstalled()) {
if (mobile) {
const deepLink = connector._wallet.getDeepLink?.();
if (deepLink) {
Expand Down
6 changes: 0 additions & 6 deletions packages/walletkit/src/hooks/useConnector.ts

This file was deleted.

2 changes: 1 addition & 1 deletion packages/walletkit/src/hooks/useWalletConnectModal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export function useWalletConnectModal() {
try {
await connectAsync({ connector });
} catch (err) {
log('WalletConnect', err);
log('[open walletconnect modal]', err);
}

setIsOpen(false);
Expand Down
8 changes: 5 additions & 3 deletions packages/walletkit/src/hooks/useWalletKitConnect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ import { commonErrorHandler } from '@/utils/common';
import { useConnect } from 'wagmi';
import { useWalletKitContext } from '..';

export function useWalletKitConnect({ ...props }: any = {}): ReturnType<typeof useConnect> {
export type UseWalletKitConnectProps = Parameters<typeof useConnect>[0];

export function useWalletKitConnect(props?: UseWalletKitConnectProps) {
const { log, options } = useWalletKitContext();

const connectProps = {
Expand All @@ -11,13 +13,13 @@ export function useWalletKitConnect({ ...props }: any = {}): ReturnType<typeof u

const { connect, connectAsync, connectors, ...rest } = useConnect({
...props,
onError(error: any) {
onError(error: Error, ...params) {
commonErrorHandler({
log,
handler: options.onError,
error,
});
props?.onError?.(error);
props?.onError?.(error, ...params);
},
});

Expand Down
10 changes: 5 additions & 5 deletions packages/walletkit/src/hooks/useWalletKitSwitchNetwork.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,20 @@ import { commonErrorHandler } from '@/utils/common';
import { useSwitchNetwork } from 'wagmi';
import { useWalletKitContext } from '..';

export function useWalletKitSwitchNetwork({ ...props }: any = {}): ReturnType<
typeof useSwitchNetwork
> {
export type UseWalletKitSwitchNetworkProps = Parameters<typeof useSwitchNetwork>[0];

export function useWalletKitSwitchNetwork(props?: UseWalletKitSwitchNetworkProps) {
const { log, options } = useWalletKitContext();

const result = useSwitchNetwork({
...props,
onError(error: any) {
onError(error: Error, ...params) {
commonErrorHandler({
log,
handler: options.onError,
error,
});
props?.onError?.(error);
props?.onError?.(error, ...params);
},
});

Expand Down
1 change: 1 addition & 0 deletions packages/walletkit/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export * from './components/WalletKitButton';
export * from './components/WalletKitProvider';
export * from './components/WalletKitProvider/context';
export * from './components/SwitchNetworkModal';
export * from './components/EthereumScript';
export { useModal } from './components/ModalProvider/context';
export { type ThemeMode, type ThemeVariant } from './components/ThemeProvider';

Expand Down
10 changes: 6 additions & 4 deletions packages/walletkit/src/pages/Connecting/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@ export function ConnectingPage() {
const logos = useWalletLogos(wallet.logos);
const downloadUrl = useWalletDownloadUrl(wallet.downloadUrls);

const [status, setStatus] = useState(!wallet.installed ? states.UNAVAILABLE : states.CONNECTING);
const [status, setStatus] = useState(
wallet.isInstalled() ? states.CONNECTING : states.UNAVAILABLE,
);

const { connect } = useWalletKitConnect({
onMutate: (connector?: any) => {
Expand Down Expand Up @@ -85,14 +87,14 @@ export function ConnectingPage() {
});

const runConnect = useCallback(() => {
if (!wallet.installed) return;
if (!wallet.isInstalled()) return;

if (selectedConnector) {
connect({ connector: selectedConnector });
} else {
setStatus(states.UNAVAILABLE);
}
}, [connect, selectedConnector, wallet.installed]);
}, [connect, selectedConnector, wallet]);

useEffect(() => {
if (status === states.UNAVAILABLE) return;
Expand All @@ -104,7 +106,7 @@ export function ConnectingPage() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

log('[Connect]', status, selectedConnector?.name);
log('[connecting page]', `name: ${selectedConnector?.name}, status: ${status}`);

const isError = [states.FAILED, states.NOTCONNECTED, states.REJECTED].includes(status);
const isLoading = status === states.CONNECTING;
Expand Down
4 changes: 3 additions & 1 deletion packages/walletkit/src/pages/SwitchNetwork/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,14 @@ import {
import { ModalFooter } from '@/base/components/Modal/ModalFooter';

export function SwitchNetworkPage() {
const { supportedChains } = useWalletKitContext();
const { supportedChains, log } = useWalletKitContext();
const { isLoading, switchNetwork, pendingChainId } = useWalletKitSwitchNetwork();
const { chain } = useNetwork();
const { isClosable } = useModal();

const onSwitchNetwork = (chainId: number) => {
log('[switch network page]', 'switchNetwork:', switchNetwork, ', isLoading:', isLoading);

if (switchNetwork && !isLoading) {
switchNetwork(chainId);
}
Expand Down
6 changes: 1 addition & 5 deletions packages/walletkit/src/wallets/binanceWeb3Wallet/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export function binanceWeb3Wallet(props: PartialCustomProps = {}): WalletProps {
},
spinnerColor: undefined,
showQRCode: true,
installed: isBinanceWeb3Wallet(),
isInstalled: isBinanceWeb3Wallet,
createConnector: (chains: Chain[]) => {
return new CustomConnector({
id: BINANCE_WEB3_WALLET_ID,
Expand Down Expand Up @@ -53,9 +53,5 @@ export function binanceWeb3Wallet(props: PartialCustomProps = {}): WalletProps {
export function isBinanceWeb3Wallet() {
if (typeof window === 'undefined') return false;

if (isMobile()) {
return !!window.ethereum;
}

return false;
}
2 changes: 1 addition & 1 deletion packages/walletkit/src/wallets/coinbaseWallet/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export function coinbaseWallet(props: CoinbaseWalletProps = {}): WalletProps {
},
spinnerColor: undefined,
showQRCode: false,
installed: isCoinbaseWallet(),
isInstalled: isCoinbaseWallet,
createConnector: (chains: Chain[]) => {
const { appName } = getGlobalData();

Expand Down
2 changes: 1 addition & 1 deletion packages/walletkit/src/wallets/injected/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export function injected(props: InjectedProps = {}): WalletProps {
default: undefined,
},
showQRCode: false,
installed: isInjected(),
isInstalled: isInjected,
createConnector: (chains: Chain[]) => {
return new InjectedConnector({
chains,
Expand Down
2 changes: 1 addition & 1 deletion packages/walletkit/src/wallets/mathWallet/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export function mathWallet(props: PartialCustomProps = {}): WalletProps {
},
showQRCode: false,
spinnerColor: undefined,
installed: isMathWallet(),
isInstalled: isMathWallet,
createConnector: (chains: Chain[]) => {
return new CustomConnector({
id: MATH_WALLET_ID,
Expand Down
2 changes: 1 addition & 1 deletion packages/walletkit/src/wallets/metaMask/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export function metaMask(props: MetaMaskProps = {}): WalletProps {
},
spinnerColor: '#F0B90B',
showQRCode: false,
installed: isMetaMask(),
isInstalled: isMetaMask,
createConnector: (chains: Chain[]) => {
return new MetaMaskConnector({
chains,
Expand Down
4 changes: 2 additions & 2 deletions packages/walletkit/src/wallets/okxWallet/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export function okxWallet(props: PartialCustomProps = {}): WalletProps {
},
spinnerColor: undefined,
showQRCode: false,
installed: isOkxWallet(),
isInstalled: isOkxWallet,
createConnector: (chains: Chain[]) => {
return new CustomConnector({
id: OKX_WALLET_ID,
Expand Down Expand Up @@ -60,5 +60,5 @@ export function isOkxWallet() {
return !!(window.ethereum || window.okexchain);
}

return !!(hasInjectedProvider('isOkxWallet') || window.okexchain?.isOkxWallet);
return hasInjectedProvider('isOkxWallet') || window.okexchain?.isOkxWallet;
}
2 changes: 1 addition & 1 deletion packages/walletkit/src/wallets/safe/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export function safe(props: SafeProps = {}): WalletProps {
default: undefined,
},
showQRCode: false,
installed: isSafe(),
isInstalled: isSafe,
createConnector: (chains: Chain[]) => {
return new SafeConnector({
chains,
Expand Down
2 changes: 1 addition & 1 deletion packages/walletkit/src/wallets/tokenPocket/icon.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ export const TokenPocketIcon = (props: SVGIconProps) => {
</linearGradient>
</defs>
<g id="p1" stroke="none" strokeWidth="1" fill="none" fillRule="evenodd">
<g id="tokenpocket" fillRule="nonzero">
<g fillRule="nonzero">
<polygon id="path" fill="#2980FE" points="27.9874275 0 0 0 0 28 27.9874275 28"></polygon>
<g id="group" transform="translate(5.107577, 7.574219)">
<path
Expand Down
4 changes: 2 additions & 2 deletions packages/walletkit/src/wallets/tokenPocket/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export function tokenPocket(props: PartialCustomProps = {}): WalletProps {
},
spinnerColor: '#2980FE',
showQRCode: false,
installed: isTokenPocket(),
isInstalled: isTokenPocket,
createConnector: (chains: Chain[]) => {
return new CustomConnector({
id: TOKEN_POCKET_ID,
Expand Down Expand Up @@ -55,5 +55,5 @@ export function tokenPocket(props: PartialCustomProps = {}): WalletProps {
export function isTokenPocket() {
if (typeof window === 'undefined') return false;

return !!(hasInjectedProvider('isTokenPocket') || window.tokenpocket);
return hasInjectedProvider('isTokenPocket') || window.tokenpocket;
}
8 changes: 3 additions & 5 deletions packages/walletkit/src/wallets/trustWallet/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ export function trustWallet(props: TrustWalletProps = {}): WalletProps {
},
spinnerColor: '#1098FC',
showQRCode: false,
installed: isTrustWallet(),
isInstalled: isTrustWallet,
createConnector: (chains: Chain[]) => {
return new TrustWalletConnector({
chains,
Expand All @@ -66,9 +66,7 @@ export function trustWallet(props: TrustWalletProps = {}): WalletProps {
export function isTrustWallet() {
if (typeof window === 'undefined') return false;

return !!(
hasInjectedProvider('isTrust') ||
window?.trustwallet?.isTrust ||
window?.trustWallet?.isTrust
return (
hasInjectedProvider('isTrust') || window?.trustwallet?.isTrust || window?.trustWallet?.isTrust
);
}
Loading

0 comments on commit e418a56

Please sign in to comment.