Blockchain 使用Web3 1.0调用智能合约方法

Blockchain 使用Web3 1.0调用智能合约方法,blockchain,ethereum,solidity,web3,Blockchain,Ethereum,Solidity,Web3,目前,我已经成功地将智能合约部署到Rinkeby测试网,使用web3版本1.0访问有问题的方法时遇到问题 下面是我的web3代码,它实例化了一个合同实例并调用了一个合同方法: const contractInstance = new web3.eth.Contract(abiDefinition, contractAddress); var value = web3.utils.toWei('1', 'ether') var sentTransaction = contractInstance.

目前,我已经成功地将智能合约部署到Rinkeby测试网,使用web3版本1.0访问有问题的方法时遇到问题

下面是我的web3代码,它实例化了一个合同实例并调用了一个合同方法:

const contractInstance = new web3.eth.Contract(abiDefinition, contractAddress);
var value = web3.utils.toWei('1', 'ether')
var sentTransaction = contractInstance.methods.initiateScoreRetrieval().send({value: value, from: fromAddress})

console.log('event sent, now set listeners')

sentTransaction.on('confirmation', function(confirmationNumber, receipt){
  console.log('method confirmation', confirmationNumber, receipt)
})
sentTransaction.on('error', console.error);
这是我的智能合约,或者更确切地说是一个版本,它被精简到相关的部分:

contract myContract {

  address private txInitiator;
  uint256 private amount;


  function initiateScoreRetrieval() public payable returns(bool) {
    require(msg.value >= coralFeeInEth);
    amount = msg.value;
    txInitiator = msg.sender;
    return true;
  }


}
我无法访问在web3端设置事件侦听器的console.log,并且没有引发任何类型的错误。我当然不会从实际的事件侦听器那里得到控制台。我猜我发送交易的方式有问题,但我认为我正确地遵循了以下记录的模式:

有人知道如何使用web3 1.0正确地进行契约方法调用吗?我在传递期权等方面是否做错了什么


谢谢

我相信您忘记为您的web3指定您的
HttpProvider
,因此您没有连接到live Rinkeby网络,并且默认情况下web3在您的本地主机上运行,这就是为什么即使您提供了正确的合同地址,也没有任何内容

要连接到实时网络,我强烈建议您使用ConsenSys的Node

const Web3=require(“Web3”);

const web3=new web3(new web3.providers.HttpProvider(“https://rinkeby.infura.io"));首先,您需要使用
encodeABI()
生成事务ABI,下面是一个示例:

let tx_builder = contractInstance.methods.myMethod(arg1, arg2, ...);
let encoded_tx = tx_builder.encodeABI();
let transactionObject = {
    gas: amountOfGas,
    data: encoded_tx,
    from: from_address,
    to: contract_address
};
然后您必须使用发送方的私钥使用
signTransaction()
对事务进行签名。稍后您可以
sendSignedTransaction()


谢谢亚历克斯,但我做到了。我只是删掉了代码,以避免在堆栈溢出时代码过于复杂。很好,但这不是问题所在。更改事件发射器以检查
transactionHash
Receive
。事务哈希的回调将是您得到的第一个响应。如果你得到了,但从来没有收到收据,那么你的交易就没有被挖掘。我还将明确包括
gasPrice
gas
值。最后,您是否在Etherscan上确认您的合同已正确部署?
web3.eth.accounts.signTransaction(transactionObject, private_key, function (error, signedTx) {
        if (error) {
        console.log(error);
        // handle error
        } else {
            web3.eth.sendSignedTransaction(signedTx.rawTransaction)
              .on('receipt', function (receipt) {
              //do something
             });
    }