Skip to content

Instantly share code, notes, and snippets.

@gregfromstl
Last active July 3, 2024 20:54
Show Gist options
  • Save gregfromstl/18ddefa6483595f13dee47ae94aed8ac to your computer and use it in GitHub Desktop.
Save gregfromstl/18ddefa6483595f13dee47ae94aed8ac to your computer and use it in GitHub Desktop.
Wagmi + Thirdweb ConnectButton
'use client';
import React from "react";
import {
Connector,
createConnector,
useConfig,
} from "wagmi";
import {
ConnectButton,
} from "thirdweb/react";
import {Chain, ThirdwebClient, createThirdwebClient} from "thirdweb";
import {Wallet, createWallet} from "thirdweb/wallets";
import { baseSepolia, base } from "thirdweb/chains";
import { viemAdapter } from "thirdweb/adapters/viem";
export function createThirdwebConnector(wallet: Wallet, client: ThirdwebClient) {
return createConnector(() => {
const account = wallet.getAccount();
const chain = wallet.getChain();
if (!account?.address || !chain) {
throw new Error("Invalid wallet");
}
return {
id: wallet.id,
type: wallet.id,
name: wallet.id,
supportsSimulation: true,
connect: async (params) => {
if (!wallet.getAccount()) {
await wallet.connect({ client });
}
const account = wallet.getAccount();
if (!account?.address) {
throw new Error("Invalid wallet");
}
return {
accounts: [
account.address
],
chainId: chain.id,
}
},
disconnect: async () => {
if (wallet.getAccount()) {
await wallet.disconnect();
}
},
getAccounts: async () => [account.address],
getChainId: async () => chain.id,
getProvider: async () => {},
isAuthorized: async () => true,
onAccountsChanged: async () => {},
onChainChanged: async () => {},
onConnect: async () => {
if (!wallet.getAccount()) {
await wallet.connect({ client });
}
},
onDisconnect: async () => {
if (wallet.getAccount()) {
await wallet.disconnect();
}
},
onMessage: async () => {},
getClient: async () => {
return viemAdapter.walletClient.toViem({ account, client, chain });
},
};
});
}
export const CustomConnectButton = () => {
const client = createThirdwebClient({
clientId: "",
});
const config = useConfig();
const wallets = [
createWallet("inApp"),
createWallet("io.metamask"),
createWallet("com.coinbase.wallet"),
];
return (
<ConnectButton
client={client}
wallets={wallets}
onDisconnect={(wallet) => {
config.setState((x) => ({
...x,
connections: new Map(),
status: "disconnected",
}))
}}
onConnect={(wallet) => {
if (!wallet.getChain() || !wallet.getAccount()) {
return;
}
const account = wallet.getAccount();
const chain = wallet.getChain() as Chain;
if (!account?.address) return;
const connector: Connector = config._internal.connectors.setup(createThirdwebConnector(wallet, client))
config.setState((x) => ({
...x,
connections: new Map().set(wallet.id, {
accounts: [
account.address
],
chainId: chain.id,
connector: connector,
}),
current: wallet.id,
status: "connected",
}))
}}
chains={[
baseSepolia,
base
]}
/>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment