@coin-voyage/swapkit 0.5.1 → 0.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/components/modal.d.ts +1 -2
- package/dist/components/modal.js +6 -6
- package/dist/components/styles.js +4 -1
- package/dist/components/wallet-connector.d.ts +1 -1
- package/dist/components/wallet-connector.js +11 -62
- package/dist/components/wallet-connector.test.js +77 -15
- package/dist/hooks/use-wallet-connection.d.ts +10 -0
- package/dist/hooks/use-wallet-connection.js +71 -0
- package/package.json +3 -3
|
@@ -3,9 +3,8 @@ interface ModalProps extends PropsWithChildren {
|
|
|
3
3
|
open: boolean;
|
|
4
4
|
title: string;
|
|
5
5
|
onClose: () => void;
|
|
6
|
-
closeDisabled?: boolean;
|
|
7
6
|
preventDismiss?: boolean;
|
|
8
7
|
maxWidth?: number;
|
|
9
8
|
}
|
|
10
|
-
export declare function Modal({ open, title, onClose,
|
|
9
|
+
export declare function Modal({ open, title, onClose, preventDismiss, maxWidth, children }: ModalProps): import("react").ReactPortal | null;
|
|
11
10
|
export {};
|
package/dist/components/modal.js
CHANGED
|
@@ -6,16 +6,16 @@ import { useSwapKit } from "../providers/swapkit-context";
|
|
|
6
6
|
import { SwapKitRoot } from "../styles/root";
|
|
7
7
|
import { CloseIcon } from "./icons";
|
|
8
8
|
import { Dialog, DialogCloseButton, DialogHeader, Overlay } from "./styles";
|
|
9
|
-
export function Modal({ open, title, onClose,
|
|
9
|
+
export function Modal({ open, title, onClose, preventDismiss = false, maxWidth, children }) {
|
|
10
10
|
const { mode, theme } = useSwapKit();
|
|
11
11
|
const previousFocus = useRef(null);
|
|
12
12
|
const onCloseRef = useRef(onClose);
|
|
13
|
-
const passiveDismissDisabledRef = useRef(
|
|
13
|
+
const passiveDismissDisabledRef = useRef(preventDismiss);
|
|
14
14
|
const titleId = useId();
|
|
15
15
|
useEffect(() => {
|
|
16
16
|
onCloseRef.current = onClose;
|
|
17
|
-
passiveDismissDisabledRef.current =
|
|
18
|
-
}, [
|
|
17
|
+
passiveDismissDisabledRef.current = preventDismiss;
|
|
18
|
+
}, [onClose, preventDismiss]);
|
|
19
19
|
useEffect(() => {
|
|
20
20
|
if (!open)
|
|
21
21
|
return;
|
|
@@ -33,8 +33,8 @@ export function Modal({ open, title, onClose, closeDisabled = false, preventDism
|
|
|
33
33
|
if (!open || typeof document === "undefined")
|
|
34
34
|
return null;
|
|
35
35
|
const closeFromOverlay = (event) => {
|
|
36
|
-
if (event.target === event.currentTarget && !
|
|
36
|
+
if (event.target === event.currentTarget && !preventDismiss)
|
|
37
37
|
onClose();
|
|
38
38
|
};
|
|
39
|
-
return createPortal(_jsx(SwapKitRoot, { "$mode": mode, "$customTheme": theme, "data-swapkit-portal": "", children: _jsx(Overlay, { onMouseDown: closeFromOverlay, children: _jsx(Dialog, { "$maxWidth": maxWidth, role: "dialog", "aria-modal": "true", "aria-labelledby": titleId, children: _jsxs(FocusTrap, { children: [_jsxs(DialogHeader, { children: [_jsx("h2", { id: titleId, children: title }),
|
|
39
|
+
return createPortal(_jsx(SwapKitRoot, { "$mode": mode, "$customTheme": theme, "data-swapkit-portal": "", children: _jsx(Overlay, { onMouseDown: closeFromOverlay, children: _jsx(Dialog, { "$maxWidth": maxWidth, role: "dialog", "aria-modal": "true", "aria-labelledby": titleId, children: _jsxs(FocusTrap, { children: [_jsxs(DialogHeader, { children: [_jsx("h2", { id: titleId, children: title }), _jsx(DialogCloseButton, { type: "button", "aria-label": "Close dialog", onClick: onClose, children: _jsx(CloseIcon, {}) })] }), children] }) }) }) }), document.body);
|
|
40
40
|
}
|
|
@@ -589,6 +589,8 @@ export const ErrorBox = styled.div `
|
|
|
589
589
|
color: var(--sk-danger);
|
|
590
590
|
background: color-mix(in srgb, var(--sk-danger) 10%, transparent);
|
|
591
591
|
font-size: 12px;
|
|
592
|
+
overflow-wrap: anywhere;
|
|
593
|
+
white-space: pre-line;
|
|
592
594
|
`;
|
|
593
595
|
export const PrimaryButton = styled.button `
|
|
594
596
|
display: inline-flex;
|
|
@@ -726,6 +728,7 @@ export const SearchField = styled.div `
|
|
|
726
728
|
export const PickerBody = styled.div `
|
|
727
729
|
position: relative;
|
|
728
730
|
min-width: 0;
|
|
731
|
+
min-height: min(404px, calc(100vh - 122px));
|
|
729
732
|
`;
|
|
730
733
|
export const PickerControls = styled.div `
|
|
731
734
|
position: relative;
|
|
@@ -746,7 +749,7 @@ export const NetworkMenu = styled.div `
|
|
|
746
749
|
right: 0;
|
|
747
750
|
display: grid;
|
|
748
751
|
width: min(202px, 100%);
|
|
749
|
-
max-height: min(360px, calc(100vh -
|
|
752
|
+
max-height: min(360px, calc(100vh - 166px));
|
|
750
753
|
align-content: start;
|
|
751
754
|
padding: 4px;
|
|
752
755
|
overflow-y: auto;
|
|
@@ -1,20 +1,12 @@
|
|
|
1
|
-
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
-
import {
|
|
3
|
-
import { useInstalledWallets, useUniversalConnect } from "@coin-voyage/crypto/hooks";
|
|
4
|
-
import { getConnectorId, getErrorMessage, isWalletConnectionCancelledError } from "@coin-voyage/crypto/utils";
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
|
2
|
+
import { useInstalledWallets } from "@coin-voyage/crypto/hooks";
|
|
5
3
|
import { getChainTypeName } from "@coin-voyage/shared/chain";
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import { EmptyState, Hint, MultichainBadge, WalletList, WalletOption, WalletOptionMeta, WalletSwitchButton, } from "./styles";
|
|
4
|
+
import { useMemo, useState } from "react";
|
|
5
|
+
import { useWalletConnection } from "../hooks/use-wallet-connection";
|
|
6
|
+
import { EmptyState, ErrorBox, Hint, MultichainBadge, PrimaryButton, WalletList, WalletOption, WalletOptionMeta, WalletSwitchButton, } from "./styles";
|
|
9
7
|
import { Modal } from "./modal";
|
|
10
8
|
import { WalletIconDisplay } from "./wallet-icon";
|
|
11
9
|
const getWalletDisplayName = (wallet) => wallet.id.toLowerCase() === "walletconnect" ? "Mobile Wallets" : wallet.name;
|
|
12
|
-
const addWalletConnectModalStyle = () => {
|
|
13
|
-
const style = document.createElement("style");
|
|
14
|
-
style.textContent = "w3m-modal, wcm-modal { --wcm-z-index: 2147483647; --w3m-z-index: 2147483647; }";
|
|
15
|
-
document.head.appendChild(style);
|
|
16
|
-
return style;
|
|
17
|
-
};
|
|
18
10
|
export function WalletConnector(props) {
|
|
19
11
|
if (!props.open)
|
|
20
12
|
return null;
|
|
@@ -25,55 +17,12 @@ function OpenWalletConnector({ chainType, intent = "connect", beforeConnect, onC
|
|
|
25
17
|
const wallets = useMemo(() => chainType
|
|
26
18
|
? installedWallets.filter((wallet) => wallet.connectors.some((connector) => connector.chainType === chainType))
|
|
27
19
|
: installedWallets, [chainType, installedWallets]);
|
|
28
|
-
const
|
|
29
|
-
const [pending, setPending] = useState(false);
|
|
20
|
+
const { pendingLabel, error, connect, cancel } = useWalletConnection(onClose, beforeConnect);
|
|
30
21
|
const [selectedWallet, setSelectedWallet] = useState(null);
|
|
31
|
-
const
|
|
22
|
+
const pending = pendingLabel !== null;
|
|
32
23
|
const selectedConnectors = selectedWallet
|
|
33
24
|
? selectedWallet.connectors.filter((connector, index, connectors) => connectors.findIndex((candidate) => candidate.chainType === connector.chainType) === index)
|
|
34
25
|
: [];
|
|
35
|
-
const close = () => {
|
|
36
|
-
pendingRef.current = false;
|
|
37
|
-
onClose();
|
|
38
|
-
};
|
|
39
|
-
const showError = (error) => {
|
|
40
|
-
if (isWalletConnectionCancelledError(error))
|
|
41
|
-
return;
|
|
42
|
-
setError(getErrorMessage(error) || "Unable to connect wallet");
|
|
43
|
-
};
|
|
44
|
-
const { connect } = useUniversalConnect({
|
|
45
|
-
onSuccess: close,
|
|
46
|
-
onError: showError,
|
|
47
|
-
});
|
|
48
|
-
const handleConnect = async (connector) => {
|
|
49
|
-
if (pendingRef.current)
|
|
50
|
-
return;
|
|
51
|
-
pendingRef.current = true;
|
|
52
|
-
setPending(true);
|
|
53
|
-
setError(null);
|
|
54
|
-
let walletConnectModalStyle;
|
|
55
|
-
try {
|
|
56
|
-
await beforeConnect?.();
|
|
57
|
-
const connectorId = getConnectorId(connector.connector);
|
|
58
|
-
const isWalletConnect = connectorId?.toLowerCase().includes("walletconnect");
|
|
59
|
-
if (isWalletConnect)
|
|
60
|
-
walletConnectModalStyle = addWalletConnectModalStyle();
|
|
61
|
-
const walletConnector = connector.chainType === ChainType.EVM && isWalletConnect
|
|
62
|
-
? { ...connector, connector: await createWalletConnectModalConnector(connector.connector) }
|
|
63
|
-
: connector;
|
|
64
|
-
await connect({ walletConnector });
|
|
65
|
-
}
|
|
66
|
-
catch (error) {
|
|
67
|
-
showError(error);
|
|
68
|
-
}
|
|
69
|
-
finally {
|
|
70
|
-
walletConnectModalStyle?.remove();
|
|
71
|
-
const shouldUpdatePending = pendingRef.current;
|
|
72
|
-
pendingRef.current = false;
|
|
73
|
-
if (shouldUpdatePending)
|
|
74
|
-
setPending(false);
|
|
75
|
-
}
|
|
76
|
-
};
|
|
77
26
|
const chooseWallet = (wallet) => {
|
|
78
27
|
const connectors = wallet.connectors.filter(({ chainType: connectorChainType }) => !chainType || connectorChainType === chainType);
|
|
79
28
|
if (!chainType && new Set(connectors.map((connector) => connector.chainType)).size > 1) {
|
|
@@ -81,14 +30,14 @@ function OpenWalletConnector({ chainType, intent = "connect", beforeConnect, onC
|
|
|
81
30
|
return;
|
|
82
31
|
}
|
|
83
32
|
if (connectors[0])
|
|
84
|
-
void
|
|
33
|
+
void connect(connectors[0], getWalletDisplayName(wallet));
|
|
85
34
|
};
|
|
86
35
|
const modalTitle = selectedWallet ? "Choose network" : intent === "switch" ? "Switch wallet" : "Connect wallet";
|
|
87
|
-
return (_jsxs(Modal, { open: true, title: modalTitle, onClose:
|
|
36
|
+
return (_jsxs(Modal, { open: true, title: modalTitle, onClose: onClose, preventDismiss: pending, children: [selectedWallet && (_jsx(WalletSwitchButton, { type: "button", disabled: pending, onClick: () => setSelectedWallet(null), children: "Back" })), _jsx(WalletList, { "aria-busy": pending, children: selectedWallet
|
|
88
37
|
? selectedConnectors.map((connector) => {
|
|
89
38
|
const chainName = getChainTypeName(connector.chainType);
|
|
90
39
|
const walletName = getWalletDisplayName(selectedWallet);
|
|
91
|
-
return (_jsxs(WalletOption, { type: "button", disabled: pending, "aria-label": `Connect ${walletName} on ${chainName}`, onClick: () => void
|
|
40
|
+
return (_jsxs(WalletOption, { type: "button", disabled: pending, "aria-label": `Connect ${walletName} on ${chainName}`, onClick: () => void connect(connector, walletName), children: [_jsx(WalletIconDisplay, { icon: selectedWallet.icon, name: chainName }), _jsxs(WalletOptionMeta, { children: [_jsx("span", { children: _jsx("strong", { children: chainName }) }), _jsxs("small", { children: [chainName, " network"] })] })] }, connector.chainType));
|
|
92
41
|
})
|
|
93
42
|
: wallets.map((wallet) => {
|
|
94
43
|
const connector = wallet.connectors.find((candidate) => !chainType || candidate.chainType === chainType);
|
|
@@ -98,5 +47,5 @@ function OpenWalletConnector({ chainType, intent = "connect", beforeConnect, onC
|
|
|
98
47
|
const chainTypes = [...new Set(wallet.connectors.map(({ chainType }) => chainType))];
|
|
99
48
|
const capabilityLabel = chainTypes.map(getChainTypeName).join(" · ");
|
|
100
49
|
return (_jsxs(WalletOption, { type: "button", disabled: pending, "aria-label": `${intent === "switch" ? "Switch to" : "Connect"} ${walletName} wallet`, onClick: () => chooseWallet(wallet), children: [_jsx(WalletIconDisplay, { icon: wallet.icon, name: walletName }), _jsxs(WalletOptionMeta, { children: [_jsxs("span", { children: [_jsx("strong", { children: walletName }), chainTypes.length > 1 && _jsx(MultichainBadge, { children: "Multichain" })] }), _jsx("small", { children: chainTypes.length > 1 ? capabilityLabel : `${capabilityLabel} wallet` })] })] }, wallet.id));
|
|
101
|
-
}) }), !selectedWallet && wallets.length === 0 && _jsx(EmptyState, { children: "No compatible installed wallets found" }),
|
|
50
|
+
}) }), !selectedWallet && wallets.length === 0 && _jsx(EmptyState, { children: "No compatible installed wallets found" }), pending && (_jsxs(_Fragment, { children: [_jsxs(Hint, { role: "status", children: ["Waiting for ", pendingLabel, ". Open your wallet to approve the request."] }), _jsx(PrimaryButton, { type: "button", style: { marginTop: 12 }, onClick: cancel, children: "Cancel" })] })), error && (_jsxs(ErrorBox, { role: "alert", style: { marginTop: 12 }, children: [_jsx("strong", { children: error.title }), _jsx("div", { children: error.details }), _jsx("div", { children: "Unlock your wallet, check it for open requests, and try again." })] }))] }));
|
|
102
51
|
}
|
|
@@ -8,7 +8,6 @@ import { WalletConnector } from "./wallet-connector";
|
|
|
8
8
|
import { Overlay } from "./styles";
|
|
9
9
|
const connectWallet = vi.fn();
|
|
10
10
|
const createWalletConnectModalConnector = vi.fn();
|
|
11
|
-
let connectErrorHandler;
|
|
12
11
|
let installedWallets = [
|
|
13
12
|
{
|
|
14
13
|
id: "phantom",
|
|
@@ -18,22 +17,19 @@ let installedWallets = [
|
|
|
18
17
|
];
|
|
19
18
|
vi.mock("@coin-voyage/crypto/hooks", () => ({
|
|
20
19
|
useInstalledWallets: () => installedWallets,
|
|
21
|
-
useUniversalConnect: ({
|
|
22
|
-
connectErrorHandler = onError;
|
|
23
|
-
return { connect: connectWallet };
|
|
24
|
-
},
|
|
20
|
+
useUniversalConnect: () => ({ connect: connectWallet }),
|
|
25
21
|
}));
|
|
26
22
|
vi.mock("@coin-voyage/crypto/connectors", () => ({
|
|
27
23
|
createWalletConnectModalConnector: (...args) => createWalletConnectModalConnector(...args),
|
|
28
24
|
}));
|
|
29
25
|
vi.mock("./modal", () => ({
|
|
30
|
-
Modal: ({ open, title,
|
|
26
|
+
Modal: ({ open, title, preventDismiss, children, }) => open ? (_jsx("div", { role: "dialog", "aria-label": title, "data-prevent-dismiss": preventDismiss || undefined, children: children })) : null,
|
|
31
27
|
}));
|
|
32
28
|
afterEach(() => {
|
|
33
29
|
cleanup();
|
|
30
|
+
vi.useRealTimers();
|
|
34
31
|
connectWallet.mockReset();
|
|
35
32
|
createWalletConnectModalConnector.mockReset();
|
|
36
|
-
connectErrorHandler = undefined;
|
|
37
33
|
installedWallets = [
|
|
38
34
|
{
|
|
39
35
|
id: "phantom",
|
|
@@ -63,7 +59,7 @@ describe("WalletConnector", () => {
|
|
|
63
59
|
await user.dblClick(option);
|
|
64
60
|
expect(connectWallet).toHaveBeenCalledTimes(1);
|
|
65
61
|
expect(option.hasAttribute("disabled")).toBe(true);
|
|
66
|
-
expect(screen.getByRole("dialog").getAttribute("data-
|
|
62
|
+
expect(screen.getByRole("dialog").getAttribute("data-prevent-dismiss")).toBe("true");
|
|
67
63
|
finishConnect?.();
|
|
68
64
|
await waitFor(() => expect(option.hasAttribute("disabled")).toBe(false));
|
|
69
65
|
});
|
|
@@ -128,16 +124,82 @@ describe("WalletConnector", () => {
|
|
|
128
124
|
failConnect?.();
|
|
129
125
|
await waitFor(() => expect([...document.head.querySelectorAll("style")].some((style) => style.textContent?.includes("--w3m-z-index: 2147483647"))).toBe(false));
|
|
130
126
|
});
|
|
131
|
-
it("does not show viem's resource-unavailable error when the wallet prompt is closed", () => {
|
|
127
|
+
it("does not show viem's resource-unavailable error when the wallet prompt is closed", async () => {
|
|
128
|
+
connectWallet.mockRejectedValue(new Error("Requested resource not available. Details: Requested resource not available. Version: viem@2.55.10"));
|
|
132
129
|
render(_jsx(WalletConnector, { open: true, onClose: vi.fn() }));
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
130
|
+
await userEvent.click(screen.getByRole("button", { name: "Connect Phantom wallet" }));
|
|
131
|
+
expect(connectWallet).toHaveBeenCalledTimes(1);
|
|
132
|
+
expect(screen.queryByRole("alert")).toBeNull();
|
|
133
|
+
});
|
|
134
|
+
it("names the wallet and network and shows actionable error details", async () => {
|
|
135
|
+
connectWallet.mockRejectedValue({ code: -32603, message: "Unexpected error" });
|
|
136
|
+
const onClose = vi.fn();
|
|
137
|
+
render(_jsx(WalletConnector, { open: true, onClose: onClose }));
|
|
138
|
+
await userEvent.click(screen.getByRole("button", { name: "Connect Phantom wallet" }));
|
|
139
|
+
const alert = screen.getByRole("alert").textContent;
|
|
140
|
+
expect(alert).toContain("Couldn't connect Phantom on Solana");
|
|
141
|
+
expect(alert).toContain("Unexpected error (code -32603)");
|
|
142
|
+
expect(onClose).not.toHaveBeenCalled();
|
|
143
|
+
});
|
|
144
|
+
it.each([
|
|
145
|
+
["success", (late) => late.resolve()],
|
|
146
|
+
["failure", (late) => late.reject(new Error("Too late"))],
|
|
147
|
+
])("cancels a pending request and ignores its late %s", async (_result, settle) => {
|
|
148
|
+
const late = Promise.withResolvers();
|
|
149
|
+
connectWallet.mockReturnValue(late.promise);
|
|
150
|
+
const onClose = vi.fn();
|
|
151
|
+
render(_jsx(WalletConnector, { open: true, onClose: onClose }));
|
|
152
|
+
const option = screen.getByRole("button", { name: "Connect Phantom wallet" });
|
|
153
|
+
await userEvent.click(option);
|
|
154
|
+
await userEvent.click(screen.getByRole("button", { name: "Cancel" }));
|
|
155
|
+
await act(async () => settle(late));
|
|
156
|
+
expect(option.hasAttribute("disabled")).toBe(false);
|
|
157
|
+
expect(onClose).not.toHaveBeenCalled();
|
|
136
158
|
expect(screen.queryByRole("alert")).toBeNull();
|
|
137
159
|
});
|
|
138
|
-
it("still
|
|
160
|
+
it("explains a request that is still open in the wallet when retrying after a cancel", async () => {
|
|
161
|
+
connectWallet
|
|
162
|
+
.mockReturnValueOnce(new Promise(() => { }))
|
|
163
|
+
.mockRejectedValueOnce(new Error("Requested resource not available."))
|
|
164
|
+
.mockResolvedValueOnce(undefined);
|
|
165
|
+
const onClose = vi.fn();
|
|
166
|
+
render(_jsx(WalletConnector, { open: true, onClose: onClose }));
|
|
167
|
+
const option = screen.getByRole("button", { name: "Connect Phantom wallet" });
|
|
168
|
+
await userEvent.click(option);
|
|
169
|
+
await userEvent.click(screen.getByRole("button", { name: "Cancel" }));
|
|
170
|
+
await userEvent.click(option);
|
|
171
|
+
expect(screen.getByRole("alert").textContent).toContain("Requested resource not available.");
|
|
172
|
+
await userEvent.click(option);
|
|
173
|
+
expect(onClose).toHaveBeenCalledTimes(1);
|
|
174
|
+
});
|
|
175
|
+
it("ignores a late success after the dialog is closed", async () => {
|
|
176
|
+
let finish;
|
|
177
|
+
connectWallet.mockReturnValue(new Promise((resolve) => (finish = resolve)));
|
|
178
|
+
const onClose = vi.fn();
|
|
179
|
+
const { unmount } = render(_jsx(WalletConnector, { open: true, onClose: onClose }));
|
|
180
|
+
await userEvent.click(screen.getByRole("button", { name: "Connect Phantom wallet" }));
|
|
181
|
+
unmount();
|
|
182
|
+
await act(async () => finish());
|
|
183
|
+
expect(onClose).not.toHaveBeenCalled();
|
|
184
|
+
});
|
|
185
|
+
it("does not connect when cancelled while the previous wallet disconnects", async () => {
|
|
186
|
+
let finishDisconnect;
|
|
187
|
+
const beforeConnect = () => new Promise((resolve) => (finishDisconnect = resolve));
|
|
188
|
+
render(_jsx(WalletConnector, { open: true, beforeConnect: beforeConnect, onClose: vi.fn() }));
|
|
189
|
+
await userEvent.click(screen.getByRole("button", { name: "Connect Phantom wallet" }));
|
|
190
|
+
await userEvent.click(screen.getByRole("button", { name: "Cancel" }));
|
|
191
|
+
await act(async () => finishDisconnect());
|
|
192
|
+
expect(connectWallet).not.toHaveBeenCalled();
|
|
193
|
+
});
|
|
194
|
+
it("times out when the wallet never responds", async () => {
|
|
195
|
+
vi.useFakeTimers();
|
|
196
|
+
connectWallet.mockReturnValue(new Promise(() => { }));
|
|
139
197
|
render(_jsx(WalletConnector, { open: true, onClose: vi.fn() }));
|
|
140
|
-
|
|
141
|
-
|
|
198
|
+
const option = screen.getByRole("button", { name: "Connect Phantom wallet" });
|
|
199
|
+
act(() => option.click());
|
|
200
|
+
expect(option.hasAttribute("disabled")).toBe(true);
|
|
201
|
+
await act(() => vi.advanceTimersByTimeAsync(60000));
|
|
202
|
+
expect(screen.getByRole("alert").textContent).toContain("No response after 60 seconds");
|
|
203
|
+
expect(option.hasAttribute("disabled")).toBe(false);
|
|
142
204
|
});
|
|
143
205
|
});
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { ChainTypeWalletConnector } from "@coin-voyage/crypto/types";
|
|
2
|
+
export declare function useWalletConnection(onConnected: () => void, beforeConnect?: () => Promise<unknown>): {
|
|
3
|
+
pendingLabel: string | null;
|
|
4
|
+
error: {
|
|
5
|
+
title: string;
|
|
6
|
+
details: string;
|
|
7
|
+
} | null;
|
|
8
|
+
connect: (wallet: ChainTypeWalletConnector, walletName: string) => Promise<void>;
|
|
9
|
+
cancel: () => void | undefined;
|
|
10
|
+
};
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { createWalletConnectModalConnector } from "@coin-voyage/crypto/connectors";
|
|
2
|
+
import { useUniversalConnect } from "@coin-voyage/crypto/hooks";
|
|
3
|
+
import { getConnectorId, getErrorDetails, isUserRejectedError, isWalletConnectionCancelledError, } from "@coin-voyage/crypto/utils";
|
|
4
|
+
import { getChainTypeName } from "@coin-voyage/shared/chain";
|
|
5
|
+
import { ChainType } from "@coin-voyage/shared/types";
|
|
6
|
+
import { useEffect, useRef, useState } from "react";
|
|
7
|
+
const CONNECT_TIMEOUT_MS = 60000;
|
|
8
|
+
const addWalletConnectModalStyle = () => {
|
|
9
|
+
const style = document.createElement("style");
|
|
10
|
+
style.textContent = "w3m-modal, wcm-modal { --wcm-z-index: 2147483647; --w3m-z-index: 2147483647; }";
|
|
11
|
+
document.head.appendChild(style);
|
|
12
|
+
return style;
|
|
13
|
+
};
|
|
14
|
+
export function useWalletConnection(onConnected, beforeConnect) {
|
|
15
|
+
const { connect: connectWallet } = useUniversalConnect();
|
|
16
|
+
const [pendingLabel, setPendingLabel] = useState(null);
|
|
17
|
+
const [error, setError] = useState(null);
|
|
18
|
+
const controllerRef = useRef(null);
|
|
19
|
+
const abandonedRef = useRef(false);
|
|
20
|
+
const cancel = () => controllerRef.current?.abort();
|
|
21
|
+
useEffect(() => cancel, []);
|
|
22
|
+
const connect = async (wallet, walletName) => {
|
|
23
|
+
const label = `${walletName} on ${getChainTypeName(wallet.chainType)}`;
|
|
24
|
+
const isWalletConnect = getConnectorId(wallet.connector)?.toLowerCase().includes("walletconnect");
|
|
25
|
+
const controller = new AbortController();
|
|
26
|
+
const { signal } = controller;
|
|
27
|
+
const aborted = new Promise((_, reject) => {
|
|
28
|
+
signal.addEventListener("abort", () => reject(signal.reason));
|
|
29
|
+
});
|
|
30
|
+
const timeout = setTimeout(() => {
|
|
31
|
+
if (!isWalletConnect)
|
|
32
|
+
controller.abort(new Error(`No response after ${CONNECT_TIMEOUT_MS / 1000} seconds`));
|
|
33
|
+
}, CONNECT_TIMEOUT_MS);
|
|
34
|
+
let modalStyle;
|
|
35
|
+
const run = async () => {
|
|
36
|
+
await beforeConnect?.();
|
|
37
|
+
signal.throwIfAborted();
|
|
38
|
+
if (isWalletConnect)
|
|
39
|
+
modalStyle = addWalletConnectModalStyle();
|
|
40
|
+
const walletConnector = isWalletConnect && wallet.chainType === ChainType.EVM
|
|
41
|
+
? { ...wallet, connector: await createWalletConnectModalConnector(wallet.connector) }
|
|
42
|
+
: wallet;
|
|
43
|
+
signal.throwIfAborted();
|
|
44
|
+
await connectWallet({ walletConnector });
|
|
45
|
+
};
|
|
46
|
+
controllerRef.current = controller;
|
|
47
|
+
setPendingLabel(label);
|
|
48
|
+
setError(null);
|
|
49
|
+
try {
|
|
50
|
+
await Promise.race([run(), aborted]);
|
|
51
|
+
onConnected();
|
|
52
|
+
}
|
|
53
|
+
catch (error) {
|
|
54
|
+
abandonedRef.current || (abandonedRef.current = signal.aborted);
|
|
55
|
+
const isCancelled = abandonedRef.current ? isUserRejectedError : isWalletConnectionCancelledError;
|
|
56
|
+
const cancelledHere = error instanceof DOMException && error === signal.reason;
|
|
57
|
+
if (cancelledHere || isCancelled(error))
|
|
58
|
+
return;
|
|
59
|
+
setError({
|
|
60
|
+
title: `Couldn't connect ${label}`,
|
|
61
|
+
details: getErrorDetails(error) || "The wallet returned no error details",
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
finally {
|
|
65
|
+
clearTimeout(timeout);
|
|
66
|
+
modalStyle?.remove();
|
|
67
|
+
setPendingLabel(null);
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
return { pendingLabel, error, connect, cancel };
|
|
71
|
+
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@coin-voyage/swapkit",
|
|
3
3
|
"description": "A reusable cross-chain swap component for CoinVoyage.",
|
|
4
|
-
"version": "0.5.
|
|
4
|
+
"version": "0.5.2",
|
|
5
5
|
"private": false,
|
|
6
6
|
"sideEffects": false,
|
|
7
7
|
"author": "Lars <lars@coinvoyage.io>",
|
|
@@ -28,8 +28,8 @@
|
|
|
28
28
|
"LICENSE"
|
|
29
29
|
],
|
|
30
30
|
"dependencies": {
|
|
31
|
-
"@coin-voyage/shared": "3.
|
|
32
|
-
"@coin-voyage/crypto": "3.
|
|
31
|
+
"@coin-voyage/shared": "3.8.0",
|
|
32
|
+
"@coin-voyage/crypto": "3.8.0"
|
|
33
33
|
},
|
|
34
34
|
"devDependencies": {
|
|
35
35
|
"@testing-library/react": "^16.3.0",
|