Created
July 24, 2024 14:37
-
-
Save developeruche/3de82874ea23fe624c666ad20117dea3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
contract EIP712 { | |
bytes32 private constant TYPE_HASH = | |
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); | |
bytes32 private immutable _cachedDomainSeparator; | |
uint256 private immutable _cachedChainId; | |
address private immutable _cachedThis; | |
bytes32 private immutable _hashedName; | |
bytes32 private immutable _hashedVersion; | |
string private _name; | |
string private _version; | |
string private _nameFallback; | |
string private _versionFallback; | |
constructor(string memory name, string memory version) { | |
_name = name; | |
_version = version; | |
_hashedName = keccak256(bytes(name)); | |
_hashedVersion = keccak256(bytes(version)); | |
_cachedChainId = block.chainid; | |
_cachedDomainSeparator = _buildDomainSeparator(); | |
_cachedThis = address(this); | |
} | |
function _domainSeparatorV4() internal view returns (bytes32) { | |
if (address(this) == _cachedThis && block.chainid == _cachedChainId) { | |
return _cachedDomainSeparator; | |
} else { | |
return _buildDomainSeparator(); | |
} | |
} | |
function _buildDomainSeparator() private view returns (bytes32) { | |
return keccak256(abi.encode(TYPE_HASH, _hashedName, _hashedVersion, block.chainid, address(this))); | |
} | |
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { | |
return toTypedDataHash(_domainSeparatorV4(), structHash); | |
} | |
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) public pure returns (bytes32) { | |
bytes memory encodedData = abi.encodePacked("\x19\x01", domainSeparator, structHash); | |
return keccak256(encodedData); | |
} | |
/** | |
* @dev See {IERC-5267}. | |
*/ | |
function eip712Domain() | |
public | |
view | |
virtual | |
returns ( | |
bytes1 fields, | |
string memory name, | |
string memory version, | |
uint256 chainId, | |
address verifyingContract, | |
bytes32 salt, | |
uint256[] memory extensions | |
) | |
{ | |
return ( | |
hex"0f", // 01111 | |
_EIP712Name(), | |
_EIP712Version(), | |
block.chainid, | |
address(this), | |
bytes32(0), | |
new uint256[](0) | |
); | |
} | |
// solhint-disable-next-line func-name-mixedcase | |
function _EIP712Name() internal view returns (string memory) { | |
return _nameFallback; | |
} | |
// solhint-disable-next-line func-name-mixedcase | |
function _EIP712Version() internal view returns (string memory) { | |
return _versionFallback; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment