Skip to main content

Overview

The FHE library provides cryptographically secure random number generation that produces encrypted random values. The values are generated in encrypted form—no one can see the plaintext until it is explicitly decrypted.

Random Functions

FunctionReturn Type
FHE.randomEuint8()euint8
FHE.randomEuint16()euint16
FHE.randomEuint32()euint32
FHE.randomEuint64()euint64
FHE.randomEuint128()euint128

Usage

import { FHE, euint8, euint32, ebool } from "@fhenixprotocol/cofhe-contracts/FHE.sol";

contract RandomExample {
    euint32 private storedRandom;

    // Basic random generation
    function generateRandom() public {
        euint32 random = FHE.randomEuint32();
        FHE.allowThis(random);
        storedRandom = random;
    }

    // Random in range [0, 99]
    function randomInRange() public returns (euint32) {
        euint32 random = FHE.randomEuint32();
        euint32 result = FHE.rem(random, FHE.asEuint32(100));
        FHE.allowThis(result);
        return result;
    }

    // Efficient random boolean (coin flip)
    function randomBool() public returns (ebool) {
        euint8 random = FHE.randomEuint8();

        // AND with 1 forces the value into {0,1}, ensuring a uniform 50/50 distribution.
        ebool result = FHE.asEbool(FHE.and(random, FHE.asEuint8(1)));
        FHE.allowThis(result);
        return result;
    }
}
Call FHE.allowThis() on random values if you need to store or use them later in your contract.