blockchainethers.jsweb3-react

How to correctly set up a WebSocketProvider in ethers.js?


I'm trying to switch my dapp from Web3Provider to WebSocketProvider,

form this:

const provider = new ethers.providers.Web3Provider(window.ethereum)
const accounts = await window.ethereum.request({ method: "eth_accounts" })
const account = accounts[0]
const signer = provider.getSigner()

to this:

const provider = new ethers.providers.WebSocketProvider("ws://localhost:8545") <-
const accounts = await window.ethereum.request({ method: "eth_accounts" })
const account = accounts[0]
const signer = provider.getSigner()

With this change I can interact with the Contract only with account that creates and deploy the smart contract, also, the transactions have no confirmation from the user. However, when I try to call some Contract function with another address I get this error: enter image description here

On the fourth line, the value of the "from" key is different from the address actually selected in the metamask, in fact it is the address of the creator of the Smart Contract. There seems to be some problem with the signer or what? With Web3Provider everything works fine.

Can you help me in any way or tell me more about WebSocketProvider?

Thanks in advance


Solution

  • I think the issue you are facing is likely due to the fact that the WebSocketProvider does not have access to the accounts stored in MetaMask.

    According to Metamask extension github websocket providers are not supported yet (see https://github.com/MetaMask/metamask-extension/issues/1645)

    The WebSocketProvider is good to read data and track events and transactions, but is not usually used to sign transactions.

    If you need or want to use the WebSocketProvider provider to track smart contracts events or other things, my suggestion would be to instantiate a WebSocketProvider provider to do this and use other provider (Web3Provider/JsonRpcProvider) to execute the transactions.