I've just been trying for a week now to figure this out...
I just want to be able to enter a customer's name and increase their level by 1.
I am trying to do that by iterating through an array of structs to find their name and then when the name matches up, increase the level by 1.
I am getting the error type string storage ref is not implicitly convertible to expected type bool
on line 20
Here's my code:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.8;
contract LevelUp {
struct Customers {
string name;
uint256 level;
}
Customers[] public customers;
mapping (string => uint256) nameToTicketLevel;
function addCustomer(string memory _name, uint256 _ticketLevel) public {
customers.push(Customers(_name, _ticketLevel));
nameToTicketLevel[_name]=_ticketLevel;
}
function levelUp(string memory _name) public {
for (uint i = 0; i <= customers.length; i++ ){
if (customers[i].name = _name){
customers[i].ticketLevel += 1;
}
}
}
}
The problem is in your levelUp function, you used the assignment operator =
instead of the equality operator ==
inside the if statement on line 20.
Additionally, iterating over a dynamic array in Solidity can be gas inefficient, especially if the array grows in size. Each iteration consumes gas, and if the array gets too large, it can result in high gas costs. It's recommended to avoid iterating over dynamic arrays in Solidity whenever possible.
A better approach would be to use only a mapping to store your customers.
You already made something, you made the
mapping (string => uint256) nameToTicketLevel;
then why using also the array?
You can use only that, the main thing is that from your function every user can call the addUser
function, so using the "name" var as key of the mapping is wrong, since users can overwrite other user's data
Use the wallet address instead and save the name inside the struct
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.8;
contract LevelUp {
struct Customers {
string name;
uint256 level;
}
mapping (address => Customers) customers;
function addCustomer(string memory _name, uint256 _ticketLevel) public {
customers[msg.sender] = Customers(_name, _ticketLevel);
}
function levelUp(string memory _name) public {
customers[msg.sender].level++;
}
}
Anyways I think addCustomer
should be onlyOwner
or the contract should have a different logic, since now users can't overwrite other user's data, but can do whatever they want with their data.
Anyway this is the fix of the error