Discussions

Ask a Question
Back to All

is hook execution atomic from another?

Hi there,

I just have a question about the execution of the hook.

So the first question would be: can the same hook that belongs to the same hook account execute concurrently if it receives multiple transactions from different accounts within a short time period, or at least start at different times and end at different times, but still have an overlap of the time in which they are executed?

If the answer to the first question is no, you don't have to answer the next question because it is the premise of the next question. The next question goes like this:

Let's say you mutate a state by using state_set in your hook.

And you invoke the hook many times within a short period of time by sending several transactions to the hook for which it is installed to be invoked upon.

Then is the mutation of the state always atomic? For example:

#include "hookapi.h"

int64_t hook(uint32_t reserved) {
  uint8_t key[32] = {0};

  int64_t count[1];
  int64_t state_read_result = state(SBUF(count), key, 32);
  if (state_read_result == DOESNT_EXIST) {
    count[0] = 0;
    if (state_set(SBUF(count), key, 32) <= 0) {
      rollback(SBUF("failed to set count"), -2);
    }
  } else if (state_read_result <= 0) {
    rollback(SBUF("failed to read state"), -1);
  } else {
    count[0] += 1;
    if (state_set(SBUF(count), key, 32) <= 0) {
      rollback(SBUF("failed to set count"), -2);
    }
  }

  accept(SBUF(count), 1);
  _g(1,
     1); // every hook needs to import guard function and use it at least once
  // unreachable
  return 0;
}

And let's say 100 different accounts invoke the hook approximately within the same second, and the hook runs for those people approximately within the same time range. I am asking if it is possible that the count[0] is NOT 100 after all of successful 100 executions.

I was designing some vault stuff using state and came to a conclusion that state mutation has to be atomic in order for all the hooks to be secure. But I couldn't find that in any of the documents, so I just wanted to confirm.

KP