0

How do I dynamically call an event with a name? For example, my contract has a few events and based on some conditions I would like to call one of them. I don't want to use a switch or an if statement but would like to specify the name of the event and call it with data

I tried the following simple example but it didn't work.

event StoredValue(
   string data);

function callEvent(string eventName, data) {
this.call(bytes4(sha3("StoredValue(data)")));
}

I want to pass a name and arguments into a function which will be used to call the event

0

Events aren't functions, so you'll have to wrap them in functions to accomplish this and instead pass the function name in, e.g:

modifier onlySelf(){
    require(msg.sender==this);
    _;
}

event EventOne(string data);
event EventTwo(string data);

function logEventOne(string data) public onlySelf{
    EventOne(data);
}

function logEventTwo(string data) public onlySelf{
    EventTwo(data);
}

function callEvent(string functionSignature, string data){
    this.call(bytes4(sha3(functionSignature)),data);
}

Note that, since this.call will create a message call, the functions you call must be public to work. To get around the fact that they're public, I added the onlySelf modifier so only the contract can call them.

I would advise against doing any of this since events must exist at compile time anyway, so you can just do EventOne/EventTwo directly instead of dynamically.

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.