简体   繁体   中英

How to connect Expo to Ganache

I am trying to connect my Typescript Expo app to a local Ganache node using ethers.js. Currently my code looks like this:

import React, {useEffect, useState} from 'react'
import {View, Text} from 'react-native'
import "react-native-get-random-values"
import "@ethersproject/shims"
import { ethers } from 'ethers'

const ganacheUrl = "http://127.0.0.1:7545"

const Portfolio:React.FC = () => {
    const provider = new ethers.providers.JsonRpcProvider(ganacheUrl)
    const signer = provider.getSigner()
    const [wallet,setWallet] = useState<Wallet>({privateKey:'',address:'',mnemonic:{phrase:''}})
    useEffect(() => {
        const newWallet = ethers.Wallet.createRandom()
        const connectedWallet = newWallet.connect(provider)
        const currentGas = connectedWallet.getGasPrice()
        setWallet({privateKey:connectedWallet.privateKey,address:connectedWallet.address,mnemonic:connectedWallet.mnemonic})
    },[])



    return(
        <View>
            <Text style={{color:theme.colors.textWhite}}>Your public address:</Text>
            <Text style={{color:theme.colors.textWhite}}>{wallet.address}</Text>
        </View>
    )
}

The public address is being displayed correctly, but when I try to get some on-chain data (like Gas Price) I get "NO-NETWORK" error. I suppose that my expo client can't connect to Ganache node because of the url, and the fact that native and web applications use different host notations (localhost vs 192.168.1.1) but I am not sure what exactly do I need to change to make this thing work.

I just found this post and have the same problem. But after looking at your post, I got an epiphany.

If you are using the ganache client, you can go to the settings and switch the server to your own Ethernet, otherwise, look if you have settings for your ganache-cli that can switch your setting to the IP address of your node server ip address so that the expo device can access the node within the local area network.

Etc. If your computer/machine running the ganache node has an IP of 192.168.12.4 then you put this instead as your node server IP and ganache defaults listen to port 8545. Hope this helps you although I am close to a year late here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM