0

I am writing smart contract and stucked on this line :

int p = 0;
p = (rand() % 997);

This is giving error

error: use of undeclared identifier 'rand'

I do search and got some reference links but not getting expected answers. Some old answers reference links are also not valid now. Can somebody please help to generate random numbers in a smart contract?

2
  • you can't do that, for smart contract can't support random method
    – Jimmy Guo
    Commented Dec 14, 2020 at 6:04
  • Okay, I want to implement the Shamir Secret Sharing Algorithm in a smart contract, I was needed random numbers for this. Can you suggest some alternative for this?
    – Varsh
    Commented Dec 14, 2020 at 6:07

1 Answer 1

0

Not safe solution for safe random number oracle rng should be used.

Table

   struct [[eosio::table]] seed{
      uint64_t key = 1;
      uint32_t value = 1;
      auto primary_key() const { return key; }
   };
   typedef eosio::multi_index<"seed"_n, seed> seed_table;

Action in .ccp

int contractclass::random(const int range)
{
   auto _s = seed_table(_self, get_self().value);
   // Find the existing seed
   auto seed_iterator = _s.begin();

   // Initialize the seed with default value if it is not found
   if (seed_iterator == _s.end())
   {
      seed_iterator = _s.emplace(_self, [&](auto &seed) {});
   }
   auto new_seed_value = (seed_iterator->value + current_time_point().elapsed.count()) % current_time_point().elapsed.count();

   // Store the updated seed value in the table
   _s.modify(seed_iterator, _self, [&](auto &s)
             { s.value = new_seed_value; });
   int random_result = new_seed_value % range;
   return random_result;
}

Usage

int rng = random(100);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.