Skip to content

Commit

Permalink
feat: break out address checksum encoding to erc55EncodeAddress function
Browse files Browse the repository at this point in the history
  • Loading branch information
legobeat committed Jul 11, 2023
1 parent 3245089 commit 18660b6
Showing 1 changed file with 21 additions and 16 deletions.
37 changes: 21 additions & 16 deletions src/hex.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,26 @@ export function isValidHexAddress(possibleAddress: Hex) {
);
}

/**
* Encodes a passed hex string as an ERC-55 mixed-case checksum address.
* Specification: https://eips.ethereum.org/EIPS/eip-55.
*
* @param address - The hex address to encode.
* @returns The address encoded according to ERC-55.
*/
export function erc55EncodeAddress(address: Hex) {
const unPrefixed = remove0x(address.toLowerCase());
const unPrefixedHash = remove0x(bytesToHex(keccak256(unPrefixed)));
return `0x${unPrefixed
.split('')
.map((character, nibbleIndex) =>
parseInt(unPrefixedHash[nibbleIndex] as string, 16) > 7
? character.toUpperCase()
: character,
)
.join('')}`;
}

/**
* Validate that the passed hex string is a valid ERC-55 mixed-case
* checksum address.
Expand All @@ -91,22 +111,7 @@ export function isValidChecksumAddress(possibleChecksum: Hex) {
return false;
}

const unPrefixed = remove0x(possibleChecksum);
const unPrefixedHash = remove0x(
bytesToHex(keccak256(unPrefixed.toLowerCase())),
);

for (let i = 0; i < unPrefixedHash.length; i++) {
const value = parseInt(unPrefixedHash[i] as string, 16);
if (
(value > 7 && unPrefixed[i]?.toUpperCase() !== unPrefixed[i]) ||
(value <= 7 && unPrefixed[i]?.toLowerCase() !== unPrefixed[i])
) {
return false;
}
}

return true;
return erc55EncodeAddress(possibleChecksum) === possibleChecksum;
}

/**
Expand Down

0 comments on commit 18660b6

Please sign in to comment.