1

Supose I Have a contract like

contract foo{

    bytes32[] bar;

    function set(bytes32 _foo) {
        bar.push(_foo);
    }
}

So if i deploy the contract what will happen 1st. And for every time when i call set() will the whole bar array need to be writen in chain or only the newest element will be writen in chain as a transaction. Now if i hav a getter for bar then how it will return the all element of that array?

2

So if i deploy the contract what will happen 1st.

This contract has no constructor, so at deployment nothing much happens - the contract code is copied into the blockchain, that's all. No storage is allocated at this point.

And for every time when i call set() will the whole bar array need to be writen in chain or only the newest element will be writen in chain as a transaction

Only the newest element is written; the previous elements remain untouched.

Two things happen when you call set:

  1. An additional storage location is written to with your input value _foo.

    You will be charged 20000 gas for setting the element to a non-zero value.

  2. The length of the array is updated. Solidity maintains this as a separate record in storage for you.

    The first time you call set, intially setting this length record will cost 20000 gas; subsequent calls only update it and cost 5000 gas.

Now if i hav a getter for bar then how it will return the all element of that array?

You can create a getter automatically by declaring bar like this:

bytes32[] public bar;

This creates a "constant" function bar(uint n) which returns element n from the array. If you need to know how long the array is you will need to write a function for that:

function getLength() returns (uint) {
    return bar.length;
}

If you want to get the whole array returned with a single call, you can add your own getter function:

function returnAll() returns (bytes32[]) {
    return bar;
}
  • Thanks @benjaminion but fir getter i am interested ti know the process of data retrival. Will it 1st go to the deployed address of contrct then will it read one by one transaction to give me the vakue of bar array? – Sidhartha Majumder Aug 19 '17 at 15:25
  • The information you seek is in my answer... Either use the automatic getter to get the values one-by-one, or write a getter like returnAll() above to get it all at once. The contract just reads the storage and returns the data; it's quite simple. – benjaminion Aug 19 '17 at 15:35

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.