Esc

wallet-sdk-react

@megaeth-labs/wallet-sdk-reactAI Generated

React hooks for MOSS, built on wallet-sdk and TanStack Query. Wrap your app in MegaProvider, then use a hook for each wallet function.

pnpm add @megaeth-labs/wallet-sdk-react @tanstack/react-query

Hooks that act, such as useConnect, are TanStack Query mutations: call mutate to run them. Hooks that read, such as useBalances, are queries that run on their own. Each takes TanStack Query's options, apart from the function it runs, and returns TanStack Query's result. Each hook lists its request and response types, which you can import from @megaeth-labs/wallet-sdk.

tsTypes
import type { UndefinedInitialDataOptions, UseMutationOptions } from '@tanstack/react-query';

type MutationOptions<TData, TVariables> = Omit<UseMutationOptions<TData, Error, TVariables>, 'mutationFn'>;
type QueryOptions<TData> = Omit<UndefinedInitialDataOptions<TData, Error>, 'queryKey' | 'queryFn'>;

Connecting#

MegaProvider#

Initialises the wallet for a network and gives its status to every hook inside it. Put it around your whole app. See Initialise and Sponsoring Gas.

tsTypes
MegaProvider: (props: { config: Config; children?: ReactNode }) => JSX.Element;

interface Config {
    network: 'mainnet' | 'testnet';
    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
}
tsxExample
import { MegaProvider } from '@megaeth-labs/wallet-sdk-react';

export default function App() {
    return (
        <MegaProvider config={{ network: 'testnet' }}>
            {/* ...your app */}
        </MegaProvider>
    );
}

To use your own QueryClient instead, for example for its defaults or Devtools, put your QueryClientProvider inside MegaProvider. The hooks use the nearest provider, so they share your client. Your app and the SDK must use the same copy of @tanstack/react-query (version 5).

tsxExample
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { MegaProvider } from '@megaeth-labs/wallet-sdk-react';

const queryClient = new QueryClient();

export default function App() {
    return (
        <MegaProvider config={{ network: 'testnet' }}>
            <QueryClientProvider client={queryClient}>
                {/* ...your app */}
            </QueryClientProvider>
        </MegaProvider>
    );
}

useStatus#

Returns whether a wallet is connected, its address and the network, and updates when they change. See Status.

tsTypes
useStatus: () => {
    initialised: boolean;
    error: Error | null;
    status: 'connected' | 'disconnected' | 'cancelled';
    address?: `0x${string}`;
    network: 'mainnet' | 'testnet';
};
import { useStatus } from '@megaeth-labs/wallet-sdk-react';

export default function Status() {
    const { initialised, status, address, network, error } = useStatus();

    if (error) return <p>Couldn't load the wallet: {error.message}</p>;
    if (!initialised) return <p>Loading…</p>;

    return (
        <ul>
            <li>Status: {status}</li>
            <li>Network: {network}</li>
            {address && <li>Address: {address}</li>}
        </ul>
    );
}
Runs on testnet with your wallet

useConnect#

Asks the user to sign in or create a wallet. See Connect.

tsTypes
useConnect: (
    options?: MutationOptions<ConnectionStatus, ConnectRequest | void>,
) => UseMutationResult<ConnectionStatus, Error, ConnectRequest | void>;

type ConnectionStatus = {
    status: 'connected' | 'disconnected' | 'cancelled';
    address?: `0x${string}`;
    network: 'mainnet' | 'testnet';
};

interface ConnectRequest {
    address?: `0x${string}`;
}
import { useConnect, useStatus } from '@megaeth-labs/wallet-sdk-react';

export default function ConnectButton() {
    const { status, address } = useStatus();
    const { mutate: connect, isPending } = useConnect();

    if (status === 'connected') return <p>Connected: {address}</p>;

    return (
        <button onClick={() => connect()} disabled={isPending}>
            {isPending ? 'Connecting…' : 'Connect wallet'}
        </button>
    );
}
Runs on testnet with your wallet

useDisconnect#

Disconnects the wallet from your app. See Disconnect.

tsTypes
useDisconnect: (
    options?: MutationOptions<ConnectionStatus, void>,
) => UseMutationResult<ConnectionStatus, Error, void>;

type ConnectionStatus = {
    status: 'connected' | 'disconnected' | 'cancelled';
    address?: `0x${string}`;
    network: 'mainnet' | 'testnet';
};
import { useDisconnect } from '@megaeth-labs/wallet-sdk-react';

export default function DisconnectButton() {
    const { mutate: disconnect, isPending } = useDisconnect();

    return (
        <button onClick={() => disconnect()} disabled={isPending}>
            Disconnect
        </button>
    );
}
Runs on testnet with your wallet

Authenticating#

useAuthenticate#

Signs the user in to your server with Sign-In with Ethereum and returns a JWT for your server to verify. See Authenticate and Authentication.

tsTypes
useAuthenticate: (
    options?: MutationOptions<AuthenticateResponse, void>,
) => UseMutationResult<AuthenticateResponse, Error, void>;

interface AuthenticateResponse {
    status: 'success' | 'cancelled' | 'error';
    error?: string;
    jwt?: string;
}
import { useAuthenticate } from '@megaeth-labs/wallet-sdk-react';

export default function SignInButton() {
    const { mutate: authenticate, isPending } = useAuthenticate({
        onSuccess: async (auth) => {
            if (auth.status !== 'success' || !auth.jwt) return;

            await fetch('/api/login', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ token: auth.jwt }),
            });
        },
    });

    return (
        <button onClick={() => authenticate()} disabled={isPending}>
            Sign in
        </button>
    );
}
Runs on testnet with your wallet

Signing#

useSignMessage#

Asks the user to sign a plain text message. See Sign Message.

tsTypes
useSignMessage: (
    options?: MutationOptions<SignMessageResponse, string>,
) => UseMutationResult<SignMessageResponse, Error, string>;

interface SignMessageResponse {
    status: 'success' | 'cancelled' | 'error';
    error?: string;
    signature?: `0x${string}`;
}
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>}
        </>
    );
}
Runs on testnet with your wallet

useSignData#

Asks the user to sign EIP-712 typed data. See Sign Data.

tsTypes
useSignData: (
    options?: MutationOptions<SignDataResponse, SignDataRequest>,
) => UseMutationResult<SignDataResponse, Error, SignDataRequest>;

interface SignDataResponse {
    status: 'success' | 'cancelled' | 'error';
    error?: string;
    signature?: string;
}

interface SignDataRequest {
    data: any;
}
import { useSignData } from '@megaeth-labs/wallet-sdk-react';

const data = {
    domain: { name: 'MyApp', version: '1', chainId: 6343 }, // MegaETH testnet
    types: {
        Person: [
            { name: 'name', type: 'string' },
            { name: 'wallet', type: 'address' },
        ],
    },
    primaryType: 'Person',
    message: { name: 'Alice', wallet: '0xFD8D73c93385271d06138FA0Ff6E9c639C3Bd8b0' },
};

export default function SignDataButton() {
    const { mutate: signData, isPending, data: result } = useSignData();

    return (
        <>
            <button onClick={() => signData({ data })} disabled={isPending}>
                Sign data
            </button>
            {result?.status === 'success' && <p>Signature: {result.signature}</p>}
        </>
    );
}
Runs on testnet with your wallet

Opening the Wallet#

mega.open#

Opens the MOSS wallet. There's no hook for it: call it on the mega object this package re-exports. See Open Wallet and Account Management.

tsTypes
mega.open: () => Promise<void>;
import { mega } from '@megaeth-labs/wallet-sdk-react';

export default function OpenWalletButton() {
    return <button onClick={() => mega.open()}>Open wallet</button>;
}
Runs on testnet with your wallet

Calling Contracts#

useCallContract#

Sends a transaction that calls a contract, or several calls batched into one transaction when given an array. See Call Contract, Permissions and Gas.

A call is silent unless it sets silent: false, or the config sets silentDefault: false. A silent call is sent with the app's session key without a prompt when the key's permissions cover it, whether the app granted them or the user set them up in the wallet, and the user is asked to approve it otherwise. One call with silent: false asks for the whole batch.

tsTypes
useCallContract: (
    options?: MutationOptions<TransactionResult, CallContractRequest | CallContractRequest[]>,
) => UseMutationResult<TransactionResult, Error, CallContractRequest | CallContractRequest[]>;

interface TransactionResult {
    status: 'approved' | 'cancelled' | 'error';
    receipt?: TransactionReceipt;
    receipts?: TransactionReceipt[];
    error?: string;
    silentHasUsedFallback?: boolean;
}

interface CallContractRequest {
    address: `0x${string}`;
    abi?: any;
    functionName?: string;
    args?: any[];
    data?: `0x${string}`;
    silent?: boolean; // Defaults to config.silentDefault
    silentUIApproveFallback?: boolean;
    value?: bigint | string;
    sponsor?: boolean;
    maxGasAllowance?: bigint;
}

interface TransactionReceipt {
    hash: `0x${string}`;
    blockHash: string;
    blockNumber: number;
    chainId: number;
    gasUsed: number;
    logs: { address: `0x${string}`; data: `0x${string}`; topics: string[] }[];
    status: string;
    transactionHash: `0x${string}`;
}
import { useCallContract } from '@megaeth-labs/wallet-sdk-react';

export default function StoreButton() {
    const { mutate: callContract, isPending, data } = useCallContract();

    return (
        <>
            <button
                disabled={isPending}
                onClick={() =>
                    callContract({
                        address: '0x3e942744C21Eec1D88FBD463Fd0CcE42891Aec5C',
                        abi: storageAbi,
                        functionName: 'store',
                        args: [42],
                    })
                }
            >
                Store 42
            </button>
            {data?.status === 'approved' && <p>Stored: {data.receipt?.hash}</p>}
        </>
    );
}
Runs on testnet with your wallet

useGetFromContract#

Reads from a contract without a transaction or any gas. It's a mutation, so call mutate when you want the value. See Get from Contract.

tsTypes
useGetFromContract: (
    options?: MutationOptions<unknown, GetFromContractRequest>,
) => UseMutationResult<unknown, Error, GetFromContractRequest>;

interface GetFromContractRequest {
    address: `0x${string}`;
    abi: any;
    functionName: string;
    args: any[];
}
import { useGetFromContract } from '@megaeth-labs/wallet-sdk-react';
import { useEffect } from 'react';

export default function StoredValue() {
    const { mutate: getFromContract, data } = useGetFromContract();

    useEffect(() => {
        getFromContract({
            address: '0x3e942744C21Eec1D88FBD463Fd0CcE42891Aec5C',
            abi: storageAbi,
            functionName: 'retrieve',
            args: [],
        });
    }, [getFromContract]);

    return <p>Stored value: {String(data ?? '…')}</p>;
}
Runs on testnet with your wallet

useGrantPermissions#

Asks the user to let your app make set calls and spend up to set limits without approving each transaction. See Grant Permissions and Permissions.

tsTypes
useGrantPermissions: (
    options?: MutationOptions<GrantPermissionsResponse, GrantPermissionsRequest>,
) => UseMutationResult<GrantPermissionsResponse, Error, GrantPermissionsRequest>;

type GrantPermissionsResponse = {
    status: 'approved' | 'cancelled';
};

interface GrantPermissionsRequest {
    permissions: Permission;
    externalAddress?: `0x${string}`;
    sponsor?: boolean;
    append?: boolean;
}

interface Permission {
    id?: string;
    expiry: number; // Unix timestamp, in seconds
    permissions: {
        calls: { signature: string; to: string }[];
        spend: {
            limit: bigint;
            period: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year';
            token?: `0x${string}`;
        }[];
    };
}
import { useGrantPermissions } from '@megaeth-labs/wallet-sdk-react';
import { parseEther } from 'viem';

export default function GrantButton() {
    const { mutate: grantPermissions, isPending } = useGrantPermissions();

    return (
        <button
            disabled={isPending}
            onClick={() =>
                grantPermissions({
                    permissions: {
                        expiry: Math.floor(Date.now() / 1000) + 60 * 60 * 3, // 3 hours
                        permissions: {
                            calls: [{ to: '0x3e942744C21Eec1D88FBD463Fd0CcE42891Aec5C', signature: 'store(uint256)' }],
                            spend: [{ limit: parseEther('0.01'), period: 'day' }],
                        },
                    },
                })
            }
        >
            Allow quick actions
        </button>
    );
}
Runs on testnet with your wallet

usePermissions#

Returns the permissions the user has granted your app that haven't expired. It runs once a wallet is connected. See Get Permissions and Permissions.

tsTypes
usePermissions: (
    address?: string,
    options?: QueryOptions<GetPermissionsResponse | undefined>,
) => UseQueryResult<GetPermissionsResponse | undefined, Error>;

interface GetPermissionsResponse {
    permissions?: {
        expiry: number;
        permissions: {
            calls: { signature: string; to: `0x${string}` }[];
            spend: {
                limit: bigint;
                period: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year';
                token?: `0x${string}`;
            }[];
        };
    } | null;
}
import { usePermissions } from '@megaeth-labs/wallet-sdk-react';

export default function PermissionsSummary() {
    const { data, isLoading } = usePermissions();

    if (isLoading) return <p>Loading…</p>;
    if (!data?.permissions) return <p>No active permissions</p>;

    return <p>Expires {new Date(data.permissions.expiry * 1000).toLocaleString()}</p>;
}
Runs on testnet with your wallet

useRevokePermissions#

Removes the permissions the user has granted your app. See Revoke Permissions and Permissions.

tsTypes
useRevokePermissions: (
    options?: MutationOptions<void, void>,
) => UseMutationResult<void, Error, void>;
import { useRevokePermissions } from '@megaeth-labs/wallet-sdk-react';

export default function RevokeButton() {
    const { mutate: revokePermissions, isPending } = useRevokePermissions();

    return (
        <button onClick={() => revokePermissions()} disabled={isPending}>
            Revoke permissions
        </button>
    );
}
Runs on testnet with your wallet

Sending Funds#

useTransfer#

Sends native tokens, an ERC-20, an ERC-721 or an ERC-1155 to an address. See Transfer.

tsTypes
useTransfer: (
    options?: MutationOptions<TransactionResult, TransferRequest>,
) => UseMutationResult<TransactionResult, Error, TransferRequest>;

interface TransactionResult {
    status: 'approved' | 'cancelled' | 'error';
    receipt?: TransactionReceipt;
    receipts?: TransactionReceipt[];
    error?: string;
    silentHasUsedFallback?: boolean;
}

interface TransferRequest {
    amount: string; // In the token's smallest unit
    to: `0x${string}`;
    type: 'native' | 'erc20' | 'erc721' | 'erc1155';
    contractAddress?: string;
    tokenId?: number;
    sponsor?: boolean;
}

interface TransactionReceipt {
    hash: `0x${string}`;
    blockHash: string;
    blockNumber: number;
    chainId: number;
    gasUsed: number;
    logs: { address: `0x${string}`; data: `0x${string}`; topics: string[] }[];
    status: string;
    transactionHash: `0x${string}`;
}
import { useTransfer } from '@megaeth-labs/wallet-sdk-react';
import { parseUnits } from 'viem';

export default function SendTokenButton() {
    const { mutate: transfer, isPending, data } = useTransfer();

    return (
        <>
            <button
                disabled={isPending}
                onClick={() =>
                    transfer({
                        type: 'erc20',
                        to: '0xFD8D73c93385271d06138FA0Ff6E9c639C3Bd8b0',
                        contractAddress: '0x2715b6d04b6a0AB227631019899282a585Be410F',
                        amount: parseUnits('1', 18).toString(),
                    })
                }
            >
                Send 1 token
            </button>
            {data?.status === 'approved' && <p>Sent: {data.receipt?.hash}</p>}
        </>
    );
}
Runs on testnet with your wallet

useCheckout#

Asks the user to pay your app an amount in US dollars. It uses the config from MegaProvider. See Checkout and Ramps.

tsTypes
useCheckout: (
    options?: MutationOptions<CheckoutResult, CheckoutRequest>,
) => UseMutationResult<CheckoutResult, Error, CheckoutRequest>;

interface CheckoutResult {
    status: 'approved' | 'cancelled' | 'error';
    error?: string;
    address?: `0x${string}`;
    hash?: `0x${string}`;
    tokenAmount?: string;
    usdAmount?: string;
    destination?: `0x${string}`;
}

interface CheckoutRequest {
    config?: Config;
    amountUSD: string;
    destination?: `0x${string}`;
    tokenAddress?: `0x${string}`;
    reference?: string;
    lineItems?: { amountUSD: string; label: string }[];
}

interface Config {
    network: 'mainnet' | 'testnet';
    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
}
import { useCheckout } from '@megaeth-labs/wallet-sdk-react';

export default function PayButton() {
    const { mutate: checkout, isPending, data } = useCheckout();

    return (
        <>
            <button
                disabled={isPending}
                onClick={() =>
                    checkout({ amountUSD: '1.00', destination: '0xFD8D73c93385271d06138FA0Ff6E9c639C3Bd8b0' })
                }
            >
                Pay $1.00
            </button>
            {data?.status === 'approved' && <p>Paid: {data.hash}</p>}
        </>
    );
}
Runs on testnet with your wallet

useSend#

Opens the wallet's send screen, optionally with a token and destination filled in. See Send.

tsTypes
useSend: (
    options?: MutationOptions<TransactionResult, SendRequest>,
) => UseMutationResult<TransactionResult, Error, SendRequest>;

interface TransactionResult {
    status: 'approved' | 'cancelled' | 'error';
    receipt?: TransactionReceipt;
    receipts?: TransactionReceipt[];
    error?: string;
    silentHasUsedFallback?: boolean;
}

interface SendRequest {
    token?: `0x${string}` | 'native';
    destination?: `0x${string}`;
}

interface TransactionReceipt {
    hash: `0x${string}`;
    blockHash: string;
    blockNumber: number;
    chainId: number;
    gasUsed: number;
    logs: { address: `0x${string}`; data: `0x${string}`; topics: string[] }[];
    status: string;
    transactionHash: `0x${string}`;
}
import { useSend } from '@megaeth-labs/wallet-sdk-react';

export default function SendButton() {
    const { mutate: send, isPending } = useSend();

    return (
        <button onClick={() => send({})} disabled={isPending}>
            Send
        </button>
    );
}
Runs on testnet with your wallet

Tokens#

useDeposit#

Opens the wallet's deposit screen, where the user can buy tokens or bridge them in. See Deposit, Ramps and Bridging.

tsTypes
useDeposit: (
    options?: MutationOptions<void, void>,
) => UseMutationResult<void, Error, void>;
import { useDeposit } from '@megaeth-labs/wallet-sdk-react';

export default function DepositButton() {
    const { mutate: deposit, isPending } = useDeposit();

    return (
        <button onClick={() => deposit()} disabled={isPending}>
            Add funds
        </button>
    );
}
Runs on testnet with your wallet

useSwap#

Opens the wallet's swap screen, optionally with the tokens filled in. See Swap and Swaps.

tsTypes
useSwap: (
    options?: MutationOptions<TransactionResult, SwapRequest>,
) => UseMutationResult<TransactionResult, Error, SwapRequest>;

interface TransactionResult {
    status: 'approved' | 'cancelled' | 'error';
    receipt?: TransactionReceipt;
    receipts?: TransactionReceipt[];
    error?: string;
    silentHasUsedFallback?: boolean;
}

interface SwapRequest {
    fromToken?: `0x${string}` | 'native';
    toToken?: `0x${string}` | 'native';
}

interface TransactionReceipt {
    hash: `0x${string}`;
    blockHash: string;
    blockNumber: number;
    chainId: number;
    gasUsed: number;
    logs: { address: `0x${string}`; data: `0x${string}`; topics: string[] }[];
    status: string;
    transactionHash: `0x${string}`;
}
import { useSwap } from '@megaeth-labs/wallet-sdk-react';

export default function SwapButton() {
    const { mutate: swap, isPending } = useSwap();

    return (
        <button
            disabled={isPending}
            onClick={() => swap({ fromToken: 'native', toToken: '0x2715b6d04b6a0AB227631019899282a585Be410F' })}
        >
            Swap
        </button>
    );
}
Runs on testnet with your wallet

useBalances#

Returns the connected account's token balances, for every token it holds or just the ones you list. It runs once a wallet is connected. See Balances.

tsTypes
useBalances: (
    tokens?: string[],
    options?: QueryOptions<OwnedTokenResponse[]>,
) => UseQueryResult<OwnedTokenResponse[], Error>;

interface OwnedTokenResponse {
    name: string;
    symbol: string;
    decimals: number;
    address: string;
    image?: string;
    balance: string;
    displayBalance: string;
    usdPrice?: string;
    usdBalance?: string;
    marketCap?: string;
    volume?: string;
    holders?: number;
    percentChange?: number;
}
import { useBalances } from '@megaeth-labs/wallet-sdk-react';

export default function Balances() {
    const { data: balances, isLoading } = useBalances(['0x2715b6d04b6a0AB227631019899282a585Be410F']);

    if (isLoading) return <p>Loading…</p>;

    return (
        <ul>
            {balances?.map((token) => (
                <li key={token.address}>
                    {token.displayBalance} {token.symbol}
                </li>
            ))}
        </ul>
    );
}
Runs on testnet with your wallet

useCollectible#

Opens the wallet on one of the user's collectibles. See Collectible.

tsTypes
useCollectible: (
    options?: MutationOptions<void, CollectibleRequest>,
) => UseMutationResult<void, Error, CollectibleRequest>;

interface CollectibleRequest {
    address: `0x${string}`;
    tokenId: string;
}
import { useCollectible } from '@megaeth-labs/wallet-sdk-react';

export default function ViewNftButton() {
    const { mutate: showCollectible } = useCollectible();

    return (
        <button
            onClick={() =>
                showCollectible({ address: '0x9416E9a7E89ceF6ECF97A6D7Cc4b58E128d0d3bb', tokenId: '1' })
            }
        >
            View in wallet
        </button>
    );
}
Runs on testnet with your wallet

MegaNames#

useFromMegaName#

Returns the address a MegaName points to, or undefined when it isn't registered. It runs once you pass a name. See From MegaName.

tsTypes
useFromMegaName: (
    name?: string,
    options?: QueryOptions<`0x${string}` | undefined>,
) => UseQueryResult<`0x${string}` | undefined, Error>;
import { useFromMegaName } from '@megaeth-labs/wallet-sdk-react';

export default function ResolvedAddress() {
    const { data: address, isLoading } = useFromMegaName('alice.mega');

    if (isLoading) return <span>Looking up…</span>;
    return <span>{address ?? 'No address found'}</span>;
}
Runs on testnet with your wallet

useToMegaName#

Returns the MegaName for an address, or undefined when it has none. It runs once you pass an address. See To MegaName.

tsTypes
useToMegaName: (
    address?: `0x${string}`,
    options?: QueryOptions<string | undefined>,
) => UseQueryResult<string | undefined, Error>;
import { useToMegaName } from '@megaeth-labs/wallet-sdk-react';

export default function DisplayName() {
    const address = '0xFD8D73c93385271d06138FA0Ff6E9c639C3Bd8b0';
    const { data: name } = useToMegaName(address);

    return <span>{name ?? address}</span>;
}
Runs on testnet with your wallet