【发布时间】:2018-11-07 17:21:56
【问题描述】:
我有一个带有 set() 函数的简单可靠合约。当我调用合约的 set() 函数时,生成的交易位于新创建的合约地址,而不是 Solidity 代码所在的合约地址。
如果我在 Remix 中使用 UI,则新交易(带有更新的字符串值)与原始合约相关联。当我尝试用 web3js 做同样的事情时,正在创建全新的合同。
我希望所有使用 web3js 的新 get() 调用都与原始合同相关联。
Solidity 代码
pragma solidity ^0.4.0;
contract HashRecord {
string public hashValue;
function setHashValue(string newHashValue) public {
hashValue = newHashValue;
}
function getHashValue() public view returns (string) {
return hashValue;
}
}
web3js 代码
var Tx = require('ethereumjs-tx')
const Web3 = require('web3')
const web3 = new Web3('https://ropsten.infura.io/v3/d55489f8ea264a1484c293b05ed7eb85')
const abi = [ABI_CODE]
const contractAddress = '0x6c716feb775d5e7b34856edf75048a13fe0c16b0'
const myAccount = '0x59f568176e21EF86017EfED3660625F4397A2ecE'
const privateKey1 = new Buffer('PRIVATE_KEY', 'hex')
hashValue = 'newly updated value'
const contract = new web3.eth.Contract(abi, contractAddress,{
from: myAccount,
web3.eth.getTransactionCount(myAccount, (err, txCount) => {
//Smart contract data
const data = contract.methods.setHashValue(hashValue).encodeABI()
// Build the transaction
const txObject = {
nonce: web3.utils.toHex(txCount),
gasLimit: web3.utils.toHex(1000000),
gasPrice: '5000',
data: data,
from: myAccount,
}
// Sign the transaction
const tx = new Tx(txObject)
tx.sign(privateKey1)
const serializedTx = tx.serialize()
// Broadcast the transaction
web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex')).
on('receipt', console.log)
})
我的猜测是这与const contract = new web3.eth.Contract创建新合同有关。我想不出另一种方法来做到这一点。
再次,我希望存储在变量 hashValue 下的新值与 const contractAddress = '0x6c716feb775d5e7b34856edf75048a13fe0c16b0' 的原始合约地址相关联
谢谢!!!
【问题讨论】:
-
您的交易中似乎缺少
to地址。不是to任何地址的交易是合约创建交易。 -
这里可能有问题,但我认为您在此处粘贴代码时遗漏了一些内容。它看起来不正确。我想你错过了右括号。