1

I wonder why data insertion in users occurs only once, while userCount updates correctly?

pragma solidity >=0.4.22 <0.7.0;

contract TestChainStorage {

address private owner;
uint256 public userCount;

    struct User {
        uint256 userNumber; // User number at registration time
        uint256 regTime;    // Registration time (unixTime)
        string userName;
        address userWallet;
    }

    User[] public users;

    modifier isOwner() {
        require(msg.sender == owner, "Caller is not owner");
        _;
    }

    constructor() public {
        owner = msg.sender; // 'msg.sender' is sender of current call, contract deployer for a constructor
    }

    function store(uint256 unixtime, string memory username) public {
        userCount++;
        users.push(User({
        regTime : unixtime,
        userName : username,
        userWallet : msg.sender,
        userNumber : userCount
        }));
    }

    function compareWallet (string memory a, string memory b)  internal pure returns (bool){
       return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))) );
   }

    function kill() public isOwner {
       selfdestruct(msg.sender);
   }
}

enter image description here

enter image description here

enter image description here

Any help appreciated!

1 Answer 1

0

You can access only one element of an array with the automatically generated getter method (the argument passed is the position of the array to return, default is 0). To get the full array, you need to write a getter yourself that returns an array.

Also, I recommend you use a mapping instead of a dynamic array:

contract TestChainStorage {

    ...

    uint256 public userCount;

    struct User {
        uint256 userNumber; // User number at registration time
        uint256 regTime;    // Registration time (unixTime)
        string userName;
        address userWallet;
    }

    mapping(uint256 => User) users;

    ...

    function store(uint256 unixtime, string memory username) public {
        users[userCount] = User({
        regTime : unixtime,
        userName : username,
        userWallet : msg.sender,
        userNumber : userCount
        });
        userCount += 1;
    }

    ....

}    

EDIT
Here is how you can get the user array in the mapping version:

function getUsers() public view return(User[] memory userArray) {
    userArray = new User[](userCount);
    for(uint i = 0; i < userCount; i++){
      userArray[i] = users[i];
    }
}
1
  • function getUsers() public view returns (User[] memory userArray) { Additional: pragma experimental ABIEncoderV2;
    – pr0logas
    Mar 11, 2020 at 17:12

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.