Skip to content

Commit

Permalink
feat: add pseudo random example
Browse files Browse the repository at this point in the history
  • Loading branch information
cehali committed Feb 28, 2023
1 parent 1c545a5 commit 84452af
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 0 deletions.
46 changes: 46 additions & 0 deletions contracts/ExamplePseudoRandom.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.2;

import "@redstone-finance/evm-connector/contracts/data-services/MainDemoConsumerBase.sol";

contract ExamplePseudoRandom is MainDemoConsumerBase {
uint256[] generatedNFTIndexes;

function getPseudoRandomness() private view returns(uint256) {
bytes32 dataFeedId = bytes32("ENTROPY");
uint256 randomValue = getOracleNumericValueFromTxMsg(dataFeedId);

return uint256(
keccak256(
abi.encodePacked(
randomValue,
block.timestamp,
blockhash(block.number - 1),
blockhash(block.number)
)
)
);
}

// Generates a random number from 1 to maxValue
function generateRandomNumber(uint256 maxValue) public view returns(uint256) {
uint256 randomness = getPseudoRandomness();
return (randomness % maxValue) + 1;
}

// Firstly it generates a single random number (e.g. number of NFTs in a box)
// Then it generates the specified number of random numbers
function generateManyRandomNumbers(uint256 maxRandomNumbersCount, uint256 maxValue) public {
uint256 randomness = getPseudoRandomness();
uint256 randomNumbersCount = generateRandomNumber(maxRandomNumbersCount);
generatedNFTIndexes = new uint256[](randomNumbersCount);
for (uint256 i = 0; i < randomNumbersCount; i++) {
generatedNFTIndexes[i] = uint256(keccak256(abi.encode(randomness, i))) % maxValue + 1;
}
}

function getGeneratedNFTIndexes() public view returns(uint256[] memory) {
return generatedNFTIndexes;
}
}
26 changes: 26 additions & 0 deletions test/ExamplePseudoRandom.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
const { WrapperBuilder } = require("@redstone-finance/evm-connector");

describe("ExamplePseudoRandom", function () {
let contract;

beforeEach(async () => {
// Deploy contract
const ExamplePseudoRandom = await ethers.getContractFactory("ExamplePseudoRandom");
contract = await ExamplePseudoRandom.deploy();
});

it("Build random NFT indexes", async function () {
// Wrapping the contract
const wrappedContract = WrapperBuilder.wrap(contract).usingDataService({
dataServiceId: "redstone-main-demo",
uniqueSignersCount: 1,
dataFeeds: ["ENTROPY"],
}, ["https://d33trozg86ya9x.cloudfront.net"]);

// Interact with the contract (getting oracle value securely)
const generateManyRandomNumbersTx = await wrappedContract.generateManyRandomNumbers(10, 10);
await generateManyRandomNumbersTx.wait();
const generatedNFTIndexes = await wrappedContract.getGeneratedNFTIndexes();
console.log({ generatedNFTIndexes });
});
});

0 comments on commit 84452af

Please sign in to comment.