我尝试在solidity中执行一个简单的函数,我将一个值传递给set()
函数,它将该值存储在智能合约中的一个预声明变量中。truffle unbox react
提供的初始代码工作正常,您传递给它一个int
,它返回事务散列,但是,如果我传递给它一个字符串,它会抛出一个错误。
这是truffle unbox react
提供的初始代码/契约
react.pragma solidity ^0.5.0;
contract SimpleStorage {
uint storedData;
function set(uint x) public {
storedData = x;
}
function get() public view returns (uint) {
return storedData;
}
}
我是这么叫的,
componentDidMount = async () => {
try {
const web3 = await getWeb3();
const accounts = await web3.eth.getAccounts();
const networkId = await web3.eth.net.getId();
const deployedNetwork = SimpleStorageContract.networks[networkId];
const contract = new web3.eth.Contract(
SimpleStorageContract.abi,
deployedNetwork && deployedNetwork.address
);
this.setState({ web3, accounts, contract });
} catch (error) {
alert(
`Failed to load web3, accounts, or contract. Check console for details.`
);
}
};
这就是功能
contract.methods.set(5).send({ from: accounts[0] });
const response = await contract.methods.get().call();
这是新合同:
pragma solidity ^0.5.0;
contract SimpleStorage {
string storedData;
function set(string memory x) public {
storedData = x;
}
function get() public view returns (string memory) {
return storedData;
}
}
我就这么叫,
contract.methods.set("5").send({ from: accounts[0] });
const response = await contract.methods.get().call();
我收到以下错误
errors.js:85未捕获(在承诺中)错误:动态字节长度的数据不足(参数="",编码类型="动态字节",值="0x0000000000000000000000000000000000000000000000000000000000005",版本= 4.0.33)
我哪里做错了?
1条答案
按热度按时间monwx1rj1#
在Web3 1.0中,bytes和string类型的函数参数必须使用
web3.utils.asciiToHex()
转换为十六进制字节字符串。代替
contract.methods.set("5").send({ from: accounts[0] });
,执行:
contract.methods.set(web3.utils.utf8ToHex("5")).send({ from: accounts[0] });