1

I have a problem with understanding. I created a utility function, safeMath() , which I run first to create the block. Next, I get the block number, which is usually in the range from 10 to 14. And then I try to get the hash of this block, but I get zeros.

In the code below, the blockh variable always return 0x000...

//SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol";

contract getBlockhash {
    uint a = 5;
    uint b = 2;
    uint public c;
    bytes32 public blockh;
    uint public blockn;

    using SafeMath for uint256;

    function hashBlock() public {
        blockn = block.number;      
        blockh = blockhash(blockn);
    }

    function safeMath() public {
        c = a.sub(b);
    }

}
1

1 Answer 1

0

Are you using Remix?

Because this seems to be a remix issue.

I used your code and modified it a bit so I can play experiment with it. And it does return awkward results. (I only get real Blockhash for block.number = 0 )

//SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol";

contract Blockhash {
    uint a = 5;
    uint b = 2;
    uint public c;
    bytes32 public blockh;
    uint public blockn;

    using SafeMath for uint256;

    function getBlockNumber() public view returns(uint) {
        return block.number;
    }

    function getBlockhash(uint blocknumber) public view returns(bytes32) {
        return blockhash(blocknumber);
    }

    function hashBlock() public {
        blockn = block.number;
        blockh = blockhash(blockn);
    }

    function safeMath() public {
        c = a.sub(b);
    }

}
3
  • don't worry it will give real hash in real blockchain. and for tests, you can put 32 random bytes
    – Nulik
    Commented Dec 20, 2022 at 15:12
  • So it's really just a Remix issue?
    – Sky
    Commented Dec 20, 2022 at 15:37
  • I don't use Remix, so can't tell. But if you want to try your contract upload it to test net or create local chain using geth and you will see the hash properly set
    – Nulik
    Commented Dec 20, 2022 at 16:24

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