Sunday, November 13, 2016

Truffle and Ethereum - call vs transactions

After banging my head for 4 hours trying to figure out why my sample Dapp doesn't actually save (persist) data to my contract I found out that i was actually making a call instead of executing a transaction .

What's the difference between a call and a transaction you say ?

- Well a call is free ( does not cost any gas ) , it is readonly and will return a value
- whilst a transaction costs gas , it usually persists something and does not return anything

Please read the "Making a transaction" and "Making a call" section in the offical lib: 

Say for example in your app.js of your truffle app you have a fictionious setComment and getComment function ( to persist and retrieve comments respectively ) this is how they could look like :

===Extract app.js====================

function setComment(){

 // Assuming your contract is called MyContract
  var meta = MyContract.deployed();

//Taking a comment field from page to save 
  var comment = document.getElementById("comment").value;

// Note that the setComment should exist in your MyContract
  meta.setComment(comment,{from: account}).then(function() {

    setStatus( "Tried to save Comment:" +comment);
  }).catch(function(e) {
    setStatus("Error saving comment .. see log."+ e);

function getComment(){
  var meta = MyContract.deployed();

 // notice that in the readonly getComment method that after method name a .call is used
// this is what differentiates a call from a transaction{from: account}).then(function(value) {

    setStatus( "Comment:" +value);
  }).catch(function(e) {
    setStatus("Error retrieving comment .. see log."+ e);



Roshan Gunoo said...
And in Java ;)

Javed Mandary said...

Aha thanks for the share :) ... javascript seems to rule the world these days :P