Skip to content

Issue: Account Switch Listener and useSiweAuth Hook Causing Broken State #102

@0xboga

Description

@0xboga

Client Code:

<ConnectButton
  client={client}
  chain={chain}
  chains={[chain]}
  auth={{
    isLoggedIn: async (address) => {
      const loggedIn = await isLoggedIn(address);
      if (!loggedIn) {
        await logout();
      }
      return loggedIn;
    },
    doLogin: async (params) => {
      await login(params);
    },
    getLoginPayload: async ({ address }) => generatePayload({ address }),
    doLogout: async () => {
      await logout();
    },
  }}
/>

Backend Code:

const privateKey = env.THIRDWEB_ADMIN_PRIVATE_KEY;

if (!privateKey) {
  throw new Error('Missing THIRDWEB_ADMIN_PRIVATE_KEY in .env file.');
}

const thirdwebAuth = createAuth({
  domain: env.NEXT_PUBLIC_APP_URL || '',
  adminAccount: privateKeyToAccount({ client, privateKey }),
});

export const { generatePayload } = thirdwebAuth;

export async function login(payload: VerifyLoginPayloadParams) {
  const verifiedPayload = await thirdwebAuth.verifyPayload(payload);
  if (verifiedPayload.valid) {
    const jwt = await thirdwebAuth.generateJWT({
      payload: verifiedPayload.payload,
    });
    cookies().set('jwt', jwt);
  }
}

export async function isLoggedIn(address: string) {
  const jwt = cookies().get('jwt');
  if (!jwt?.value) {
    return false;
  }

  const authResult = await thirdwebAuth.verifyJWT({ jwt: jwt.value });
  if (!authResult.valid || authResult.parsedJWT.sub !== address) {
    return false;
  }
  return true;
}

export async function logout() {
  cookies().delete('jwt');
}

Problem Description:

When connecting using a wallet like MetaMask and switching between two accounts ( using the Metamask account switcher not the modal provided by ThirdWeb ), the application ends up in a broken state. Specifically, the ConnectButton indicates that the user is connected when, in fact, they actually need to sign in again to obtain a valid JWT. This inconsistency is caused by the account switch not properly triggering the authentication state to update, resulting in the UI reflecting an incorrect state.

Expected Behavior:

Upon switching accounts from a wallet extension, the ConnectButton should correctly prompt the user to sign in again to obtain a new JWT, ensuring the authentication state is accurately maintained.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions