【问题标题】:Error: random is not a function solidity/web3js错误:随机不是一个函数solidity/web3js
【发布时间】:2018-10-04 17:57:49
【问题描述】:

我正在尝试从我的智能合约上使用“区块难度”和“区块时间戳”的函数中提取一个随机数。

solidity 代码如下所示:

pragma solidity ^0.4.18;

 contract ApprovalContract {

  function random() external view returns (uint8){
  return uint8(uint256(keccak256(abi.encodePacked(block.timestamp, 
  block.difficulty)))%251);
  } 
 ...
 }

用 JS 编写的应用程序代码如下所示:

ApprovalContract.methods.random().call(
        function(error, result) {
            if (error) {
              console.log('error: ' + error);
            }
            else {
              console.log('result: ' + JSON.stringify(result));
            }
          });

我需要做的就是将随机生成的数字记录到控制台。不幸的是,我一直看到“未捕获的 TypeError:ApprovalContract.methods.random 不是函数”

【问题讨论】:

  • 将其更改为ApprovalContract.methods.random.call(...)random 上没有括号)
  • @AdamKipnis index.html:204 Uncaught TypeError: Cannot read property 'call' of undefined at HTMLFormElement. (index.html:204) at HTMLFormElement.dispatch (jquery-3.2.1. slim.min.js:3) 在 HTMLFormElement.q.handle (jquery-3.2.1.slim.min.js:3) 我也看不到我的“随机”函数列为合约对象中的方法跨度>

标签: ethereum solidity smartcontracts web3 web3js


【解决方案1】:

您尚未发布完整的 JS 代码,因此不清楚您是如何获得 ApprovalContract 的。理想情况下应该如下所示。您需要大于 1.0 的 web3js 版本才能运行此代码。我用的版本是1.0.0-beta.34。

var approvalcontract_artifact = require('../build/contracts/ApprovalContract.json'); /*Please insert path of your ApprovalContract.json in here */
var Web3 = require('web3');
var web3 = new Web3('https://ropsten.infura.io/7dsXakGVRMs1EwuYwkQv'); /*Your Client Endpoint */

var ApprovalContract = new web3.eth.Contract(approvalcontract_artifact.abi, '0x3f6eeae6bb291ed249a4cbff22c49f0ce96b723a'); /* Please write your contract address in place of this address */

var random = ApprovalContract.methods.random().call()
    .then(function(result){
       console.log('result: ' + JSON.stringify(result));
    })
    .catch(function(error) {
      console.log('error: ' + error);
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-01
    • 2014-04-27
    • 2011-03-18
    • 2022-11-10
    • 2022-01-05
    • 2018-04-03
    • 2014-12-25
    相关资源
    最近更新 更多