gpt4 book ai didi

javascript - 无法通过 JavaScript 更新 solidity 合约的状态变量

转载 作者:行者123 更新时间:2023-11-30 19:08:37 25 4
gpt4 key购买 nike

我有以下契约(Contract),只想更新其状态变量值,即 totalSupply。但是,当我尝试通过 JavaScript 代码(如下所示)调用其函数(即 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;
}

}

我只想更新它的值(value),即总供应量。以下是我用于上述目的的 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的值不会更新。

关于javascript - 无法通过 JavaScript 更新 solidity 合约的状态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58731372/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com