Rand - Get random number on the chain

Warning

Lity supports built-in random function after lity v1.2.7.

Built-in Random Function

Lity provides a new built-in function rand for the gaming Dapp developers.

The function prototype is function rand() returns (uint). When calling rand(), developers will receive an random number which is generated by the following formula:

function rand() returns (uint) {
  return keccak256(Randomness Seed, Nonce, CodeHash, Counter);
}
  • The Randomness Seed is generated by Travis chain and you can find it in the difficulty field of current block header. This depends on current block. It will be the same until receiving the next block.
  • The Nonce is nonce of the transaction origin and depends on the transaction order in current block.
  • The CodeHash is the hash of caller’s contract bytecode.
  • The Counter will automaticlly increase after the opRand is called. This depends on the the called time of rand(). If you call rand() twice in same code block, you will receive different results.

Warning

You should NOT call rand() in a view or pure function. If the random number does not need to be recorded on the blockchain (i.e., outside of a transaction in a view function executed on a single node), it does not need to be generated by the blockchain. The calling application should simply generate a random number locally – it is much cheaper in terms of resource consumption.

Example 1

The example below shows how to generate a random numbers.

pragma lity ^1.2.7;

contract RandNumberExample {
  uint randnum;
  function getAndSetRandnum() public returns (uint) {
    randnum = rand();
    return randnum;
  }
}

Example 2

The example below shows how to generate a series of random numbers between 0 and 99. You can invoke createRand() multiple times within a block (i.e., wthin 10s) or across multiple blocks to see the results.

pragma lity >=1.2.7;

contract RandDemo {
  uint[] s;

  function createRand () public {
    s.push(rand() % 100);
  }

  function last5Rands () public view returns (uint, uint, uint, uint, uint) {
    require (s.length >= 5);
    return (s[s.length-1], s[s.length-2], s[s.length-3], s[s.length-4], s[s.length-5]);
  }
}