0

I am trying pull a random number generated from a function on my smart contract that uses the' block difficulty' and the 'block time stamp'.

The solidity code looks like this:

pragma solidity ^0.4.18;

 contract ApprovalContract {

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

The application code written in JS looks like this:

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

All I need to do is log the randomly generated number to the console. Unfortunately, I keep seeing "Uncaught TypeError: ApprovalContract.methods.random is not a function"

  • 1
    I updated the ABI definition and random definitely shows up as a function in the ABI – Sachit Shetty Oct 5 '18 at 16:01
  • Make the function public – Kashish Khullar Oct 5 '18 at 16:27
  • The function is external, so you should be good in terms of accessibility. How are you initializating ApprovalContract in your javascript code? – Henk Oct 5 '18 at 19:53
  • @Henk var ApprovalContract = new web3.eth.Contract(abi,contractAddress) – Sachit Shetty Oct 6 '18 at 21:47
1

Remove the () after methods.random. random isn't a function on methods, it's an object.

  • I don't understand though. How would I 'call' random if it shows up as an object?How do I access this data? I'm trying to implement rudimentary 2-factor authentication by generating a random number that I can call from the smart contract and then send it back to the smart contract in order to authenticate. – Sachit Shetty Oct 6 '18 at 22:18
  • Random is a function in Solidity, but when web3.js generates the contract object for interacting with it, it creates random as an object. This is because it has multiple functions on it – flygoing Oct 6 '18 at 22:28
  • so should I rename my function? I still don't see how I can access the data in random. Please help!! – Sachit Shetty Oct 7 '18 at 0:30
  • Just change ApprovalContract.methods.random().call to ApprovalContract.methods.random.call. Random is an object on the methods object, not a function. You are calling an object as a function. – flygoing Oct 7 '18 at 0:41
  • I did try that, I'm getting "Cannot read property 'call' of undefined". Thank you for your help! – Sachit Shetty Oct 7 '18 at 0:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.