I'm having a problem with the blockhash function at remix.ethereum.org. Despite several attempts with different codes the blockhash function always causes problems and the result is that all variables are returned with a value of zero.
In the case below, the _previousBlockNumber variable always return zeroed. If the blockhash function line is commented out then the error does not occur and at least the _previousBlockNumber variable returns correctly.
I've tried several different versions of compilers.
pragma solidity ^0.5.5;
contract Test {
constructor() public {
}
function rand() public view returns(uint,bytes32) {
uint _previousBlockNumber;
bytes32 _previousBlockHash;
_previousBlockNumber = uint(block.number - 1);
bytes32 _previousBlockHash = bytes32(blockhash(_previousBlockNumber));
return (_previousBlockNumber,_previousBlockHash);
}
}
It's a bug issue?
Thanks for any help.
I tried to run this code to fix the problem and it's working for me with some changes. Same contract you can find on Rinkebey Testnet with this address 0x86ee6d633fd691e77dc79cbdb2a9fb108f79ecbd
.
pragma solidity ^0.5.5;
contract Test {
uint256 i;
constructor() public {
}
function rand() public view returns(uint,bytes32) {
uint _previousBlockNumber;
bytes32 _previousBlockHash;
_previousBlockNumber = uint(block.number - 1);
_previousBlockHash = bytes32(blockhash(_previousBlockNumber));
return (_previousBlockNumber,_previousBlockHash);
}
function setI(uint256 k) public{
i = k;
}
}
Initially, you were declaring the _previousBlockHash
two times, and second time on the line of blockhash
function. I fix it and working fine.
Secondly, in the current contract code you are not changing any state of the contract and not doing any transaction, rand()
is just an call, which will not add any other block. So it will always remain 0
. I add one dummy transaction function for testing which is working fine now.
Lastly, try to run this on live test network to see actual things. Hope it will work.