简体   繁体   English

如何在 web3 上调用 function

[英]How to call function on web3

I'm trying to call a function on web3, but it doesn't get executed on web3.我试图在 web3 上调用 function,但它没有在 web3 上执行。 It just doesn't popup Metamask wallet to ask for the transaction approval, so it doesn't execute.它只是不会弹出 Metamask 钱包来请求交易批准,因此它不会执行。

Solidity function:坚固性 function:

function Deposit(uint _amount) payable public{
    require(msg.value == _amount);
    funds[msg.sender] += _amount;
}

Function on web3 Function on web3

  deposit = async(depositAmount)=>{
    const web3 = window.web3
    const ethers = web3.utils.toWei(this.depositAmount.value, 'ether')
    await web3.contract.methods.Deposit(depositAmount).send({from: this.account, value: ethers})
  }

How is the function called function怎么叫

<form className="deposit" onSubmitCapture={(event) => {
              event.preventDefault()
              const amount = this.amount
              this.deposit(amount)
            }}>
              <input type="text" className="inputs" placeholder="Amount to deposit" 
              ref={(input)=>this.amount = input}/>
              <input type="submit" className="btn" value="DEPOSIT"/>
        </form>

I'm loading web3 and loading blockchain data correctly, and deposit function is called in a button component.我正在加载 web3 并正确加载区块链数据,并在按钮组件中调用存款 function。 Just wanted to know if it has something to do with this code, or the problem might be somewhere else.只是想知道它是否与此代码有关,或者问题可能出在其他地方。 The smart contract is correctly migrated with truffle and ganache.智能合约使用松露和甘纳许正确迁移。

You need to initialize web3 properly.您需要正确初始化 web3。 According to the docs, you should initialize as const web3 = new Web3(web3.currentProvider).根据文档,您应该初始化为const web3 = new Web3(web3.currentProvider).

//You can use with gasLimit param. //您可以与 gasLimit 参数一起使用。

await web3.contract.methods.Deposit(depositAmount).send({from: this.account, value: ethers, gasLimit: "21000"})等待 web3.contract.methods.Deposit(depositAmount).send({from: this.account, value: ethers, gasLimit: "21000"})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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