簡體   English   中英

State Solidity 合約變量無法通過 JavaScript 更新

[英]State Variable of solidity Contract could not be updated through JavaScript

我有以下合同,只想更新其 state 變量值,即 totalSupply。 但是,當我嘗試通過 JavaScript 代碼(如下所示)調用其 function 即 setTotalSupply 來嘗試此任務時,tts 值不會更新。

pragma solidity 0.5.1;

contract MyContract {

    uint256 totalSupply; 
    mapping(address => uint256) public balances;
    address owner;

    constructor(address payable _wallet) public {
        totalSupply = 10;
        owner = _wallet;
    }

    function () external payable{
        buyToken();
    }

    function buyToken() public payable {
        require(totalSupply >= (msg.value/1000000000000000000)*2);
        balances[msg.sender] += (msg.value/1000000000000000000)*2;
        // wallet.tranfer(msg.value);
        totalSupply -=(msg.value/1000000000000000000)*2;

    }
    function getTotalSupply()public view returns  (uint256 ){
        return totalSupply;
    }
       function setTotalSupply(uint256 newSupply)public {
        require(msg.sender == owner && totalSupply<1);
        totalSupply = newSupply;

    }
    function getBalance() public view returns  (uint) {
        return address(this).balance;
    }

}

我只想更新它的價值,即總供應量。 以下是我的 JavaScript 代碼用於上述目的

var Tx = require('ethereumjs-tx').Transaction
const Web3 = require('web3');
const provider = new Web3.providers.HttpProvider("https://ropsten.infura.io/v3/7fb0bdc97c.....");
 const web3 = new Web3(provider);

var contract1  = new web3.eth.Contract(contractABI, contractAddress1)
const txData2 = contract1.methods.setTotalSupply(10).encodeABI(); 
setSupplyBalance(contractAddress1, txData2);

function setSupplyBalance(contractAddress, txData ){

web3.eth.getTransactionCount(account1, (err, txCount) => {
      txObject = {
      nonce:    web3.utils.toHex(txCount),
      gasLimit: web3.utils.toHex(1000000),
      gasPrice: web3.utils.toHex(web3.utils.toWei('100', 'gwei')),
      to: contractAddress,
      value: web3.utils.toHex(web3.utils.toWei('0', 'ether')),
      data:txData
    }




  const tx = new Tx(txObject, {chain:'ropsten', hardfork: 'petersburg'})
// sign the trx
tx.sign(privateKey1)

serializedTx = tx.serialize()

raw = '0x' + serializedTx.toString('hex')

  web3.eth.sendSignedTransaction (raw, (err, txHash)=> {
    console.log('err:', err)
    console.log('txHash', txHash)
  })

  })

}

更新

我想我找到了原因。 部署合約時,您沒有在構造函數中為_wallet變量提供正確的地址,因此它不會通過 setTotalSupply 中的 require 語句。


調用 setTotalSupply 時,totalSupply 是否等於 0?

因為你在 setTotalSupply 中有一條 require 語句,如果它不為 0,那么事務將被還原,totalSupply 的值不會被更新。

使應付totalSupply和function setTotalSupply,然后使值為零的trx將解決此錯誤...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM