# Sign Message

Present a message to a user to sign. Can be used to implement your own SIWE or prove acceptance of terms. Messages
which follow the SIWE pattern will be validated based on the origin they are being sent from, network and address.

> [!WARNING]
> MOSS wallets are smart accounts which produce ERC-1271 signatures, which are checked by the account contract. See
> below for guidance.

```ts title="Pure JS"
import { mega } from '@megaeth-labs/wallet-sdk';

const result = await mega.signMessage('Hello, World!');

if (result.status === 'success') {
    console.log('Signature:', result.signature);
}
```

```tsx title="React"
import { useSignMessage } from '@megaeth-labs/wallet-sdk-react';

export default function SignButton() {
    const { mutate: signMessage, isPending, data } = useSignMessage();

    return (
        <>
            <button onClick={() => signMessage('Hello, World!')} disabled={isPending}>
                Sign message
            </button>
            {data?.status === 'success' && <p>Signature: {data.signature}</p>}
        </>
    );
}
```

```tsx title="Wagmi"
import { useSignMessage } from 'wagmi';

export default function SignButton() {
    const { signMessage, isPending, data: signature } = useSignMessage();

    return (
        <>
            <button onClick={() => signMessage({ message: 'Hello, World!' })} disabled={isPending}>
                Sign message
            </button>
            {signature && <p>Signature: {signature}</p>}
        </>
    );
}
```

```ts
interface SignMessageResponse {
    status: 'success' | 'cancelled' | 'error';
    error?: string;
    signature?: `0x${string}`;
}
```

## Verifying Signatures
MOSS wallets create ERC-1271 smart account signatures instead of EIP-191 `personal_sign` ones. To verify these
signatures, we recommend using the `@megaeth-labs/wallet-intent` library.

```ts
import { verifyMessage } from '@megaeth-labs/wallet-intent';
import { createPublicClient, http } from 'viem';
import { megaeth } from 'viem/chains';

// Use megaethTestnet for signatures made on testnet.
const client = createPublicClient({ chain: megaeth, transport: http() });

export async function isValidSignature(
    address: `0x${string}`,
    message: string,
    signature: `0x${string}`,
): Promise<boolean> {
    // Asks the account contract to check the signature (ERC-1271), including one
    // from an account that hasn't sent its first transaction yet (ERC-8010).
    return verifyMessage(client, { address, message, signature });
}
```

## SIWE
The `@megaeth-labs/wallet-server-verify` package exists to simplify the process of authenticating a user using SIWE
with your own message and nonce validation.

> [!NOTE]
> MOSS also comes pre-packaged with a mechanism to authenticate a user server side from the client using a JWT
> issued from
> our servers. [Read more](https://moss.megaeth.com/developers/concepts/authentication)

```ts
import {
    getMessageToSign,
    type MessageConfig,
    type MessageToSign,
    verifySignature,
} from '@megaeth-labs/wallet-server-verify';

const config: MessageConfig = {
    scheme: 'https',
    domain: 'app.example.com', // your app's host
    uri: 'https://app.example.com',
    statement: 'Sign in to Example',
    chainId: 4326, // 4326 for mainnet, 6343 for testnet
};

// Messages handed out and not yet used, by nonce. Use your database or cache in production.
const pending = new Map<string, MessageToSign>();
const MAX_AGE_MS = 5 * 60 * 1000;

// POST /api/siwe/message: { address } → the message for the user to sign
export async function createMessage(request: Request): Promise<Response> {
    const { address } = await request.json();
    const toSign = getMessageToSign(config, address);

    pending.set(toSign.nonce, toSign);
    return Response.json({ message: toSign.message, nonce: toSign.nonce });
}

// POST /api/siwe/verify: { nonce, signature } → the verified address
export async function verify(request: Request): Promise<Response> {
    const { nonce, signature } = await request.json();

    // Use the message this server issued, not one sent back by the client, and only once.
    const issued = pending.get(nonce);
    pending.delete(nonce);

    if (!issued || Date.now() - issued.issuedAt.getTime() > MAX_AGE_MS) {
        return new Response('Message expired', { status: 401 });
    }

    try {
        // Throws DIFFERENT_MESSAGE or INVALID_SIGNATURE if the signature doesn't check out.
        await verifySignature(config, { ...issued, signature });
    } catch {
        return new Response('Invalid signature', { status: 401 });
    }

    // Issue your own session for issued.address here.
    return Response.json({ address: issued.address });
}
```
