【问题标题】:Calling the set() function (with web3js) of a solidity contract is creating a new contract address. Why?调用 Solidity 合约的 set() 函数(使用 web3js)正在创建一个新的合约地址。为什么?
【发布时间】: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 任何地址的交易是合约创建交易。
  • 这里可能有问题,但我认为您在此处粘贴代码时遗漏了一些内容。它看起来不正确。我想你错过了右括号。

标签: ethereum solidity web3js


【解决方案1】:

添加to: contractAddress,

在下面的代码块中

  const txObject = {
    nonce:    web3.utils.toHex(txCount),
    // value:    web3.utils.toHex(web3.utils.toWei('0.1', 'ether')),
    gasLimit: web3.utils.toHex(1000000),
    gasPrice: '5000',
    // gasPrice: '0x' + estimatedGas,
    data: data,
    from: myAccount,
    to: contractAddress,

解决问题。

谢谢@smarx!

【讨论】:

    猜你喜欢
    • 2018-02-04
    • 2019-07-08
    • 2022-12-03
    • 2021-09-11
    • 2022-07-05
    • 2018-12-19
    • 1970-01-01
    • 2019-06-16
    • 1970-01-01
    相关资源
    最近更新 更多