Hash
To hash a part of memory in Yul, we use the keccak256(a, b)
function. This function takes in two arguments, the location in memory to start and the size of the memory to hash.
Normal Hash
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
contract Yul {
function hash(uint256 a) public pure returns (bytes32) {
assembly {
mstore(0x80, a)
let hash := keccak256(0x80, 0x20)
mstore(0x80, hash)
return(0x80, 0x20)
}
}
}
To Has A Variable In Memory
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
contract Yul {
function hashString(string memory s) public pure returns (bytes32) {
assembly {
mstore(0x80, 0x20)
mstore(0xa0, mload(s))
mstore(0xc0, mload(add(s, 0x20)))
mstore(0x80, keccak256(0x80, 0x60))
return(0x80, 0x20)
}
}
}