• Examples
  • Sign Message

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 * as React from 'react'
import { useSignMessage } from 'wagmi'
import { recoverMessageAddress } from 'viem'
 
export function SignMessage() {
  const recoveredAddress = React.useRef<string>()
  const { data: signMessageData, error, isLoading, signMessage, variables } = useSignMessage()
 
  React.useEffect(() => {
    ;(async () => {
      if (variables?.message && signMessageData) {
        const recoveredAddress = await recoverMessageAddress({
          message: variables?.message,
          signature: signMessageData,
        })
        setRecoveredAddress(recoveredAddress)
      }
    })()
  }, [signMessageData, variables?.message])
 
  return (
    <form
      onSubmit={(event) => {
        event.preventDefault()
        const formData = new FormData(event.target)
        const message = formData.get('message')
        signMessage({ message })
      }}
    >
      <label htmlFor="message">Enter a message to sign</label>
      <textarea
        id="message"
        name="message"
        placeholder="The quick brown fox…"
      />
      <button disabled={isLoading}>
        {isLoading ? 'Check Wallet' : 'Sign Message'}
      </button>
 
      {signMessageData && (
        <div>
          <div>Recovered Address: {recoveredAddress.current}</div>
          <div>Signature: {signMessageData}</div>
        </div>
      )}
 
      {error && <div>{error.message}</div>}
    </form>
  )
}

Step 3: Add To App

Import the SignMessage component and display it when the account is connected.

import { useAccount, useConnect, useDisconnect } from 'wagmi'
 
import { SignMessage } from './SignMessage'
 
export function Profile() {
  const { isConnected } = useAccount()
  const { connect, connectors, error, isLoading, pendingConnector } =
    useConnect()
  const { disconnect } = useDisconnect()
 
  if (isConnected) {
    return (
      <div>
        {/* Account content goes here */}
        <SignMessage />
      </div>
    )
  }
 
  return <div>{/* Connect wallet content goes here */}</div>
}

Wrap Up

That's it! You now have a way for users to sign messages and securely prove control over a wallet address.