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 4 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
4 changes: 2 additions & 2 deletions packages/connectkit-next-siwe/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,14 @@
],
"dependencies": {
"iron-session": "^6.2.1",
"siwe": "^2.1.4"
"viem": "2.12.0"
},
"peerDependencies": {
"connectkit": ">=1.2.0",
"next": ">=12.x",
"react": "17.x || 18.x",
"react-dom": "17.x || 18.x",
"siwe": ">=2"
"viem": ">=2.12.0"
},
"devDependencies": {
"@types/node": "^16.11.27",
Expand Down
58 changes: 37 additions & 21 deletions packages/connectkit-next-siwe/src/configureSIWE.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@ 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 { generateSiweNonce, createSiweMessage } from 'viem/siwe';

import { createPublicClient, http } from 'viem';
import * as allChains from 'viem/chains';

type RouteHandlerOptions = {
afterNonce?: (
Expand Down Expand Up @@ -108,7 +111,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 @@ -153,31 +156,44 @@ const verifyRoute = async (
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 splitMessage = message.split('\n');
const address = splitMessage.find((m) => m.startsWith('0x'));
const chainId = Number(
splitMessage
.find((m) => m.startsWith('Chain ID: '))
?.split('Chain ID: ')[1]
);

const chain = Object.values(allChains).find((c) => c.id === chainId);
if (!chain) throw new Error('Invalid chain ID');

const publicClient = createPublicClient({
chain,
transport: http(),
});
const verified = await publicClient.verifySiweMessage({
message,
signature,
nonce: session.nonce,
});
if (!verified) {
return res.status(422).end('Invalid nonce.');
}
session.address = fields.address;
session.chainId = fields.chainId;
session.address = address;
session.chainId = 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 Down Expand Up @@ -253,15 +269,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 Down Expand Up @@ -58,7 +59,8 @@ 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>(1);

const locales = useLocales({});
const mobile = isMobile();
Expand All @@ -68,10 +70,10 @@ const ChainSelectList = ({

const handleSwitchNetwork = (chainId: number) => {
if (switchChain) {
setPendingChainId(chainId);
switchChain({ chainId });
}
};
const pendingChainId = isPending ? data?.id : undefined;

const { triggerResize } = useContext();

Expand Down
5 changes: 3 additions & 2 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,7 +20,7 @@ export type SIWEConfig = {
getNonce: () => Promise<string>;
createMessage: (args: {
nonce: string;
address: string;
address: Address;
chainId: number;
}) => string;
verifyMessage: (args: {
Expand Down
34 changes: 32 additions & 2 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -7728,14 +7728,14 @@ __metadata:
"@types/react": ^18.0.6
"@types/react-dom": ^18.0.2
iron-session: ^6.2.1
siwe: ^2.1.4
typescript: ^4.9.5
viem: 2.12.0
peerDependencies:
connectkit: ">=1.2.0"
next: ">=12.x"
react: 17.x || 18.x
react-dom: 17.x || 18.x
siwe: ">=2"
viem: ">=2.12.0"
languageName: unknown
linkType: soft

Expand Down Expand Up @@ -12110,6 +12110,15 @@ __metadata:
languageName: node
linkType: hard

"isows@npm:1.0.4":
version: 1.0.4
resolution: "isows@npm:1.0.4"
peerDependencies:
ws: "*"
checksum: a3ee62e3d6216abb3adeeb2a551fe2e7835eac87b05a6ecc3e7739259bf5f8e83290501f49e26137390c8093f207fc3378d4a7653aab76ad7bbab4b2dba9c5b9
languageName: node
linkType: hard

"istanbul-lib-coverage@npm:^3.0.0, istanbul-lib-coverage@npm:^3.2.0":
version: 3.2.2
resolution: "istanbul-lib-coverage@npm:3.2.2"
Expand Down Expand Up @@ -19291,6 +19300,27 @@ __metadata:
languageName: node
linkType: hard

"viem@npm:2.12.0":
version: 2.12.0
resolution: "viem@npm:2.12.0"
dependencies:
"@adraffy/ens-normalize": 1.10.0
"@noble/curves": 1.2.0
"@noble/hashes": 1.3.2
"@scure/bip32": 1.3.2
"@scure/bip39": 1.2.1
abitype: 1.0.0
isows: 1.0.4
ws: 8.13.0
peerDependencies:
typescript: ">=5.0.4"
peerDependenciesMeta:
typescript:
optional: true
checksum: 7373bf955eca9a044cfa51a3d0eece054eb91d1088f500a056c7d3f84ea10e8c79efaaca237e6d47beb9c7f21febd67085b8098838ad6f2fe13fe4c19ee626e8
languageName: node
linkType: hard

"viem@npm:^1.0.0, viem@npm:^1.1.4":
version: 1.21.4
resolution: "viem@npm:1.21.4"
Expand Down
Loading