@@ -4,7 +4,7 @@ pragma solidity ^0.8.24;
44import "./IRNG.sol " ;
55
66/// @title RNG with fallback mechanism
7- /// @notice Uses multiple RNG implementations with automatic fallback if default RNG does not respond passed a timeout.
7+ /// @notice Uses a primary RNG implementation with automatic fallback to a Blockhash RNG if the primary RNG does not respond passed a timeout.
88contract RNGWithFallback is IRNG {
99 // ************************************* //
1010 // * Storage * //
@@ -54,33 +54,6 @@ contract RNGWithFallback is IRNG {
5454 _;
5555 }
5656
57- // ************************************* //
58- // * State Modifiers * //
59- // ************************************* //
60-
61- /// @dev Request a random number from the RNG
62- function requestRandomness () external override onlyByConsumer {
63- requestTimestamp = block .timestamp ;
64- rng.requestRandomness ();
65- }
66-
67- /// @dev Receive the random number with fallback logic
68- /// @return randomNumber Random Number
69- function receiveRandomness () external override onlyByConsumer returns (uint256 randomNumber ) {
70- // Try to get random number from the RNG contract
71- randomNumber = rng.receiveRandomness ();
72-
73- // If we got a valid number, clear the request
74- if (randomNumber != 0 ) {
75- return randomNumber;
76- } else if (block .timestamp > requestTimestamp + fallbackTimeoutSeconds) {
77- // If the timeout is exceeded, try the fallback
78- randomNumber = uint256 (blockhash (block .number - 1 ));
79- emit RNGFallback ();
80- }
81- return randomNumber;
82- }
83-
8457 // ************************************* //
8558 // * Governance Functions * //
8659 // ************************************* //
@@ -103,4 +76,28 @@ contract RNGWithFallback is IRNG {
10376 fallbackTimeoutSeconds = _fallbackTimeoutSeconds;
10477 emit FallbackTimeoutChanged (_fallbackTimeoutSeconds);
10578 }
79+
80+ // ************************************* //
81+ // * State Modifiers * //
82+ // ************************************* //
83+
84+ /// @dev Request a random number from the primary RNG
85+ /// @dev The consumer is trusted not to make concurrent requests.
86+ function requestRandomness () external override onlyByConsumer {
87+ requestTimestamp = block .timestamp ;
88+ rng.requestRandomness ();
89+ }
90+
91+ /// @dev Receive the random number from the primary RNG with fallback to the blockhash RNG if the primary RNG does not respond passed a timeout.
92+ /// @return randomNumber Random number or 0 if not available
93+ function receiveRandomness () external override onlyByConsumer returns (uint256 randomNumber ) {
94+ randomNumber = rng.receiveRandomness ();
95+
96+ // If we didn't get a random number and the timeout is exceeded, try the fallback
97+ if (randomNumber == 0 && block .timestamp > requestTimestamp + fallbackTimeoutSeconds) {
98+ randomNumber = uint256 (blockhash (block .number - 1 ));
99+ emit RNGFallback ();
100+ }
101+ return randomNumber;
102+ }
106103}
0 commit comments