Open
Description
π§ Motivation
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 OpenZeppelin for checking whether a string contains only alphanumeric characters.
π Example Implementation
/// @notice Checks whether the provided string contains only alphanumeric characters and spaces.
/// @dev Note that this returns true for empty strings, but it is not a security concern.
function isAlphanumeric(string memory str) internal pure returns (bool) {
// Convert the string to bytes to iterate over its characters.
bytes memory b = bytes(str);
uint256 length = b.length;
for (uint256 i = 0; i < length; ++i) {
bytes1 char = b[i];
// Check if it's a space or an alphanumeric character.
bool isSpace = char == 0x20; // space
bool isDigit = char >= 0x30 && char <= 0x39; // 0-9
bool isUppercase = char >= 0x41 && char <= 0x5A; // A-Z
bool isLowercase = char >= 0x61 && char <= 0x7A; // a-z
if (!(isSpace || isDigit || isUppercase || isLowercase)) {
return false;
}
}
return true;
}
Footnotes
-
See, for example, finding M-01 in Sablier's recent audit contest on CodeHawks. β©