首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Web3/JS:无法使用“.call()”读取“公共视图”函数,而调用其他函数(如call等…)工作精细

Web3/JS:无法使用“.call()”读取“公共视图”函数,而调用其他函数(如call等…)工作精细
EN

Ethereum用户
提问于 2020-11-23 12:16:55
回答 1查看 996关注 0票数 0

我在这里张贴一个问题,我已经张贴在堆栈溢出之前,我意识到这个ethereum论坛。不确定这样做的礼仪,所以请告诉我是否应该删除堆栈溢出帖子(https://stackoverflow.com/questions/64909327/web3-js-unable-to-read-a-public-view-function-using-call-while-the-call)。

我正在为博彩智能合同编写一个小应用程序(使用react),该应用程序受教程的启发(信用给:https://medium.com/coinmonks/create-a-sports-betting-dapp-on-the-ethereum-blockchain-part-1-1f69f908b939)。

这个教程很棒,但是我不得不在这里和那里做一些修改,因为这个教程有点过时(很明显,它是在Metamask使用.enable()提高安全性之前编写的)。但是总的来说,除了一件事之外,我设法使所有的东西都正常工作,而且我真的不明白为什么它不能工作(尝试了大量的修复,但是都没有起作用)。

在我的坚实契约中,我有一个非常简单的吸气器:

代码语言:javascript
复制
   // Getter for front end: amount of Bets in Pool1
   function AmountOne() public view returns(uint256){
       return totalBetOne;
   }

我很确定这个函数可以工作,因为我已经在Remix上测试过了

所以我的猜测是这个问题来自我的js脚本。同样奇怪的是,所有对其他函数的调用--它们都比较复杂--工作得很好,只有这个函数不能工作。现在,我真的是这门语言的初学者,所以我很难理解到底出了什么问题。任何帮助都将不胜感激。我的应用程序脚本如下:

代码语言:javascript
复制
 //constructor
     constructor(){
          super();
          this.state={
            web3: '',
            Amount: '',
            InputAmount: '',
            weiConversion: 1000000000000000000
          }
          this.getAmount = this.getAmount.bind(this);
          this.Bet = this.Bet.bind(this); 
        }
    
    
    //load web 3
    componentDidMount(){
        getWeb3.then(results => {
          /*After getting web3, we save the informations of the web3 user by
          editing the state variables of the component */
          results.web3.eth.getAccounts( (error,acc) => {
            //this.setState is used to edit the state variables
            this.setState({
              web3: results.web3
            })
          });
          //At the end of the first promise, we return the loaded web3
          return results.web3
        }).then(results => {
          //In the next promise, we pass web3 (in results) to the getAmount function
          this.getAmount(results)
        }).catch( () => {
          //If no web3 provider was found, log it in the console
          console.log('Error finding web3.')
        })
      }
    
      //Smart Contract function THAT DOES NOT WORK
  getAmount(web3){
    //Get the contract
    const contract = require('@truffle/contract');
    const Betting = contract(BettingContract);
    Betting.setProvider(web3.currentProvider);
    var BettingInstance;
    web3.eth.getAccounts((error, accounts) => {
        Betting.deployed().then((instance) => {
            //Instantiate the contract in a promise
            BettingInstance = instance
        }).then((result) => {
            //Calling the AmountOne function of the smart-contract
            return BettingInstance.AmountOne().call() // <-- issue: seems to return an empty value
        }).then((result) => {
            //Then the value returned is stored in the Amount state var.            
            this.setState({
                Amount : result.c              
            })
        });
    })
}
    
    
      //Smart Contract function THAT WORKS
      Bet(){
            //const contract = require('truffle-contract');
            const contract = require('@truffle/contract');
        const Betting = contract(BettingContract);
        Betting.setProvider(this.state.web3.currentProvider);
        var BettingInstance;
        this.state.web3.eth.getAccounts((error, accounts) => {
          Betting.deployed().then((instance) => {
            BettingInstance = instance
          }).then((result) => {
            // Get the value from the contract to prove it worked.
            return BettingInstance.bet(1, {from: accounts[0],
            value: this.state.InputAmount})
          }).catch(() => {
            console.log("Error with betting")
          })
        })
      }

如果错误来自我的getWeb3,下面是脚本:

代码语言:javascript
复制
import Web3 from 'web3'

let getWeb3 = new Promise(function(resolve, reject) {
  // Wait for loading completion before loading web3, to be sure it's
  // already injected
  window.addEventListener('load', function() {
    var results
    var web3 = window.web3
    
    // Pop-up to ask user to connect his Metamask
    // Modern DApp Browsers
    if (window.ethereum) {
      web3 = new Web3(window.ethereum);
      try { 
        window.ethereum.enable().then(function() {
            // User has allowed account access to DApp...
        });
      } catch(e) {
        // User has denied account access to DApp...
      }
    }
    // Legacy DApp Browsers
    else if (window.web3) {
      web3 = new Web3(window.web3.currentProvider);
    }
    // Non-DApp Browsers
    else {
      alert('You have to install MetaMask !');
    }

    // Connect to Metamask
    // Checking if Web3 has been injected by the browser MetaMask
    if (typeof web3 !== 'undefined') {
      // Use MetaMask's provider.
      web3 = new Web3(web3.currentProvider)
      results = {
        web3: web3
      }
      console.log('Injected web3 detected.');
      resolve(results)
    } else {
      // If no web3 is detected, then the local web3 provider is loaded.
      var provider = new Web3.providers.HttpProvider('http://127.0.0.1:9545')
      web3 = new Web3(provider)
      results = {
        web3: web3
      }
      console.log('No web3 instance injected, using Local web3.');
      resolve(results)
    }
  })
})
export default getWeb3

我没有包括所有的应用程序的其他部分,因为这篇文章已经够长了,但请问一下,如果你认为它可能相关的话,我很乐意把它们包括进去。

谢谢你的帮助!

EN

回答 1

Ethereum用户

回答已采纳

发布于 2020-11-24 09:55:13

好的,实际上这里的主要问题已经解决了:混乱控制台的问题:无法读取未定义的属性“调用”

我必须做一些其他的更改,以便粘贴在我的上下文中工作的代码,以防有人试图做这个教程,但无法使它工作:

代码语言:javascript
复制
getAmount(web3){
//Get the contract
const contract = require('@truffle/contract');
const Betting = contract(BettingContract);
Betting.setProvider(web3.currentProvider);
//var BettingInstance;
web3.eth.getAccounts((error, accounts) => {
Betting.deployed().then(function(instance) {
return instance.AmountTwo.call({from: accounts[0]})
}).then(function(AmountTwo){
const myres = AmountTwo.toString();
return myres
}).then((myres)=>{
this.setState({
Amount : myres/10**18
})
})
})
} 
票数 0
EN
页面原文内容由Ethereum提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://ethereum.stackexchange.com/questions/90438

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档