# Wagmi

Integrate MOSS into your existing code base or use connectors such as RainbowKit using the
[@megaeth-labs/wallet-wagmi-connector](https://moss.megaeth.com/developers/packages/wallet-wagmi-connector) package.

> [!NOTE]
> Features such as silent calls and permissions are available using the custom `wallet_` requests. [Learn
> more](https://moss.megaeth.com/developers/packages/wallet-wagmi-connector#wallet-methods)

## Install
Install the MOSS wallet connector for Wagmi into your client.
```bash title="pnpm"
pnpm add @megaeth-labs/wallet-wagmi-connector wagmi viem @tanstack/react-query
```

```bash title="npm"
npm install @megaeth-labs/wallet-wagmi-connector wagmi viem @tanstack/react-query
```

```bash title="yarn"
yarn add @megaeth-labs/wallet-wagmi-connector wagmi viem @tanstack/react-query
```

## Configure
Set your Wagmi config to use the MegaETH chain and MOSS wallet connector.
```ts title="wagmi.ts"
import { mossWallet } from '@megaeth-labs/wallet-wagmi-connector';
import { megaethTestnet } from 'viem/chains';
import { createConfig, http } from 'wagmi';

export const config = createConfig({
    chains: [megaethTestnet],
    connectors: [mossWallet({ network: 'testnet' })],
    transports: {
        [megaethTestnet.id]: http(),
    },
});
```

## Initialise
Initialise the `WagmiProvider` in your app to expose connection information and call methods.

```tsx title="App.tsx"
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { WagmiProvider } from 'wagmi';
import { ConnectButton } from './ConnectButton';
import { config } from './wagmi';

const queryClient = new QueryClient();

export default function App() {
    return (
        <WagmiProvider config={config}>
            <QueryClientProvider client={queryClient}>
                <ConnectButton />
            </QueryClientProvider>
        </WagmiProvider>
    );
}
```

## Connect
Trigger the connect flow for a user to create or use an existing wallet.

```tsx title="ConnectButton.tsx"
import { useAccount, useConnect, useDisconnect } from 'wagmi';

export function ConnectButton() {
    const { address, isConnected } = useAccount();
    const { connect, connectors } = useConnect();
    const { disconnect } = useDisconnect();
    const connector = connectors.find((c) => c.id === 'mossWallet');

    if (isConnected) {
        return <button onClick={() => disconnect()}>{address}</button>;
    }

    return (
        <button disabled={!connector} onClick={() => connector && connect({ connector })}>
            Connect MOSS Wallet
        </button>
    );
}
```

## Wagmi Functions
Methods such as `signMessage` from Wagmi work as normal and follow the standards.

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

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

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

```tsx title="SendTransaction.tsx"
import { parseEther } from 'viem';
import { useAccount, useSendTransaction } from 'wagmi';

export function SendTransaction() {
    const { address } = useAccount();
    const { data: hash, sendTransaction, isPending } = useSendTransaction();

    return (
        <>
            <button
                disabled={!address || isPending}
                onClick={() => sendTransaction({ to: address, value: parseEther('0.001') })}
            >
                Send
            </button>
            {hash && <p>{hash}</p>}
        </>
    );
}
```

## Authenticate
Custom methods such as authentication using our [server authentication flow](https://moss.megaeth.com/developers/concepts/authentication) are
exposed as functions on
the provider.
```tsx title="Authenticate.tsx"
import type { MegaWalletProvider } from '@megaeth-labs/wallet-wagmi-connector';
import { useAccount } from 'wagmi';

export function Authenticate() {
    const { connector } = useAccount();

    async function authenticate() {
        const provider = (await connector?.getProvider()) as MegaWalletProvider;
        const { jwt } = await provider.authenticate();

        // Send the token to your server to verify and start your own session.
        await fetch('/api/login', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ token: jwt }),
        });
    }

    return <button onClick={authenticate}>Sign in</button>;
}
```

## Permissions and Silent Calls
Use permissions and call contracts silently using MOSS's rich permissions model and realtime transactions. [Read
more](https://moss.megaeth.com/developers/concepts/permissions).

```tsx title="SilentCall.tsx"
import type { MegaWalletProvider } from '@megaeth-labs/wallet-wagmi-connector';
import { parseAbi } from 'viem';
import { useAccount, useWriteContract } from 'wagmi';

const address = '0x3e942744C21Eec1D88FBD463Fd0CcE42891Aec5C';
const abi = parseAbi(['function store(uint256 num)']);

export function SilentCall() {
    const { connector } = useAccount();
    const { data: hash, writeContract, isPending } = useWriteContract();

    async function grant() {
        const provider = (await connector?.getProvider()) as MegaWalletProvider;

        // The user approves this once. It throws if they cancel.
        await provider.grantPermissions({
            permissions: {
                expiry: Math.floor(Date.now() / 1000) + 60 * 60 * 3, // 3 hours
                permissions: {
                    calls: [{ to: address, signature: 'store(uint256)' }],
                    spend: [],
                },
            },
        });
    }

    return (
        <>
            <button onClick={grant}>Grant permissions</button>
            {/* No approval screen while the session allows this call. */}
            <button
                disabled={isPending}
                onClick={() => writeContract({ address, abi, functionName: 'store', args: [42n] })}
            >
                Store silently
            </button>
            {hash && <p>{hash}</p>}
        </>
    );
}
```
