Skip to content

Instantly share code, notes, and snippets.

@Y5Yash
Created September 25, 2023 07:18
Show Gist options
  • Save Y5Yash/721a5f5c3e392a6a28f47db1d3114501 to your computer and use it in GitHub Desktop.
Save Y5Yash/721a5f5c3e392a6a28f47db1d3114501 to your computer and use it in GitHub Desktop.
convert address to checksum string (EIP-55) in solidity
function addressToChecksumString(address tempaddr) public view returns (string memory) {
bytes memory lowercase = addressToLowercaseBytes(tempaddr); // get address in lowercase hex without '0x'
bytes32 hashed_addr = keccak256(abi.encodePacked(lowercase)); // get the hash of the lowercase address
bytes memory result = new bytes(42); // store checksum address with '0x' prepended in this.
result[0] = '0';
result[1] = 'x';
uint160 addrValue = uint160(tempaddr);
uint160 hashValue = uint160(bytes20(hashed_addr));
for (uint i = 41; i>1; --i) {
uint addrIndex = addrValue & 0xf;
uint hashIndex = hashValue & 0xf;
if (hashIndex > 7) {
result[i] = _CAPITAL[addrIndex];
}
else {
result[i] = _SYMBOLS[addrIndex];
}
addrValue >>= 4;
hashValue >>= 4;
}
return string(abi.encodePacked(result));
}
// get small case character corresponding to a byte.
function getChar(bytes1 b) internal pure returns (bytes1 c) {
if (uint8(b) < 10) return bytes1(uint8(b) + 0x30);
else return bytes1(uint8(b) + 0x57);
}
// get convert address bytes to lowercase char hex bytes (without '0x').
function addressToLowercaseBytes(address x) internal pure returns (bytes memory) {
bytes memory s = new bytes(40);
for (uint i = 0; i < 20; i++) {
bytes1 b = bytes1(uint8(uint(uint160(x)) / (2 ** (8 * (19 - i)))));
bytes1 hi = bytes1(uint8(b) / 16);
bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi));
s[2 * i] = getChar(hi);
s[2 * i + 1] = getChar(lo);
}
return s;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment