[Ethereum] call function from truffle console (newbie)

testingtruffle

This should be fairly simple, but I'm still trying to wrap my mind around a lot of things.

What is the easiest way of testing the function addEntity by hand? What command do I type into the truffle console to execute addEntity?

Thanks

 pragma solidity ^0.4.18;
 
 
 contract MetaCoin {
      struct  Entity {
               string name;
               string nickname;
               string streetaddress;
      }
      mapping (uint => Entity) entities;
      uint entitiesCount;
      event EntityAdded(address indexed _senderAddress, uint _entityId);

      function addEntity(string _name, string _nickname, string _streetaddress) returns(uint entityId) {
            entityId=entitiesCount ++;
            entities[entityId]=Entity(_name,_nickname,_streetaddress);
            EntityAdded(msg.sender,entityId);
      }
 }

Best Answer

In truffle console you can do the following.
1.Get a deployed instance of the contract and store it in a variable (coin).

MetaCoin.deployed().then(function(instance) {coin=instance;});

2.Now execute the addEntity function with your own variables.

coin.addEntity('x', 'y', 'z');

When this is executed it will show you a transaction receipt (or errors if any occurred).
3.Check the entities mapping for the new entity.

coin.entities(1);

This shows you the entity that you just created based on the increment value of entitiesCount variable.

If you want to test with specific gas and account settings you can modify the call to addEntity function to include account and gas values.

coin.addEntity('x','y','z', {from:web3.eth.accounts[0], gas:500000, gasPrice: web3.toWei(1,"Gwei")})



UPDATED: Code modifications
1. Add public to the entities mapping so it is accessible.
2. Change entities=entitiesCount++ to just entitiesCount++
3. Used entitiesCount instead of entityId when storing the new entity.
4. You could remove the returns value or define a return uint for the entityCounter variable if you need it.

     pragma solidity ^0.4.18;

     contract MetaCoin {
          struct  Entity {
                   string name;
                   string nickname;
                   string streetaddress;
          }
          mapping (uint => Entity) public entities;
          uint entitiesCount;
          event EntityAdded(address indexed _senderAddress, uint _entityId);

          function addEntity(string _name, string _nickname, string _streetaddress) returns(uint entityCount) {
                //entityId=entitiesCount ++;
                entitiesCount++;
                entities[entitiesCount]=Entity(_name,_nickname,_streetaddress);
                EntityAdded(msg.sender,entitiesCount);
          }
     }


This will make coin.entities(1) work as initially described.

Related Topic