64 lines
1.6 KiB
TypeScript
Raw Normal View History

2023-10-30 23:57:10 +01:00
import React from "react";
import { useStore } from "./useStore";
import { isEthereumEvenEmitterValid } from "@/utils/ethereum";
import { useRLN } from "./useRLN";
type UseWalletResult = {
2023-11-06 23:48:24 +01:00
onWalletConnect: () => void;
2023-10-30 23:57:10 +01:00
};
export const useWallet = (): UseWalletResult => {
const { rln } = useRLN();
2023-11-07 01:26:09 +01:00
const { setEthAccount, setChainID, setWalletConnected } = useStore();
2023-10-30 23:57:10 +01:00
React.useEffect(() => {
const ethereum = window.ethereum;
if (!isEthereumEvenEmitterValid(ethereum)) {
console.log("Cannot subscribe to ethereum events.");
return;
}
const onAccountsChanged = (accounts: string[]) => {
setEthAccount(accounts[0] || "");
};
ethereum.on("accountsChanged", onAccountsChanged);
const onChainChanged = (chainID: string) => {
const ID = parseInt(chainID, 16);
setChainID(ID);
};
ethereum.on("chainChanged", onChainChanged);
return () => {
ethereum.removeListener("chainChanged", onChainChanged);
ethereum.removeListener("accountsChanged", onAccountsChanged);
};
}, [setEthAccount, setChainID]);
2023-11-06 23:48:24 +01:00
const onWalletConnect = async () => {
const ethereum = window.ethereum;
if (!ethereum) {
console.log("No ethereum instance found.");
return;
}
if (!rln?.rlnInstance) {
console.log("RLN instance is not initialized.");
return;
}
try {
await window.ethereum.request({ method: 'eth_requestAccounts' });
await rln.initRLNContract(rln.rlnInstance);
2023-11-07 01:26:09 +01:00
setWalletConnected();
2023-11-06 23:48:24 +01:00
} catch(error) {
console.error("Failed to conenct to wallet.");
}
};
2023-10-30 23:57:10 +01:00
return {
2023-11-06 23:48:24 +01:00
onWalletConnect,
2023-10-30 23:57:10 +01:00
};
};