solidity – Managing Logical Negation, Struct Conditions, and Mappings in Contracts

mappingsoliditystruct

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

Best Answer

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))
Related Topic