0

This is the contract im calling createP to push Post

    struct Post {
        uint256 amt;
        bool isActive;
        address owner;
    }

    Post[] public posts;

    function createP(uint256 amt) public payable returns(uint a) {
        posts.push(Post({
            amt: amt,
            isActive: false,
            owner: msg.sender
        }));
        return (posts.length);
    }
    function getPostLength() returns(uint a){
        return (posts.length);
    }

Truffle code

        MyContract.deployed()
        .then(async instance => {
            const weiSpend = web3.toWei(2, "ether");
            var id = await instance.createP.call(10,{
                from: accounts[0],
                value: weiSpend
            });
        var id2 = await instance.createP.call(50,{
          from: accounts[1],
          value: weiSpend
        });
        var id3 = await instance.createP.call(100,{
          from: accounts[2],
          value: weiSpend
        });                        
        var last = await instance.getPostLength.call();
        console.log(id3.toString()); // returns 1 instead of 3
        console.log(last.toString()); // returns 0 instead of 3
        });
1

You can call a function in a smart contract two different ways:

  1. You can call it, in which case no transaction is sent to the Ethereum network. The result is computed locally (on whatever node you're connected to) and returned. This is fast and free, but no state can be mutated.
  2. You can send a transaction, in which case you must pay for gas, and a transaction is sent to the network. Once it is mined into a block, its mutations take effect.

Because you're trying to modify the state variable posts, you need to actually send a transaction. But instance.createP.call is instead just calling it as though it does not mutate state. Use instance.createP.sendTransaction instead.

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.