# wallet-wagmi-connector

A [wagmi](https://wagmi.sh) connector for MOSS, built on [wallet-sdk](https://moss.megaeth.com/developers/packages/wallet-sdk). Add it to your
wagmi config and the standard wagmi hooks work with the wallet. It also adds MOSS to RainbowKit, ConnectKit, Reown
AppKit and Dynamic.

```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
```

The package needs wagmi 2.16.9 or later, including wagmi 3, and viem 2.37.6 or later. RainbowKit, AppKit and Dynamic
are optional, and are only needed if you import from their entry points.

## Connecting

### `mossWallet`

Creates the wagmi connector. It takes the same options as
[`initialise`](https://moss.megaeth.com/developers/packages/wallet-sdk#connecting), and `network` defaults to `mainnet`. The connector's `id`
is `mossWallet`.

```ts title="Types"
mossWallet: (parameters?: MegaWalletParameters) => CreateConnectorFn;

type MegaWalletParameters = {
    network?: 'mainnet' | 'testnet'; // Defaults to 'mainnet'
    logging?: 'debug' | 'info' | 'warn' | 'error';
    devMode?: boolean;
    devUIUrl?: string;
    debug?: boolean;
    sponsorUrl?: string;
    sponsorMode?: 'everything' | 'app-only' | 'explicit';
    sponsorToken?: 'native' | 'usdm';
    handshakeTimeoutMs?: number;
    silentDefault?: boolean; // Defaults to true
};
```

```ts title="wagmi.ts"
import { mossWallet } from '@megaeth-labs/wallet-wagmi-connector';
import { megaeth } from 'viem/chains';
import { createConfig, http } from 'wagmi';

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

> [!NOTE]
> Your config's `chains` must include the chain for the connector's network: `megaeth` for `mainnet` and
> `megaethTestnet` for `testnet`. Otherwise the connector throws `ChainNotConfiguredError`.

Then use wagmi as you would with any other connector:

```tsx title="Example"
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>
    );
}
```

`useSignMessage`, `useSignTypedData` and `useSendTransaction` work too. See [Limitations](#limitations) for the
transaction fields the connector accepts.

### Connector Metadata

The function returned by `mossWallet` carries the wallet's details in `metadata`, for building a wallet list. The same
`id`, `name`, `icon` and `rdns` are on the connector instance, with `type` set to `injected`.

```ts title="Example"
import { mossWallet } from '@megaeth-labs/wallet-wagmi-connector';

const connector = mossWallet({ network: 'testnet' });

connector.metadata.id; // 'mossWallet'
connector.metadata.name; // 'MOSS Wallet'
connector.metadata.icon; // A data URI
connector.metadata.rdns; // 'com.megaeth.account'
```

## RainbowKit

### `mossWalletRainbowKit`

Wraps `mossWallet` as a RainbowKit `Wallet`. RainbowKit only lists wallets from its own wallet list, so a plain wagmi
connector doesn't appear in its modal. Import it from the `/rainbowkit` entry point.

```ts title="Types"
mossWalletRainbowKit: (parameters?: MegaWalletParameters) => Wallet;
```

```ts title="wagmi.ts"
import { mossWalletRainbowKit } from '@megaeth-labs/wallet-wagmi-connector/rainbowkit';
import { connectorsForWallets, getDefaultWallets } from '@rainbow-me/rainbowkit';
import { megaethTestnet } from 'viem/chains';
import { createConfig, http } from 'wagmi';

const { wallets } = getDefaultWallets();

const connectors = connectorsForWallets(
    [
        {
            groupName: 'Recommended',
            wallets: [() => mossWalletRainbowKit({ network: 'testnet' })],
        },
        ...wallets,
    ],
    { appName: 'Your App', projectId: 'your-project-id' },
);

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

Leave out `getDefaultWallets` to list MOSS on its own. To change how MOSS appears in the modal, spread the result and
override what you need:

```ts title="Example"
wallets: [
    () => ({
        ...mossWalletRainbowKit({ network: 'testnet' }),
        iconUrl: '/custom-wallet.svg',
    }),
],
```

> [!NOTE]
> If RainbowKit's connecting modal covers the wallet, raise the wallet's iframe above it with your own CSS.

## ConnectKit

ConnectKit accepts wagmi connectors directly, so pass `mossWallet` to `getDefaultConfig`. No adapter is needed.

> [!WARNING]
> The `connectors` option replaces ConnectKit's default connectors. Add `getDefaultConnectors` to keep
> them.

```ts title="wagmi.ts"
import { mossWallet } from '@megaeth-labs/wallet-wagmi-connector';
import { getDefaultConfig, getDefaultConnectors } from 'connectkit';
import { megaethTestnet } from 'viem/chains';
import { createConfig, http } from 'wagmi';

const appName = 'Your App';
const walletConnectProjectId = 'your-project-id';

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

## Reown AppKit

AppKit also accepts wagmi connectors directly, so pass `mossWallet` to `WagmiAdapter`. Its `/appkit` entry point has two
helpers for the rest of the setup.

### `getMossWalletAppKitNetwork`

Returns a network in the shape AppKit expects, because AppKit doesn't take viem chains directly. `network` defaults to
`mainnet`.

```ts title="Types"
getMossWalletAppKitNetwork: (network?: 'mainnet' | 'testnet') => AppKitNetwork;
```

### `getMossWalletConnectorImages`

Returns the MOSS icon for AppKit's `connectorImages` option.

```ts title="Types"
getMossWalletConnectorImages: () => Record<string, string>;
```

```tsx title="Example"
import { mossWallet } from '@megaeth-labs/wallet-wagmi-connector';
import {
    getMossWalletAppKitNetwork,
    getMossWalletConnectorImages,
} from '@megaeth-labs/wallet-wagmi-connector/appkit';
import { createAppKit } from '@reown/appkit/react';
import { WagmiAdapter } from '@reown/appkit-adapter-wagmi';

const projectId = 'your-project-id';
const network = getMossWalletAppKitNetwork('testnet');

export const wagmiAdapter = new WagmiAdapter({
    projectId,
    networks: [network],
    connectors: [mossWallet({ network: 'testnet' })],
});

createAppKit({
    adapters: [wagmiAdapter],
    projectId,
    networks: [network],
    metadata: {
        name: 'Your App',
        description: 'Your app description',
        url: 'https://yourapp.example',
        icons: ['https://yourapp.example/icon.png'],
    },
    connectorImages: getMossWalletConnectorImages(),
});
```

## Dynamic

### `MossEvmWalletConnectors`

Adds MOSS to [Dynamic](https://www.dynamic.xyz). Pass it to `walletConnectors`, calling `configure` first to set the
network or other options. Import it from the `/dynamic` entry point, which needs `@dynamic-labs/ethereum`,
`@dynamic-labs/ethereum-core` and `@dynamic-labs/wallet-connector-core` 4.31.2 or later.

```ts title="Types"
MossEvmWalletConnectors.configure: (config: Partial<Config>) => typeof MossEvmWalletConnectors;
```

```tsx title="Example"
import { EthereumWalletConnectors } from '@dynamic-labs/ethereum';
import { DynamicContextProvider } from '@dynamic-labs/sdk-react-core';
import { MossEvmWalletConnectors } from '@megaeth-labs/wallet-wagmi-connector/dynamic';
import type { ReactNode } from 'react';

export function App({ children }: { children: ReactNode }) {
    return (
        <DynamicContextProvider
            settings={{
                environmentId: 'your-environment-id',
                walletConnectors: [
                    EthereumWalletConnectors,
                    MossEvmWalletConnectors.configure({ network: 'testnet' }),
                ],
            }}
        >
            {children}
        </DynamicContextProvider>
    );
}
```

## Wallet Discovery

### `announceMossWalletProvider`

Announces MOSS as an [EIP-6963](https://eips.ethereum.org/EIPS/eip-6963) provider, so code that discovers wallets can
find it. `mossWallet` already does this when wagmi sets it up, so you only need this function on a page that doesn't
use the connector. RainbowKit, ConnectKit and AppKit don't use EIP-6963 for the wallets they list themselves, so it
doesn't replace the setups above.

```ts title="Types"
announceMossWalletProvider: (parameters?: MegaWalletParameters) => void;
```

```ts title="Example"
import { announceMossWalletProvider } from '@megaeth-labs/wallet-wagmi-connector';

announceMossWalletProvider({ network: 'testnet' });
```

## Wallet Methods

Methods that wagmi has no hook for are on the connector's provider, either through `request` or as a method of the same
name. Both run the same code.

```ts title="Example"
import type { MegaWalletProvider } from '@megaeth-labs/wallet-wagmi-connector';
import { config } from './wagmi';

const connector = config.connectors.find((c) => c.id === 'mossWallet');
const provider = (await connector?.getProvider()) as MegaWalletProvider;

// These two calls do the same thing.
const balances = await provider.balances();
const sameBalances = await provider.request({ method: 'wallet_balances' });
```

| `request` method           | Provider method     | Details                                                                |
| -------------------------- | ------------------- | ---------------------------------------------------------------------- |
| `wallet_authenticate`      | `authenticate`      | [`authenticate`](https://moss.megaeth.com/developers/packages/wallet-sdk#authenticate)         |
| `wallet_balances`          | `balances`          | [`balances`](https://moss.megaeth.com/developers/packages/wallet-sdk#balances)                 |
| `wallet_callContract`      | `callContract`      | [`callContract`](https://moss.megaeth.com/developers/packages/wallet-sdk#callcontract)         |
| `wallet_checkout`          | `checkout`          | [`checkout`](https://moss.megaeth.com/developers/packages/wallet-sdk#checkout)                 |
| `wallet_collectible`       | `collectible`       | [`collectible`](https://moss.megaeth.com/developers/packages/wallet-sdk#collectible)           |
| `wallet_deposit`           | `deposit`           | [`deposit`](https://moss.megaeth.com/developers/packages/wallet-sdk#deposit)                   |
| `wallet_fromMegaName`      | `fromMegaName`      | [`fromMegaName`](https://moss.megaeth.com/developers/packages/wallet-sdk#frommeganame)         |
| `wallet_getFromContract`   | `getFromContract`   | [`getFromContract`](https://moss.megaeth.com/developers/packages/wallet-sdk#getfromcontract)   |
| `wallet_getPermissions`    | `getPermissions`    | [`getPermissions`](https://moss.megaeth.com/developers/packages/wallet-sdk#getpermissions)     |
| `wallet_grantPermissions`  | `grantPermissions`  | [`grantPermissions`](https://moss.megaeth.com/developers/packages/wallet-sdk#grantpermissions) |
| `wallet_manageAccount`     | `manageAccount`     | Takes `{ method, data }`                                               |
| `wallet_open`              | `open`              | [`open`](https://moss.megaeth.com/developers/packages/wallet-sdk#open)                         |
| `wallet_revokePermissions` | `revokePermissions` | [`revokePermissions`](https://moss.megaeth.com/developers/packages/wallet-sdk#revokepermissions) |
| `wallet_send`              | `send`              | [`send`](https://moss.megaeth.com/developers/packages/wallet-sdk#send)                         |
| `wallet_signData`          | `signData`          | [`signData`](https://moss.megaeth.com/developers/packages/wallet-sdk#signdata)                 |
| `wallet_swap`              | `swap`              | [`swap`](https://moss.megaeth.com/developers/packages/wallet-sdk#swap)                         |
| `wallet_toMegaName`        | `toMegaName`        | [`toMegaName`](https://moss.megaeth.com/developers/packages/wallet-sdk#tomeganame)             |
| `wallet_transfer`          | `transfer`          | [`transfer`](https://moss.megaeth.com/developers/packages/wallet-sdk#transfer)                 |

## Limitations

- **One network per connector:** the connector doesn't switch chains. Asking for another chain throws
  `SwitchChainNotSupportedError`.
- **One configuration per page:** the SDK initialises once per page load, so a second connector with different options
  throws an error.
- **Transaction fields:** `eth_sendTransaction` takes `to`, `value`, `data`, `from` and `chainId`, and `to` is required.
  It rejects `gas`, `gasPrice`, `maxFeePerGas`, `maxPriorityFeePerGas`, `nonce`, `type`, `accessList`,
  `authorizationList`, `blobs` and `maxFeePerBlobGas`, because the wallet sets those itself.
- **Silent by default:** `eth_sendTransaction` (so `useSendTransaction` and `useWriteContract`) and
  `wallet_callContract` go through `callContract`, so a transaction the app's session key covers is sent without a
  prompt. Set `silentDefault: false` on the connector to be asked about every one.
- **Message signing:** `personal_sign` takes plain text, or hex that decodes to UTF-8 text.
