1

This is my code. When i push address into participants the length is zero. Why?

pragma solidity ^0.4.0
contract Registration {
    address public owner;
    uint threshold = 2;
    address [] participants;
    // The addres is used to map on the balances that we have
    mapping(address => uint) public balances;
    uint conceptPrice;
    enum Stage{Initial, Registered, Modifiable, Done}
    Stage public stage = stage = Stage.Initial;
    function concept(uint _conceptPrice) public {
        owner = msg.sender;
        stage = Stage.Registered;
    }
    function saveContra() public constant returns (uint numParticipants){
        if (stage != Stage.Registered) return;
        participants.push(msg.sender);
        if (participants.length > threshold) {
            mineConcept();
        }
        //It is 0
        numParticipants = participants.length;
    }
    function mineConcept(){
        balances[owner] += 100;
        for (uint i = 0; i < participants.length; i++) {
            balances[participants[i]] += 1;
        }
        stage = Stage.Modifiable;
    }
}
1

There are a number of issues with your contract, but the reason why you are getting a return of 0 is NOT because it is returning numParticipants, but because your code is exiting at:

if (stage != Stage.Registered) return;

Likely, you have not called function concept(), which means stage was never set to Stage.Registered. Then that if statement fails, and returns nothing, which in Solidity uint is 0.

To fix some of the problems going on in your contract:

  • You should not mark the saveContra() function as constant since it modifies the state of participants.
  • You should probably change function concept() to contructor() so that it is run when your contract deploys, automatically setting the owner and the stage
  • You should have your contract "fail early, and fail loud" when there are conditions not met. So rather than if (stage != Stage.Registered) return;, you should write require(stage == Stage.Registered). Now when this condition is not satisfied, your contract will revert, something that would have helped you debug this issue to begin with.

These are just a few suggestions to get started, but not a comprehensive list of other issues in your contract.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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