Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

update: use viem for siwe #387

Merged
merged 26 commits into from
Jun 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@

# x.y.z

This update adds support for [Coinbase Smart Wallet](https://smartwallet.dev) and adds additional support for the latest versions of peer dependencies `wagmi` and `viem`.
This update adds support for [Coinbase Smart Wallet](https://smartwallet.dev), adds additional support for the latest versions of peer dependencies `wagmi` and `viem`, and removes the dependency `ethers` from `connectkit-next-siwe` in favor of `viem`'s [SIWE implementation](https://viem.sh/docs/siwe/actions/verifySiweMessage).

## New

Expand All @@ -10,6 +9,11 @@ This update adds support for [Coinbase Smart Wallet](https://smartwallet.dev) an
## Updated

- Changed default setting for `enforceSupportedChains` to `false` to allow for a better default user and developer experience.
- Updates peer dependency `viem` to `>=2.13.x`.

## Deprecated

- Removes dependency `ethers` from `connectkit-next-siwe` in favor of `viem`'s [SIWE implementation](https://viem.sh/docs/siwe/actions/verifySiweMessage).

# 1.7.3

Expand Down
1 change: 0 additions & 1 deletion examples/nextjs-siwe/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
"dependencies": {
"connectkit": "workspace:packages/connectkit",
"connectkit-next-siwe": "workspace:packages/connectkit-next-siwe",
"ethers": "^5",
"next": "12.3.0",
"react": "^18.0.0",
"react-dom": "^18.0.0",
Expand Down
3 changes: 1 addition & 2 deletions examples/testbench/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,11 @@
"@tanstack/react-query": "^5.17.10",
"connectkit": "workspace:packages/connectkit",
"connectkit-next-siwe": "workspace:packages/connectkit-next-siwe",
"ethers": "^5",
"local-ssl-proxy": "^1.3.0",
"next": "14.1.0",
"react": "^18.0.0",
"react-dom": "^18.0.0",
"viem": "^2.13.0",
"viem": "^2.13.6",
"wagmi": "^2.9.7"
},
"devDependencies": {
Expand Down
3 changes: 2 additions & 1 deletion examples/testbench/src/components/Web3Provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ const avalanche: Chain = defineChain({
testnet: false,
});

const ckConfig = getDefaultConfig({
export const ckConfig = getDefaultConfig({
/*
chains: [
mainnet,
Expand All @@ -48,6 +48,7 @@ const customConfig = {
connectors: [wallets['rainbow'], ...(ckConfig.connectors ?? [])],
};
const config = createConfig(ckConfig);

const queryClient = new QueryClient();

type ContextValue = {};
Expand Down
2 changes: 1 addition & 1 deletion examples/testbench/src/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -319,7 +319,7 @@ const Home: NextPage = () => {
</div>
<h2>dApps configured chains</h2>
<div style={{ display: 'flex', gap: 8 }}>
{chains.map((chain: wagmiChains.Chain) => (
{chains.map((chain) => (
<ChainIcon key={chain.id} id={chain.id} />
))}
</div>
Expand Down
5 changes: 5 additions & 0 deletions examples/testbench/src/utils/siweServer.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import { configureServerSideSIWE } from 'connectkit-next-siwe';
import { ckConfig } from '../components/Web3Provider';

export const siweServer = configureServerSideSIWE({
config: {
chains: ckConfig.chains,
transports: ckConfig.transports,
},
options: {
afterLogout: async () => console.log('afterLogout'),
afterNonce: async () => console.log('afterNonce'),
Expand Down
6 changes: 3 additions & 3 deletions packages/connectkit-next-siwe/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "connectkit-next-siwe",
"version": "0.2.0",
"version": "0.3.0",
"author": "Family",
"homepage": "https://docs.family.co/connectkit",
"license": "BSD-2-Clause license",
Expand Down Expand Up @@ -37,14 +37,14 @@
],
"dependencies": {
"iron-session": "^6.2.1",
"siwe": "^2.1.4"
"viem": "^2.13.0"
},
"peerDependencies": {
"connectkit": ">=1.2.0",
"next": ">=12.x",
"react": "17.x || 18.x",
"react-dom": "17.x || 18.x",
"siwe": ">=2"
"viem": ">=2.13.3"
},
"devDependencies": {
"@types/node": "^16.11.27",
Expand Down
78 changes: 56 additions & 22 deletions packages/connectkit-next-siwe/src/configureSIWE.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,14 @@ import { SIWEProvider } from 'connectkit';
import type { IncomingMessage, ServerResponse } from 'http';
import { getIronSession, IronSession, IronSessionOptions } from 'iron-session';
import { NextApiHandler, NextApiRequest, NextApiResponse } from 'next';
import { generateNonce, SiweErrorType, SiweMessage } from 'siwe';

import { Chain, Transport, PublicClient, createPublicClient, http } from 'viem';
import * as allChains from 'viem/chains';
import {
generateSiweNonce,
createSiweMessage,
parseSiweMessage,
} from 'viem/siwe';

type RouteHandlerOptions = {
afterNonce?: (
Expand All @@ -23,10 +30,16 @@ type RouteHandlerOptions = {
) => Promise<void>;
afterLogout?: (req: NextApiRequest, res: NextApiResponse) => Promise<void>;
};

type NextServerSIWEConfig = {
config?: {
chains: readonly [Chain, ...Chain[]];
transports?: Record<number, Transport>;
};
session?: Partial<IronSessionOptions>;
options?: RouteHandlerOptions;
};

type NextClientSIWEConfig = {
apiRoutePrefix: string;
statement?: string;
Expand Down Expand Up @@ -108,7 +121,7 @@ const nonceRoute = async (
case 'GET':
const session = await getSession(req, res, sessionConfig);
if (!session.nonce) {
session.nonce = generateNonce();
session.nonce = generateSiweNonce();
await session.save();
}
if (afterCallback) {
Expand Down Expand Up @@ -147,37 +160,57 @@ const verifyRoute = async (
req: NextApiRequest,
res: NextApiResponse<void>,
sessionConfig: IronSessionOptions,
config?: NextServerSIWEConfig['config'],
afterCallback?: RouteHandlerOptions['afterVerify']
) => {
switch (req.method) {
case 'POST':
try {
const session = await getSession(req, res, sessionConfig);
const { message, signature } = req.body;
const siweMessage = new SiweMessage(message);
const { data: fields } = await siweMessage.verify({ signature, nonce: session.nonce });
if (fields.nonce !== session.nonce) {
const { message, signature } = req.body as {
message: string;
signature: `0x${string}`;
};

const parsed = parseSiweMessage(message);
if (parsed.nonce !== session.nonce) {
return res.status(422).end('Invalid nonce.');
}
session.address = fields.address;
session.chainId = fields.chainId;

let chain = config?.chains
? Object.values(config.chains).find((c) => c.id === parsed.chainId)
: undefined;
if (!chain) {
// Try to find chain from allChains if not found in user-provided chains
chain = Object.values(allChains).find((c) => c.id === parsed.chainId);
}
if (!chain) {
throw new Error('Chain not found.');
}

const publicClient: PublicClient = createPublicClient({
chain,
transport: http(),
});

const verified = await publicClient.verifySiweMessage({
message,
signature,
nonce: session.nonce,
});
if (!verified) {
return res.status(422).end('Unable to verify signature.');
}

session.address = parsed.address;
session.chainId = parsed.chainId;
await session.save();
if (afterCallback) {
await afterCallback(req, res, session);
}
res.status(200).end();
} catch (error) {
switch (error) {
case SiweErrorType.INVALID_NONCE:
case SiweErrorType.INVALID_SIGNATURE: {
res.status(422).end(String(error));
break;
}
default: {
res.status(400).end(String(error));
break;
}
}
res.status(400).end(String(error));
}
break;
default:
Expand All @@ -195,6 +228,7 @@ const envVar = (name: string) => {
};

export const configureServerSideSIWE = <TSessionData extends Object = {}>({
config,
session: { cookieName, password, cookieOptions, ...otherSessionOptions } = {},
options: { afterNonce, afterVerify, afterSession, afterLogout } = {},
}: NextServerSIWEConfig): ConfigureServerSIWEResult<TSessionData> => {
Expand All @@ -220,7 +254,7 @@ export const configureServerSideSIWE = <TSessionData extends Object = {}>({
case 'nonce':
return await nonceRoute(req, res, sessionConfig, afterNonce);
case 'verify':
return await verifyRoute(req, res, sessionConfig, afterVerify);
return await verifyRoute(req, res, sessionConfig, config, afterVerify);
case 'session':
return await sessionRoute(req, res, sessionConfig, afterSession);
case 'logout':
Expand Down Expand Up @@ -253,15 +287,15 @@ export const configureClientSIWE = <TSessionData extends Object = {}>({
return nonce;
}}
createMessage={({ nonce, address, chainId }) =>
new SiweMessage({
createSiweMessage({
version: '1',
domain: window.location.host,
uri: window.location.origin,
address,
chainId,
nonce,
statement,
}).prepareMessage()
})
}
verifyMessage={({ message, signature }) =>
fetch(`${apiRoutePrefix}/verify`, {
Expand Down
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

irrelevant to SIWE update, but this required updating as useSwitchChain returns different data since the last wagmi update

Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { useState } from 'react';
import { useAccount, useSwitchChain } from 'wagmi';
import { chainConfigs } from '../../../constants/chainConfigs';

Expand All @@ -20,7 +21,6 @@ import { isCoinbaseWalletConnector, isMobile } from '../../../utils';
import ChainIcons from '../../../assets/chains';
import useLocales from '../../../hooks/useLocales';
import { useContext } from '../../ConnectKit';
import { useState } from 'react';

const Spinner = (
<svg
Expand Down Expand Up @@ -59,7 +59,7 @@ const ChainSelectList = ({
variant?: 'primary' | 'secondary';
}) => {
const { connector, chain } = useAccount();
const { chains, isPending, data, switchChain, error } = useSwitchChain();
const { chains, isPending, switchChain, error } = useSwitchChain();
const [pendingChainId, setPendingChainId] = useState<number | undefined>(
undefined
);
Expand Down
7 changes: 4 additions & 3 deletions packages/connectkit/src/siwe/SIWEContext.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { createContext } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Address } from 'viem';

export enum StatusState {
READY = 'ready',
Expand All @@ -10,7 +11,7 @@ export enum StatusState {
}

export type SIWESession = {
address: string;
address: Address;
chainId: number;
};

Expand All @@ -19,9 +20,9 @@ export type SIWEConfig = {
getNonce: () => Promise<string>;
createMessage: (args: {
nonce: string;
address: string;
address: Address;
chainId: number;
}) => string;
}) => Promise<string> | string;
verifyMessage: (args: {
message: string;
signature: string;
Expand Down
4 changes: 2 additions & 2 deletions packages/connectkit/src/siwe/SIWEProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ export const SIWEProvider = ({
const { signMessageAsync } = useSignMessage();

const onError = (error: any) => {
console.error('signIn error', error.code, error.message);
console.error('signIn error', error, error.message);
switch (error.code) {
case -32000: // WalletConnect: user rejected
case 4001: // MetaMask: user rejected
Expand Down Expand Up @@ -116,7 +116,7 @@ export const SIWEProvider = ({

setStatus(StatusState.LOADING);

const message = siweConfig.createMessage({
const message = await siweConfig.createMessage({
address,
chainId,
nonce: nonce?.data,
Expand Down
Loading
Loading