reactjs 如何在solidity中将字符串传递给setter函数?

ecbunoof  于 2023-01-30  发布在  React
关注(0)|答案(1)|浏览(114)

我尝试在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)
我哪里做错了?

monwx1rj

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] });

相关问题