Web3js – How to Trigger Contract Fallback Function from JavaScript

contract-developmentfallback-functionweb3js

For a simple contract:

pragma solidity ^0.4.11;

contract Test {
   uint private val;

   function getVal() constant returns(uint) {
       return val;
   }

   function setVal(uint newVal) payable {
       val = newVal;
   }

   function() {
       val++;
   }
}

getVal will be called from web3.js something like this:

contract.getVal.call(function(err, val) {
    //
});

setVal will be called from web3.js something like this:

contract.setVal.sendTransaction(newVal, 
  {
     gas: gas, 
     from: web3.eth.defaultAccount
  }, 
  function(err, result) {
      //
  });

How to trigger unnamed function from Javascript? Is it possible?

Best Answer

The simplest is to use web3.eth.sendTransaction.

Use the contract address for to. Leave data empty (this is the field that determines which function is invoked in a contract). Usually you would specify the amount of wei value, but you can omit this if you just want to invoke the fallback function.

Fallback functions are not intended to be used the way you might be planning. For example: they are not executed after any other function executes (you can't do work in other functions and expect that the fallback would be called to then increment a variable); they are also not intended for cleanup.

For more background: When does the fallback function get called?