diff --git a/src/Random.sol b/src/Random.sol new file mode 100644 index 0000000..b668827 --- /dev/null +++ b/src/Random.sol @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.8; + +import "./suavelib/Suave.sol"; + +library Random { + function randomUint8() internal returns (uint8 value) { + bytes memory random = Suave.randomBytes(1); + assembly { + value := mload(add(random, 0x01)) + } + } + + function randomUint16() internal returns (uint16 value) { + bytes memory random = Suave.randomBytes(2); + assembly { + value := mload(add(random, 0x02)) + } + } + + function randomUint32() internal returns (uint32 value) { + bytes memory random = Suave.randomBytes(4); + assembly { + value := mload(add(random, 0x04)) + } + } + + function randomUint64() internal returns (uint64 value) { + bytes memory random = Suave.randomBytes(8); + assembly { + value := mload(add(random, 0x08)) + } + } + + function randomUint128() internal returns (uint128 value) { + bytes memory random = Suave.randomBytes(16); + assembly { + value := mload(add(random, 0x10)) + } + } + + function randomUint256() internal returns (uint256 value) { + bytes memory random = Suave.randomBytes(32); + assembly { + value := mload(add(random, 0x20)) + } + } +} diff --git a/test/Random.t.sol b/test/Random.t.sol new file mode 100644 index 0000000..df5652f --- /dev/null +++ b/test/Random.t.sol @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: Unlicense +pragma solidity ^0.8.0; + +import "forge-std/Test.sol"; +import {console2} from "forge-std/console2.sol"; +import "src/suavelib/Suave.sol"; +import "src/Random.sol"; +import "src/Test.sol"; + +contract TestRandom is Test, SuaveEnabled { + function testRandomBytes() public { + bytes memory random = Suave.randomBytes(32); + console2.logBytes(random); + assert(random.length == 32); + } + + function testRandomUint8() public { + uint8 random = Random.randomUint8(); + console2.log("random uint8: %d", random); + assert(random > 0); + } + + function testRandomUint16() public { + uint16 random = Random.randomUint16(); + console2.log("random uint16: %d", random); + assert(random > 0); + } + + function testRandomUint32() public { + uint32 random = Random.randomUint32(); + console2.log("random uint32: %d", random); + assert(random > 0); + } + + function testRandomUint64() public { + uint64 random = Random.randomUint64(); + console2.log("random uint64: %d", random); + assert(random > 0); + } + + function testRandomUint128() public { + uint128 random = Random.randomUint128(); + console2.log("random uint128: %d", random); + assert(random > 0); + } + + function testRandomUint256() public { + uint256 random = Random.randomUint256(); + console2.log("random uint256: %d", random); + assert(random > 0); + } +}