Can I use SIWE in React Native?

73 views Asked by At

My React and React Native projects use Walletconnect to connect wallet.

My question is if I don't have window.location.host and window.location.origin in React Native, how do I send the message to my back-end just like React project ?

I have a React project send the SIWE message to back-end for login.

Here is React project code for login, just trigger signInWithEthereum function:

import { SiweMessage } from 'siwe';
import { useSignMessage } from 'wagmi';

const { signMessageAsync } = useSignMessage();

const createSiweMessage = async (address: string, statement: string, chainId: number) => {
    const domain = window.location.host;
    const origin = window.location.origin;
    // Here is what I need in React Native
    const message = new SiweMessage({
        domain,
        address,
        statement,
        uri: origin,
        version: '1',
        chainId,
    });

    return message.prepareMessage();
};

const signInWithEthereum = async (address: string, chainId: number) => {
    if (typeof window !== undefined) {
        try {
            const message = await createSiweMessage(
                address,
                'Sign in with Ethereum to the app.',
                chainId
            );
            console.log('message is', message);

            const signature = await signMessageAsync({ message });

            const nonceData = await axios.get(`${process.env.DEV_API}/auth/nonce`); // get nonce from back-end
            console.log('nonceData', nonceData);
            const { nonce } = nonceData?.data.data;

            console.log('nonce', nonce);
            console.log('signature', signature);
            console.log('message', message);
            // send data to back-end for login
            dispatch(
                loginWithSiwe({
                    nonce,
                    message,
                    signature,
                })
            );
        } catch (error) {
            console.log('signInWithEthereum error', error);
            disconnect();
        }
    }
};

I get the signature in React Native just use the code, but I still need message data just like React project

import {useAccount, useSignMessage} from 'wagmi';
// if connect wallet successfully, then use the code to sign in.
const {data, isError, isLoading, isSuccess, signMessage} = useSignMessage({
  message: 'hello web3modal + wagmi',
});

const onPress = () => {
  signMessage(););
};

console.log('Sign =>', {data, isError, isLoading, isSuccess});

return (
  <>
    <Button disabled={isLoading} onPress={onPress}>
      Sign message
    </Button>
    <Text>{`Signature is ${data}`}</Text>
  </>
);

Official document: https://docs.walletconnect.com/web3modal/react-native/hooks#usesignmessage

If there is no window in React Native, how to get createSiweMessage value ?

0

There are 0 answers