cowprotocol/solver-rewards

Handle Unsafe TransactionEvent Cast

Opened this issue · 0 comments

When it comes to type casting; you should avoid casting directly as shown above, since it is essentially an unsafe practice.

The code reads as you only expect a single type of event, however if I check the ActionFn definition, it would seem it is a generic event handler. So, ideally what you would want to do is;

  1. Create a guard so that you only execute code if it is a TransactionEvent.
  2. Have a way of dynamically verifying the type of event.

In such case, you can use something called "type guard". A type guard returns a "type predicate", i.e. the result is the cast of type, so to speak;

function isTransactionEvent(event: Event): event is TransactionEvent {
    // However you'd like to verify this. The following is just a rough example.
    // You just need to return true / false with regards to `event` being a TransactionEvent.
    return typeof event === 'object' && !!event && typeof event.hash === 'string' && typeof event.network === 'string' && Array.isArray(event.logs);
}

Afterwards you can utilise this instead of this line as;

if (!isTransactionEvent(event)) {
    // As long as you make sure this part early exits, for the rest of the function typescript will know that event
    // is a TransactionEvent after this code block.
    throw new Error("Unexpect event received");
}

Originally posted by @tukantje in #182 (comment)