0

I'm still playing around with my first bigger smart contract, and I'm creating something like public sale, ICO, etc.

Now I'm at the point where I want to specify some conditions like:

  • one address can participate only once
  • maximum allocations, and etc.

My question is: what is the correct approach to implement such conditions, how to do some checks in my function before proceeding if I can't do logical negation on structs, mappings?

1.) I have declared struct with some data and mapping where I want to store my structs:

struct Investor {
        address account;
        uint invested;
    }

mapping(address => Investor) public investors;

2.) Here is my invest function where I want to deal with some checks:

    function invest() external payable {

        // Here I want to check if msg.sender already exists as an investor in my mapping.

    }

3.) My approach was just to check if msg.sender is in my mapping and just negate it:

require(!investors[msg.sender]);

But it doesn't work as I would expect from JS experience as structs are not convertable to type boolean. How to deal with conditions like this? Should I just change the way I store my data?

compile error

EDIT

4.) Looks like it's not working even with out negation.

require(!investors[msg.sender].account)

Is not working: "! cannot be aplied to type address".

require(investors[msg.sender].account);

and

require(investors[msg.sender]);

Doesn't work and code cannot compile with error:

enter image description here

6
  • This might work require(!investors[msg.sender].account)
    – pbsh
    Commented Jan 26, 2022 at 13:08
  • It doesn't work for me, as I'm getting same kind of error but saying that negation cannot be applied to type address
    – BlackH3art
    Commented Jan 26, 2022 at 17:18
  • This should work require(investors[msg.sender].account!=address(0))
    – pbsh
    Commented Jan 26, 2022 at 17:26
  • Yes. This working. Thanks. But what if I would have mapping like: mapping(address => uint) and wanted to check if some address is already in my mapping?
    – BlackH3art
    Commented Jan 26, 2022 at 17:34
  • In that case, require(investors[msg.sender] != 0) should work. This is because, in a mapping, all the uninitiated indexes default to zero.
    – pbsh
    Commented Jan 26, 2022 at 17:38

1 Answer 1

1

Adding the answer so it's easier for others to find.

In a mapping, by default all uninitiated indexes default to zero. So does structs. So a mapping, to see if it's initialised, we can just check value. In this case, we can check the address and make sure it's not zero.

require(investors[msg.sender].account!=address(0))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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