...by Daniel Szego
quote
"On a long enough timeline we will all become Satoshi Nakamoto.."
Daniel Szego

Sunday, November 25, 2018

How to trigger Ethereum smart contract if Solidity event occurs


Well you cannot react to an event in a solidity smart contract, there is no command at all in EVM that checks the event log. Besides, there is no way of starting a smart contract automatically. However, you can use a semi-trusted setup with Oraclize, where similarly to my previous blog, you can periodically check if an event has occurred.

Firstly, you can use an Ethereum explorer API to get information of an event of a contract with the following http get request.

https://api-ropsten.etherscan.io/api?module=logs&action=getLogs
   &fromBlock=<from>
   &toBlock=latest
   &address=<contract address>
   &topic0=<event id>&
   apikey=<YourApiKeyToken>

So, what you have to do is to query this log periodically with Oraclize and check if the necessary information is present.

  // schedule update schedules the next call
 function scheduleUpdate() payable {
   if (oraclize_getPrice("URL") > this.balance) {
       LogNewOraclizeQuery("Not enough fund");
   } else {
       // NEXT UPDATE IS SCHEDULED IN 60 MIN
      oraclize_query(60, "URL", " url explorer API for the event ");
   }
 }

 function __callback(bytes32 myid, string result) {
    // SECURITY CHECK
    if (msg.sender != oraclize_cbAddress()) revert();
        
    // PROCESS INFORMATION
    if (information_not_present){
    // SCHEDULE NEXT UPDATE
       scheduleUpdate();
    }
 }

Certainly this is not the cheapest and most efficient way of triggering a smart contract for an event, but it might work on a small scale. Experimental implementation can be found under EventTriggeredEthereumContract in the following GitHub repo