2

Basically is it possible for constant functions to emit events? Example bellow:

I have Sample Contract which has a getData() function which does not modify any state, emits an event and returns a string value.

contract Sample {

    event ExampleEvent(string data_description);

    function getData() public constant returns (string) {
        ExampleEvent("From Sample contract");
        return "Event sent";
    }
}

Then I try to call it through nodejs with web3.js using .call() (this does not emit event)

SampleContract(abi).at(address).getInfo.call({from:{account});

I only receive the "Event sent" string as a response, but no event has been created.

However if I call this function via a transaction .sendTransaction()(this emits event)

SampleContract(abi).at(address).getInfo.sendTransaction({from:{account});

This returns the transaction hash as expected (since I'm creating a transaction) but it also creates a new event.

I understand that constant functions cannot change a contract state however a new event is not really part of the contract storage/state (events/logs are stored in the transaction logs)?

What is the reason for this not to be working, am I missing something obvious?

1

Events are used in transactions only. When you execute a transaction function you can't get the return value because transactions are not immediately mined and included in the blockchain.

Events allow you to get notified when the transaction has been mined in order to get the return value.

It makes no sense trying to call an Event inside a call function, given that they will return a value "immediately".

  • 5
    There is a special case where it makes sense to call a constant function as part of a transaction: When the constant function is called from another non-constant function. Still, constant functions cannot emit events because that would modify the blockchain state. Constant functions are not only disallowed from altering the storage of the current contract, they cannot have any effect that requires a change to the block hash (apart from gas consumption), and the events are (through the transaction receipt) part of the block hash. – chriseth Oct 6 '17 at 23:04
  • @chriseth Thanks, that's exactly what I was wondering about. – Valdi_K Oct 9 '17 at 9:07

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.