Sign Message
Signing messages is a great way to securely prove control of a specific address. The example below builds on the Connect Wallet Example and uses the useSignMessage
hook. Try it out before moving on.
Step 1: Connect Wallet
Follow the Connect Wallet guide to get this set up.
Step 2: Add SignMessage Component
Add the useSignMessage
hook and set up a basic form:
import { verifyMessage } from 'ethers/lib/utils'import { useSignMessage } from 'wagmi'
export const SignMessage = () => { const previousMessage = React.useRef<string>() const [message, setMessage] = React.useState('') const [{ data, error, loading }, signMessage] = useSignMessage()
const recoveredAddress = React.useMemo(() => { if (!data || !previousMessage.current) return undefined return verifyMessage(previousMessage.current, data) }, [data, previousMessage])
return ( <form onSubmit={(event) => { event.preventDefault() previousMessage.current = message signMessage({ message }) }} > <label htmlFor="message">Enter a message to sign</label> <textarea id="message" placeholder="The quick brown fox…" onChange={(event) => setMessage(event.target.value)} /> <button disabled={loading || !message.length}> {loading ? 'Check Wallet' : 'Sign Message'} </button>
{data && ( <div> <div>Recovered Address: {recoveredAddress}</div> <div>Signature: {data}</div> </div> )} {error && <div>{error?.message ?? 'Error signing message'}</div>} </form> )}
Step 3: Add To App
Import the SignMessage
component and display it when the account is connected.
import { useAccount, useConnect } from 'wagmi'
import { SignMessage } from './SignMessage'
export const Example = () => { const [{ data: connectData, error: connectError }, connect] = useConnect() const [{ data: accountData }, disconnect] = useAccount({ fetchEns: true, })
if (accountData) { return ( <div> ... <SignMessage /> </div> ) }
return ...}
Wrap Up
That's it! You now have a way for users to sign messages and securely prove control over a wallet address.