Created
November 25, 2022 08:58
-
-
Save indiejoseph/698df2193ee2faff10962cca35c66844 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// copy from: https://github.com/techbandorg/web3ConnectorNPM/blob/86f5badf121b1e592da82426004d13ba8e8d7d0a/src/walletHooks/component/hooks/useSignMessage.tsx | |
import { useState, useEffect } from "react"; | |
import { useWeb3React } from "@web3-react/core"; | |
import { ethers } from "ethers"; | |
import Web3 from "web3"; | |
export const useSignMessage = () => { | |
const { library, account } = useWeb3React(); | |
let web3 = new Web3(library?.provider); | |
const [isVerify, setIsVerify] = useState(false); | |
useEffect(() => {}, [account, isVerify]); | |
const signMessage = async (messageSign?: string) => { | |
if (!library) return; | |
const fortmaticProvider = localStorage.getItem("provider"); | |
try { | |
if (fortmaticProvider === "fortmatic") { | |
await library?.provider.sendAsync( | |
{ | |
method: "personal_sign", | |
params: [messageSign, account], | |
}, | |
(err: any, result: any) => { | |
if (result) { | |
verifyMessage(result.result, messageSign); | |
} else return; | |
if (err) return; | |
} | |
); | |
} else { | |
let signature = await library.provider.request({ | |
method: "personal_sign", | |
params: [ | |
ethers.utils.hexlify(ethers.utils.toUtf8Bytes(messageSign + "")), | |
account, | |
], | |
}); | |
if (signature) { | |
verifyMessage(signature, messageSign); | |
} | |
} | |
} catch (error) { | |
return; | |
} | |
}; | |
const verifyMessage = async (signature: string, messageSign?: string) => { | |
if (!library) return; | |
let recovered = web3.eth.accounts.recover(messageSign + "", signature); | |
if (recovered === account) { | |
setIsVerify(true); | |
} | |
}; | |
return { signMessage, isVerify }; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment