Home > other >  Solidity - Contract not working as expected
Solidity - Contract not working as expected

Time:01-02

I am new to Solidity and Ethereum. I am at the stage where I have worked with basic HelloWorld and similar examples.

I have created a contract to generate a random number as follows

// 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;

}

}

This contract is working when I deploy and run it at enter image description here

However, If I try to deploy & run it within Visual Studio Code I get the following error

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

enter image description here

Why should this happen? Any inputs are appreciated. I know I might be missing something basic here

Thanks in advance

CodePudding user response:

It's been a while since I did any solidity coding, but this one is easy.

I believe your contract is working fine.

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

BN is "big number". Since a 256 bit uint doesn't work with a javascript "number" (floating point) type, the result is encoded in a BN data structure. (i.e. your random number is embedded in the words member of your returned object. (I think it's a literal 3 if I read that output right).

In your local javascript that tests your Solidity contract, just invoke toString on the BN object that is returned.

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

CodePudding user response:

Even though you did not share your javacript code, I can tell that it is because you are not awaiting.

Calling contract code is asynchronous and you either call it with async.await or with then/catch

//in truffle console:

   randomContract=await RandomNumber.deployed()
   randomContract.generateRandomNumber(rangeInteger)

CodePudding user response:

Try to update the solidity library in Vs

  • Related