vue-dapp icon indicating copy to clipboard operation
vue-dapp copied to clipboard

Automatically load wallet if its been previously connected.

Open JABirchall opened this issue 3 years ago • 14 comments

As title says, Ive been testing out this module but found an issue that i cant seem to figure out.

When you connect your wallet to the app, if you refresh the app doesnt reload the wallet details and you have to press connect again.

Is there a way to automatically reconnect the wallet if its connected already?

I also dont want it to be invasive. If the user hasnt connected I dont want to force metamask to connect as soon as the user visits the app.

JABirchall avatar Aug 28 '22 02:08 JABirchall

Hi @JABirchall thanks for the suggestion.

Currently I'm doing it manually, but we can think about extend that to became an optional init parameter.


const connectors: any = [
    new MetaMaskConnector({
        appUrl: window.location.href,
    }),
    new WalletConnectConnector({
        qrcode: true,
        rpc: {},
    }),
];

const { connectWith } = useWallet();
const web3 = window.ethereum as any;

if (web3.selectedAddress) {
    connectWith(connectors[0])
}

re2005 avatar Aug 28 '22 13:08 re2005

@re2005

I have tried something like that but my component fully loads before ethereum is even on the window.

I did find a hacky solution,

// Event should fire once metamask has injected
provider.value?.once('connect', _ => {
  if (!provider.value?.provider.isMetaMask) return;
  // Ethereum object isnt avaible through provider???
  const e = (window as any).ethereum;
  // Check 25 times if an address is avaible.
  const interval = setInterval(_ => {
    if(e.selectedAddress !== null) {
      connectWith(connectors[0])
      clearInterval(interval)
    }
  }, 200)

  // If no address after 5 seconds, assume not connected.
  setTimeout(_ => clearInterval(interval), 5000);
})

This worked yesturday, but now reopening my project it doesnt work provider is null :|

JABirchall avatar Aug 28 '22 13:08 JABirchall

Yes, you will have some timing issues.

If you just wait 100ms before checking for the window.ethereum it's already enough.

function sleep(ms: number) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

await sleep(100);
const w = window.ethereum as any;

if (w && w.selectedAddress) {
...

Will investigate the possibility to add it as a initial option.

re2005 avatar Aug 29 '22 07:08 re2005

Excuse me, I also wonder such function and I use above and it seems work,I could get the ethereum address and balance of ETH, but for example when I try to get the balance of some contract, singer or provider is invalid, we know, it need a singer or provider before we start contract, code like this: const web3 = window.ethereum as any; const { wallet, connectWith } = useWallet() const { address, balance, chainId, isActivated, dnsAlias, signer } = useEthers() if (localStorage.getItem('token') != null && web3.selectedAddress) { connectWith(connectors[0]).then(() => { console.log(wallet.status) //connected signer.value.connect(wallet.provider) }) }

it shows error: Uncaught (in promise) Error: cannot alter JSON-RPC Signer connection (operation="connect", code=UNSUPPORTED_OPERATION, version=providers/5.7.1)

get balance of some contract token is below: let contract = new ethers.Contract( import.meta.env.VITE_CONTRACT_ADDRESS, import.meta.env.VITE_CONTRACT_ABI, signer.value ) contract.balanceOf(address.value).then(res => { onChainToken.value = Number(res) / Math.pow(10, 18) })

I wonder how to get the signer valid, thank you guys! lol @re2005

YCL686 avatar Oct 17 '22 11:10 YCL686

Hi @YCL686 can you please provide a valid git repository with the reproduction code ? Without that is not possible to properly help you.

re2005 avatar Oct 17 '22 12:10 re2005

@YCL686 Why do you do this signer.value.connect(wallet.provider)?

The signer.value is null before the wallet is connected. So if you want to make sure the signer.value has value, you can write the code in the onActivated() hook like

const { onActivated, onChanged } = useEthersHooks()

onActivated(({ signer, provider }) => {
  console.log(signer)
})

johnson86tw avatar Oct 17 '22 13:10 johnson86tw

@JABirchall @re2005 I tried to implement the feature https://github.com/chnejohnson/vue-dapp/commit/5ad43f82a49745cef33708b37c60ea8bca97f5f4 though it only checks metamask provider once. Please help me review the code and make sure it meets your needs. Thanks

johnson86tw avatar Oct 17 '22 16:10 johnson86tw

@chnejohnson this is really awesome feature, thank you. Let me test it and give you some feedback.

re2005 avatar Oct 18 '22 13:10 re2005

@chnejohnson Works nicely locally.

What do you think about something optional when initialising the plugin?

app.use(VueDapp, {
  autoconnect: true,
  networks: {
    80001: {
      chainId: ethers.utils.hexValue(80001),
      blockExplorerUrls: ['https://mumbai.polygonscan.com/'],
      chainName: 'Mumbai',
      rpcUrls: ['https://rpc-mumbai.maticvigil.com/'],
       nativeCurrency: {
        name: 'Mumbai',
        decimals: 18,
        symbol: 'MATIC',
    },
  },
})

re2005 avatar Oct 18 '22 13:10 re2005

@re2005 Cool, it's better. I have updated it in this optional way. Please help me to check, thanks 33aa82a38adf3ccdad137d26992b9a9c6adf11c6

johnson86tw avatar Oct 19 '22 13:10 johnson86tw

@chnejohnson Please check my comments

re2005 avatar Oct 19 '22 13:10 re2005

@re2005 fixed 2f9432bd430ddc4f8c98456a526430530190770b

johnson86tw avatar Oct 19 '22 14:10 johnson86tw

@chnejohnson Tested and is working really nicely! I had a small comment. Good to go! 🚀

re2005 avatar Oct 20 '22 07:10 re2005

Important to mention is a breaking change, since the network options now will be inside networks key.

re2005 avatar Oct 20 '22 07:10 re2005

:tada: This issue has been resolved in version 0.6.0 :tada:

The release is available on:

Your semantic-release bot :package::rocket:

github-actions[bot] avatar Oct 23 '22 07:10 github-actions[bot]