我正在尝试使用 ethers.js 将我的 Typescript Expo 应用程序连接到本地 Ganache 节点。目前我的代码如下所示:
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>
)
}
公共地址显示正确,但是当我尝试获取一些链上数据(如 Gas Price)时,我收到“NO-NETWORK”错误。我想我的 expo 客户端无法连接到 Ganache 节点,因为 url 以及本机和 Web 应用程序使用不同的主机表示法(localhost vs 192.168.1.1)的事实,但我不确定我到底需要更改什么让这件事发挥作用。