首页 文章

调用solidity Contract 的set()函数(使用web3js)正在创建一个新的 Contract 地址 . 为什么?

提问于
浏览
0

我有一个简单的solidity Contract 与set()函数 . 当我调用 Contract 的set()函数时,生成的事务处于新创建的 Contract 地址,而不是实体代码所在的 Contract 地址 .

如果我在Remix中使用UI,则新事务(具有更新的字符串值)与原始 Contract 相关联 . 当我用web3js尝试同样的事情时,正在创建全新的 Contract .

我希望所有与web3js的新get()调用都与原始 Contract 相关联 .

Solidity Code

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 创建新 Contract 有关 . 我无法想出另一种方法来做到这一点 .

同样,我希望存储在变量 hashValue 下的新值与 const contractAddress = '0x6c716feb775d5e7b34856edf75048a13fe0c16b0' 的原始 Contract 地址相关联 .

谢谢!!!

1 回答

  • 0

    添加 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!

相关问题