1
function hasRole(uint256 tokenId, string memory role) public view returns (bool) {
    string[] memory userRoles = tokenToRoles[tokenId];
    uint256 userRolesLength = userRoles.length;
    unchecked {
        for (uint256 i; i < userRolesLength; ++i) {
            // if (keccak256(abi.encodePacked(userRoles[i])) == keccak256(abi.encodePacked(role))) {
            //     return true;
            // }
            if (userRoles[i] == role) {
                return true;
            }
        }
    }
    return false;
}

The above function compares a string memory from a string[] array that I've copied to memory from storage with a string memory that is passed in through the function parameters. You would think such a comparison would be possible, however I am getting the following error in Foundry from the Solidity Compiler (version 0.8.17)

Compiler run failed
error[2271]: TypeError: Operator == not compatible with types string memory and string memory.
  --> src/policy/VertexPolicyNFT.sol:50:21:
   |
50 |                 if (userRoles[i] == role) {
   |                     ^^^^^^^^^^^^^^^^^^^^

the lines commented out are a working solution (hashing the two values and comparing the hashes), but it seems excessive and would be cleaner and less gas intensive if we could find a way to compare the strings.

0

2 Answers 2

0

this works

//SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

contract StringComparison {

    string public a = "test";

    //pass "test" to b
   function compareStrings(string memory b) public view returns (bool) {
    return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))));
}
}
1
  • I have this solution already commented out in my post. This is not the solution I am looking for. wondering how to compare the strings directly without hashing.
    – dd0sxx
    Commented Jan 16, 2023 at 16:31
-1

Actually you should post your state mapping and arrays, but the thing which i realized it that: tokenToRoles is a mapping or array which stored some strings, you get an index of it by tokenId, so When you defining userRoles as element of tokenToRolesyou should set an string not an array of string likestring[]` you trying to get one element of array ,which is an string and define it as a array of string , then try to get an element of your new array which is you defined. You should get element of array this way:

string memory userRoles = tokenToRoles[tokenId];

Not the answer you're looking for? Browse other questions tagged or ask your own question.