-
Notifications
You must be signed in to change notification settings - Fork 378
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
✨ Feature request: utility function to check if a string contains only alphanumeric characters #962
Comments
Alternatively, a utility function to check if a single character is alphanumeric would also be helpful: function isAlphanumericChar(bytes1 char) internal pure returns (bool) {
bool isSpace = char == SPACE;
bool isDigit = char >= ZERO && char <= NINE;
bool isUppercaseLetter = char >= A && char <= Z;
bool isLowercaseLetter = char >= a && char <= z;
return isSpace || isDigit || isUppercaseLetter || isLowercaseLetter;
} |
Good feature request. Will add, thanks. |
@PaulRBerg your request is fulfilled check it out. |
Personally, I think it's quite surprising that Other examples I can find of
Maybe it would be better to have 2 functions? Other CharactersIf we are going to special case "spaces", I can also think of other characters that might deserve the same treatment. Right now, I'm writing a contract that requires strings be alphanumeric, or function _validateUrlSafe(string calldata urlSlug) internal pure {
// Check that the slug is no more than 16 bytes (which will be 16 characters assuming ASCII).
uint256 length = bytes(urlSlug).length;
if (length > 16) revert TooLong();
// Check all characters are alphanumeric or hyphen/underscore.
for (uint256 i = 0; i < length; i++) {
bytes1 charCode = bytes(urlSlug)[i];
// a-z, A-Z, hyphen, underscore
if (
(charCode > 0x60 && charCode < 0x7B) // a-z
|| (charCode > 0x40 && charCode < 0x5B) // A-Z
|| (charCode == 0x2D) // hyphen (-)
|| (charCode == 0x5F) // underscore (_)
) continue;
// numbers (0-9)
if (charCode > 0x2F && charCode < 0x3A) continue;
revert InvalidChar();
}
} |
Btw, there is also a |
Rationale
Onchain generation of NFT SVGs is on the rise. Many SVGs rely on third-party string data, e.g. ERC-20 symbols.
To sanitize strings and prevent XSS attacks, developers should only allow alphanumeric strings in the token symbol1. This should be enough, since the vast majority of tokens don't contain any special symbols.
It would thus be helpful to have a utility function in Solady for checking whether a string contains only alphanumeric characters.
Example Implementation
Footnotes
See, for example, finding M-01 in Sablier's recent audit contest on CodeHawks. ↩
The text was updated successfully, but these errors were encountered: