Ethereum Asked by contute on August 26, 2021
I would like to build a simple JavaScript (JS) front end that checks if a field submitted is the pre-image of a keccak256 hash I already know in my smart contract. I currently use the following:
Front end JS:
<script src="https://cdn.jsdelivr.net/gh/emn178/js-sha3/build/sha3.min.js"></script>
<script>keccak_ = keccak_256;</script>
<script lang="javascript">
.
.
$("a#call_preimage").click(function(){
var preimage = $("input#preimage").val();
var hash_ = keccack_(newNumber);
var hash__ = '0x'+ hash_;
var params = {from:web3.eth.accounts[0]}
contractInstance.checkPreimage(hash__, params, function(error, result){...
Solidity:
function checkPreimage(uint256 incoming) public {
if (uint256(keccak256(abi.encodePacked(known_preimage))) == incoming){
do_something(); }}
// known_preimage is of type uint 256 as well
I can’t seem to pass the if condition. I’m certain all other parts of the code work.
You should use web3's soliditySha3
utility function.
In your case, since there is only one parameter to be hashed:
// 234 is your preimage
const hash = web3.utils.soliditySha3(new BN('234'));
If you wish to hash more than one parameters:
uint256 hash = uint256(keccak256(abi.encodePacked(known_preimage1, known_preimage_2)));
const hash = web3.utils.soliditySha3(
{t: 'uint256', v: new BN('234')},
{t: 'address', v: '0x407D73d8a49eeb85D32Cf465507dd71d507100c1'},
);
Answered by roynalnaruto on August 26, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP