0

大家好!

在我开始之前,我只是说我是区块链开发的新手,尝试学习,但是从前端管理合约对我来说很困难,仅此而已。

所以,我尝试调用在 truffle 上开发的合约的状态,在 React 中使用 web3.js,问题是这样的,当我尝试查看令牌的价格(已经定义)时,它会引发错误,那个错误:

未处理错误:此合约对象尚未设置地址,请先设置地址

这是我的 App.js 的代码:

  const [AccountData, setAccountData] = useState({
    web3: 'undefined',
    account: '',
    balance: 0
  })

  const [Contracts, SetContracts] = useState({
    Token: '',
    Sale: ''
  })

  const PreLoad =async()=>{
    if (typeof window.ethereum !== 'undefined') {
      const web3 = new Web3(window.ethereum)
      const netId = await web3.eth.net.getId()
      const accounts = await web3.eth.getAccounts()

      if (typeof accounts[0] !== 'undefined') {
        const balance = await web3.eth.getBalance(accounts[0])
        setAccountData({ account: accounts[0], balance: web3.utils.fromWei(balance) })
      } else {
        window.alert('Please Login with MetaMask')
      }

      try{
        const Token = new web3.eth.Contract(SuperToken.abi, SuperToken.networks[netId.address])
        const Sale = new web3.eth.Contract(TokenSale.abi, TokenSale.networks[netId.address])
        SetContracts({Token, Sale})
      }
      catch(err){
        console.log(err)
        alert('Error, see the console')
      }

    }
    else{
      alert('please install MetaMask or any provider!!')
    }
  }
  
  useEffect( () => {
    PreLoad()
  }, [])


  const BuyToken = async(e)=>{
    e.preventDefault()
    console.log('Buying')
    let price = await Contracts.Sale.methods.tokenPrice().call()
    console.log(price)
  }

我认为我很好地遵循了 web3 的文档,并在 useEffect 上加载了良好的合同,所以我真的不知道为什么会发生这种情况。如果有人可以帮助我,那就太好了!!

PS:如果您需要更多信息,请给我留言!

解决方案: 当我用 web3 调用合约时出错,这是正确的 wey:

SuperToken.abi, SuperToken.networks[netId].address

业余问题,抱歉,谢谢!

4

0 回答 0