目前,我有一个智能合约成功部署到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,也没有抛出任何类型的错误。我当然不会从实际的事件监听器那里得到控制台。我猜我发送交易的方式有问题,但我认为我正确地遵循了下面记录的模式:
https://web3js.readthedocs.io/en/1.0/web3-eth-contract.html#methods-mymethod发送
有人知道如何使用web3.10正确地进行合约方法调用吗?我是否在传递选项等方面做错了什么。?
我相信您忘记为您的web3指定HttpProvider
,因此您没有连接到实时Rinkeby网络,并且默认情况下web3在您的本地主机上运行,这就是为什么即使您提供了正确的合同地址,也没有任何内容。
要连接到实时网络,我强烈建议您使用ConsensSys的Infura 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()
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
});
}