Search code examples
javascriptethereumethers.js

How to connect to custom Provider using ethers?


How do you create a new Provider using a custom node url using the ethers package?

Looking to do something like this:

 const provider = new ethers.providers.Web3Provider('http://my-node.com')

Solution

  • In the documentation here it says to use JsonRpcProvider instead of Web3Provider.

    // When using the JSON-RPC API, the network will be automatically detected
    
    
    // Default: http://localhost:8545
    let httpProvider = new ethers.providers.JsonRpcProvider();
    
    
    // To connect to a custom URL:
    let url = "http://something-else.com:8546";
    let customHttpProvider = new ethers.providers.JsonRpcProvider(url);
    
    
    // Connect over named pipes using IPC:
    let path = "/var/run/parity.ipc";
    let ipcProvider = new ethers.providers.IpcProvider(path);
    

    Update for ethers v6

    ethers.providers.* updated to ethers.* for providers as indicated in the docs.Additionally, to support EIP-1193 the Web3Provider for window.ethereum has been changed to BrowserProvider as follows:

    // v5
    provider = new ethers.providers.Web3Provider(window.ethereum)
    
    // v6:
    provider = new ethers.BrowserProvider(window.ethereum)