2024-04-21 23:02:42 +00:00
|
|
|
import { SiweMessage } from 'siwe';
|
|
|
|
import { PKPEthersWallet } from '@lit-protocol/pkp-ethers';
|
|
|
|
import { v4 as uuid } from 'uuid';
|
|
|
|
|
|
|
|
const domain = window.location.host;
|
|
|
|
const origin = window.location.origin;
|
|
|
|
|
2024-04-24 02:10:20 +00:00
|
|
|
export async function signInWithEthereum(
|
|
|
|
chainId: number,
|
|
|
|
action: 'signup' | 'login',
|
|
|
|
wallet: PKPEthersWallet,
|
|
|
|
) {
|
2024-04-21 23:02:42 +00:00
|
|
|
const message = await createSiweMessage(
|
2024-04-24 02:10:20 +00:00
|
|
|
chainId,
|
2024-04-21 23:02:42 +00:00
|
|
|
await wallet.getAddress(),
|
|
|
|
'Sign in with Ethereum to the app.',
|
|
|
|
);
|
|
|
|
const signature = await wallet.signMessage(message);
|
|
|
|
|
|
|
|
const res = await fetch(`${import.meta.env.VITE_SERVER_URL}/auth/validate`, {
|
|
|
|
method: 'POST',
|
|
|
|
headers: {
|
|
|
|
'Content-Type': 'application/json',
|
|
|
|
},
|
2024-04-24 02:10:20 +00:00
|
|
|
body: JSON.stringify({ action, message, signature }),
|
2024-04-21 23:02:42 +00:00
|
|
|
credentials: 'include',
|
|
|
|
});
|
2024-04-24 02:10:20 +00:00
|
|
|
return (await res.json()) as { success: boolean; error?: string };
|
2024-04-21 23:02:42 +00:00
|
|
|
}
|
|
|
|
|
2024-04-24 02:10:20 +00:00
|
|
|
async function createSiweMessage(
|
|
|
|
chainId: number,
|
|
|
|
address: string,
|
|
|
|
statement: string,
|
|
|
|
) {
|
2024-04-21 23:02:42 +00:00
|
|
|
const message = new SiweMessage({
|
|
|
|
domain,
|
|
|
|
address,
|
|
|
|
statement,
|
|
|
|
uri: origin,
|
|
|
|
version: '1',
|
2024-04-24 02:10:20 +00:00
|
|
|
chainId,
|
2024-04-21 23:02:42 +00:00
|
|
|
nonce: uuid().replace(/[^a-z0-9]/g, ''),
|
|
|
|
});
|
|
|
|
return message.prepareMessage();
|
|
|
|
}
|