Skip to content

Commit a9bf6df

Browse files
feat(RNG): randomizer
1 parent 2721df3 commit a9bf6df

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed

contracts/src/rng/IRandomizer.sol

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
// Randomizer protocol interface
2+
interface IRandomizer {
3+
function request(uint256 callbackGasLimit) external returns (uint256);
4+
5+
function clientWithdrawTo(address _to, uint256 _amount) external;
6+
}
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
// SPDX-License-Identifier: MIT
2+
3+
pragma solidity ^0.8;
4+
5+
import "./RNG.sol";
6+
import "./IRandomizer.sol";
7+
8+
/**
9+
* @title Random Number Generator that uses Randomizer.ai
10+
* https://randomizer.ai/
11+
*/
12+
contract RandomizerRNG is RNG {
13+
uint256 public constant CALLBACK_GAS_LIMIT = 50000;
14+
// TODO: should the owner be KlerosLiquid by default?
15+
address public owner = msg.sender; // The address that can withdraw funds.
16+
17+
IRandomizer public randomizer; // Randomizer address.
18+
mapping(uint128 => uint256) public randomNumbers; // randomNumbers[requestID] is the random number for this request id, 0 otherwise.
19+
mapping(address => uint128) public requesterToID; // Maps the requester to his latest request ID.
20+
21+
/** @dev Constructor.
22+
* @param _randomizer Randomizer contract.
23+
*/
24+
constructor(IRandomizer _randomizer) {
25+
randomizer = _randomizer;
26+
}
27+
28+
/**
29+
* @dev Request a random number. The id of the request is tied to the sender.
30+
*/
31+
function requestRandomness(uint256 /*_block*/) external override {
32+
uint128 id = uint128(randomizer.request(CALLBACK_GAS_LIMIT));
33+
requesterToID[msg.sender] = id;
34+
}
35+
36+
/**
37+
* @dev Return the random number.
38+
* @return randomNumber The random number or 0 if it is not ready or has not been requested.
39+
*/
40+
function receiveRandomness(uint256 /*_block*/) external view override returns (uint256 randomNumber) {
41+
// Get the latest request ID for this requester.
42+
uint128 id = requesterToID[msg.sender];
43+
randomNumber = randomNumbers[id];
44+
}
45+
46+
/**
47+
* @dev Callback function called by the randomizer contract when the random value is generated.
48+
*/
49+
function randomizerCallback(uint128 _id, bytes32 _value) external {
50+
require(msg.sender == address(randomizer), "Caller not Randomizer");
51+
randomNumbers[_id] = uint256(_value);
52+
}
53+
54+
/**
55+
* @dev Allows the owner to withdraw randomizer funds.
56+
* @param _amount Amount to withdraw in wei.
57+
*/
58+
function randomizerWithdraw(uint256 _amount) external {
59+
require(msg.sender == owner, "Only owner allowed");
60+
randomizer.clientWithdrawTo(msg.sender, _amount);
61+
}
62+
}

0 commit comments

Comments
 (0)