Esc

View as Markdownllms.txt

wallet-wagmi-connector

@megaeth-labs/wallet-wagmi-connectorAI Generated

A wagmi (opens in a new tab) connector for MOSS, built on 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.

pnpm 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, and network defaults to mainnet. The connector's id is mossWallet.

tsTypes
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
};
tswagmi.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(),
    },
});

Then use wagmi as you would with any other connector:

tsxExample
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 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.

tsExample
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.

tsTypes
mossWalletRainbowKit: (parameters?: MegaWalletParameters) => Wallet;
tswagmi.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:

tsExample
wallets: [
    () => ({
        ...mossWalletRainbowKit({ network: 'testnet' }),
        iconUrl: '/custom-wallet.svg',
    }),
],

ConnectKit#

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

tswagmi.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.

tsTypes
getMossWalletAppKitNetwork: (network?: 'mainnet' | 'testnet') => AppKitNetwork;

getMossWalletConnectorImages#

Returns the MOSS icon for AppKit's connectorImages option.

tsTypes
getMossWalletConnectorImages: () => Record<string, string>;
tsxExample
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 (opens in a new tab). 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.

tsTypes
MossEvmWalletConnectors.configure: (config: Partial<Config>) => typeof MossEvmWalletConnectors;
tsxExample
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 (opens in a new tab) 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.

tsTypes
announceMossWalletProvider: (parameters?: MegaWalletParameters) => void;
tsExample
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.

tsExample
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 methodProvider methodDetails
wallet_authenticateauthenticateauthenticate
wallet_balancesbalancesbalances
wallet_callContractcallContractcallContract
wallet_checkoutcheckoutcheckout
wallet_collectiblecollectiblecollectible
wallet_depositdepositdeposit
wallet_fromMegaNamefromMegaNamefromMegaName
wallet_getFromContractgetFromContractgetFromContract
wallet_getPermissionsgetPermissionsgetPermissions
wallet_grantPermissionsgrantPermissionsgrantPermissions
wallet_manageAccountmanageAccountTakes { method, data }
wallet_openopenopen
wallet_revokePermissionsrevokePermissionsrevokePermissions
wallet_sendsendsend
wallet_signDatasignDatasignData
wallet_swapswapswap
wallet_toMegaNametoMegaNametoMegaName
wallet_transfertransfertransfer

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.