1
    pragma solidity >=0.8.13;

    contract MyContract {
    
    // ...Variables declared here
    
    constructor() {
            // ... Variables initialized here
        }
    
    address[] public myParticipants;
    
     function someFunction() public {
     myParticipants.push(msg.sender);
    
    }
}

However, if I use truffle and call myParticipants.length it always returns me 0, even if someFunction() has been called a couple of times and addresses have been pushed into the array. Why is that?

4
  • In smart contract code that you shared, you did not declare the contract. Is it an oversight or no? Commented May 11, 2022 at 13:15
  • It's just a question oversight, in the code it is declared. I'll edit my question. Commented May 11, 2022 at 13:21
  • @AndrewHoover898 How are you getting myParticipants.length in truffle?
    – Ismael
    Commented May 11, 2022 at 13:40
  • >MyContract.deployed().then((instance) => { mc= instance; }); >mc.myParticipants.length Commented May 12, 2022 at 15:12

1 Answer 1

1

you cannot acces to the length of the array because the getter function for myParticipants doesn't return the entire array and that is the reason why you can't access to the array length

from the doc:

If you have a public state variable of array type, then you can only retrieve single elements of the array via the generated getter function. This mechanism exists to avoid high gas costs when returning an entire array. You can use arguments to specify which individual element to return, for example data(0). If you want to return an entire array in one call, then you need to write a function, for example:

take a look at my answer to this question

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.