【问题标题】:Solidity - Contract not working as expectedSolidity - 合同没有按预期工作
【发布时间】:2022-01-01 16:18:57
【问题描述】:

我是 Solidity 和以太坊的新手。我正处于使用基本 HelloWorld 和类似示例的阶段。

我已经创建了一个合约来生成如下随机数

// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;

contract RandomNumber {

function generateRandomNumber(uint range) public view returns(uint) {
// As of 1-1-22 this contract is working okay at https://remix.ethereum.org/
// However I am having issues in running it through the Visual Studio Code IDE
return uint(keccak256(abi.encodePacked(block.timestamp,block.difficulty, msg.sender))) % range;

}

}

当我在https://remix.ethereum.org/ 部署和运行此合约时,它正在运行

但是,如果我尝试在 Visual Studio Code 中部署和运行它,我会收到以下错误

BN { negative: 0, words: [ 3, <1 empty item> ], length: 1, red: null }

为什么会发生这种情况?任何输入表示赞赏。我知道我可能在这里遗漏了一些基本的东西

提前致谢

【问题讨论】:

    标签: visual-studio-code ethereum solidity smartcontracts remix


    【解决方案1】:

    我已经有一段时间没有进行任何 Solidity 编码了,但是这个很简单。

    我相信你的合同运作良好。

    BN { negative: 0, words: [ 3, &lt;1 empty item&gt; ], length: 1, red: null }

    BN 是“大数”。由于 256 位 uint 不适用于 javascript“数字”(浮点)类型,因此结果以 BN 数据结构编码。 (即,您的随机数嵌入在您返回的对象的 words 成员中。(如果我没看错的话,我认为这是一个文字 3)。

    在测试 Solidity 合约的本地 javascript 中,只需在返回的 BN 对象上调用 toString。

    https://ethereum.stackexchange.com/questions/67087/how-to-use-bignumbers-in-truffle-tests

    【讨论】:

      【解决方案2】:

      即使您没有分享您的 javacript 代码,我也可以看出这是因为您没有在等待。

      调用合约代码是异步的,您可以使用async.await 或then/catch 调用它

      //in truffle console:
      
         randomContract=await RandomNumber.deployed()
         randomNumber=await randomContract.generateRandomNumber(rangeInteger)
         // this should print
         randomNumber.toString()
      

      【讨论】:

      • 我明白了。我正在 Truffle 控制台(开发环境)中解决这个问题。在这种情况下如何使用 async / await?
      • @Nomad 我更新了答案
      • 嗨耶尔姆纳兹,感谢您的帮助。它仍然对我不起作用。你能再看一遍这个问题,并可能微调你的答案吗?
      • @Nomad 我更新了答案。我没有正确完成代码
      • @Yilmnaz 感谢您的帮助。通过在最后输入 randomNumber,我得到了 BN 的结果。我必须使用 await 将这个 toString 转换为如下 await randomNumber.toString()
      【解决方案3】:

      尝试更新Vs中的solidity库

      【讨论】:

      • 我已经检查过了。我有最新版本的 Solidity 扩展 0.0.136
      • 可能只是一个评论
      猜你喜欢
      • 2020-05-31
      • 1970-01-01
      • 1970-01-01
      • 2018-01-02
      • 1970-01-01
      • 1970-01-01
      • 2021-10-19
      • 2020-03-18
      • 2012-06-14
      相关资源
      最近更新 更多