Skip to content

Commit

Permalink
Merge pull request #20 from ltfschoen/chainlink
Browse files Browse the repository at this point in the history
Chainlink
  • Loading branch information
ltfschoen authored Jun 27, 2023
2 parents 6d85e28 + dd0d6ab commit f1d3067
Show file tree
Hide file tree
Showing 13 changed files with 636 additions and 25 deletions.
3 changes: 3 additions & 0 deletions dapps/evm2/flipper/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,6 @@ MOONBASE_PRIVATE_KEY='0x'
MOONSCAN_API_KEY=''
# https://blastapi.io/
MOONBASE_BLASTAPI_ENDPOINT=''
# obtain from https://dashboard.alchemy.com/ under Ethereum > Ethereum Sepolia
CHAINLINK_SEPOLIA_ENDPOINT='https://rpc.sepolia.org'
ALCHEMY_API_KEY=''
54 changes: 52 additions & 2 deletions dapps/evm2/flipper/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,13 +110,63 @@ shasum -a 256 moonkey
* Compile full `truffle compile --compile-all`
* Migrate
* Migrate full `truffle migrate --reset --compile-all --network moonbase`
* Migrate full `truffle migrate --reset --compile-all --network sepolia`
* Test
* `truffle test --verbose-rpc --network moonbase`
* **Important:** It is necessary to first comment-out the code that is **not being compiled** in 2_deploy_contracts.j
* `truffle test ./test/test_Flipper.js --verbose-rpc --network moonbase`
* `truffle test ./test/test_ChainlinkVRF.js --network sepolia`
* Verify Contract - Moonbase Precompile

```
# truffle run verify Flipper --network moonbase
Verifying contracts on moonscan
Verifying Flipper
Pass - Verified: https://moonbase.moonscan.io/address/0x1c440D264DcCBe9b7AC84edCEC99De926Db98753#code
Successfully verified 1 contract(s).
Verifying contracts on sourcify
Failed to connect to Sourcify API at url https://sourcify.dev/server/chains
root@ink:/app/dapps/evm2/flipper# truffle run verify RandomNumber --network moonbase
Verifying contracts on moonscan
Verifying RandomNumber
Pass - Verified: https://moonbase.moonscan.io/address/0x4027755C05514421fe00f4Fde0bD3F8475ce8A6b#code
Successfully verified 1 contract(s).
Verifying contracts on sourcify
Failed to connect to Sourcify API at url https://sourcify.dev/server/chains
```

* Verify Contract - Chainlink VRF
```
# truffle run verify VRFD20 --network sepolia
Verifying contracts on etherscan
No etherscan or sepolia_etherscan API Key provided
Verifying contracts on sourcify
Verifying VRFD20
Pass - Verified: https://sourcify.dev/#/lookup/0xe22cdfA9d8C8e942B498696ef54584426d2f5Dd6
Successfully verified 1 contract(s).
```

* Chainlink VRF https://docs.chain.link/getting-started/intermediates-tutorial
* View token balance https://sepolia.etherscan.io/address/0x1dd907abb024e17d196de0d7fe8eb507b6ccaae7
* Create and fund a subscription https://docs.chain.link/vrf/v2/subscription/examples/get-a-random-number/#create-and-fund-a-subscription
* Prepay Subscription https://vrf.chain.link/

* Run
* node ./scripts/demo.js

* Chainlink VRF https://docs.chain.link/getting-started/intermediates-tutorial
* View token balance https://sepolia.etherscan.io/address/0x1dd907abb024e17d196de0d7fe8eb507b6ccaae7
* Create and fund a subscription https://docs.chain.link/vrf/v2/subscription/examples/get-a-random-number/#create-and-fund-a-subscription
* Prepay Subscription https://vrf.chain.link/
* Receipt https://sepolia.etherscan.io/tx/0xcc2cd9edf90e0f3351f3398b7013a7259c0acc7cfbfc38454192324fcfdb7d6a
* Reference v2 contract (not implemented): https://remix.ethereum.org/#url=https://docs.chain.link/samples/VRF/VRFv2Consumer.sol&lang=en&optimize=false&runs=200&evmVersion=null&version=soljson-v0.8.18+commit.87f61d96.js

* Troubleshooting
* `Client network socket disconnected before secure TLS connection was established`
* Try fixing by running `unset https_proxy && unset http_proxy`, but this didn't actually work for me
* If you get error `PollingBlockTracker` then try connecting to a different ISP and disable VPN and stop using a proxy and restart access to your internet
* Sometimes when you run `truffle test --network moonbase` after changing some CLI options it outputs `Error: The network id specified in the truffle config (1287) does not match the one returned by the network (4619453). Ensure that both the network and the provider are properly configured`, even though the network id in the truffle-config.js is in fact 1287, but when you run it again it might works. So just keep running the command again until it
* Sometimes when you run `truffle test --network moonbase` after changing some CLI options it outputs `Error: The network id specified in the truffle config (1287) does not match the one returned by the network (4619453). Ensure that both the network and the provider are properly configured`, even though the network id in the truffle-config.js is in fact 1287 (for some reason it confuses the block number for the network id), but when you run it again it might works. So just keep running the command again until it. Or run `truffle test --network sepolia` instead of
`truffle test --verbose-rpc --network sepolia`
works or change internet connection.
* References
* https://github.com/trufflesuite/truffle/blob/develop/packages/contract/README.md
Expand Down
44 changes: 42 additions & 2 deletions dapps/evm2/flipper/contracts/lib/RandomNumber.sol
Original file line number Diff line number Diff line change
Expand Up @@ -25,21 +25,38 @@ contract RandomNumber is RandomnessConsumer {
uint32 public VRF_BLOCKS_DELAY;
bytes32 public SALT_PREFIX = "change-me-to-anything";

uint256 private constant ROLL_IN_PROGRESS = 42;

// Storage variables for the current request
uint256 public requestId;
uint256[] public random;

// address public s_owner;

// map rollers to requestIds
mapping(uint256 => address) private s_rollers;
// map vrf results to rollers
mapping(address => uint256) private s_results;

event DiceRolled(uint256 indexed requestId, address indexed roller);
event DiceLanded(uint256 indexed requestId, uint256 indexed result);

constructor() payable RandomnessConsumer() {
// Initialize use of Randomness dependency before trying to access it
theRandomness = Randomness(randomnessPrecompileAddress);
requiredDeposit = theRandomness.requiredDeposit();
// Because this contract can only perform 1 random request at a time,
// We only need to have 1 required deposit.
require(msg.value >= requiredDeposit);
// s_owner = msg.sender;
VRF_BLOCKS_DELAY = MIN_VRF_BLOCKS_DELAY;
}

function requestRandomness() public payable {
function requestRandomness(
address roller
) public payable {
// ) public onlyOwner payable {
require(s_results[roller] == 0, "Already rolled");
// Make sure that the value sent is enough
require(msg.value >= MIN_FEE);
// Request local VRF randomness
Expand All @@ -51,6 +68,10 @@ contract RandomNumber is RandomnessConsumer {
1, // Number of random words
VRF_BLOCKS_DELAY // Delay before request can be fulfilled
);

s_rollers[requestId] = roller;
s_results[roller] = ROLL_IN_PROGRESS;
emit DiceRolled(requestId, roller);
}

function getRequestStatus() public view returns(Randomness.RequestStatus) {
Expand All @@ -63,10 +84,29 @@ contract RandomNumber is RandomnessConsumer {
}

function fulfillRandomWords(
uint256, /* requestId */
uint256 reqId, /* requestId */
uint256[] memory randomWords
) internal override {
// Save the randomness results
uint256 d20Value = (randomWords[0] % 20) + 1;
s_results[s_rollers[reqId]] = d20Value;
// Save the latest for comparison
random = randomWords;
}

/**
* @notice Get the value rolled by a player once the address has rolled
* @param player address
* @return id as a string
*/
function getRolledValueForPlayer(address player) public view returns (uint256) {
require(s_results[player] != 0, "Dice not rolled");
require(s_results[player] != ROLL_IN_PROGRESS, "Roll in progress");
return s_results[player];
}

// modifier onlyOwner() {
// require(msg.sender == s_owner);
// _;
// }
}
143 changes: 143 additions & 0 deletions dapps/evm2/flipper/contracts/lib/VRFD20.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;

// Reference: https://remix.ethereum.org/#url=https://docs.chain.link/samples/VRF/VRFD20.sol&lang=en&optimize=false&runs=200&evmVersion=null&version=soljson-v0.8.18+commit.87f61d96.js
import "../vrf/interfaces/VRFCoordinatorV2Interface.sol";
import "../vrf/VRFConsumerBaseV2.sol";

/**
* @notice A Chainlink VRF consumer which uses randomness to mimic the rolling
* of a 20 sided dice
*/

/**
* Request testnet LINK and ETH here: https://faucets.chain.link/
* Find information on LINK Token Contracts and get the latest ETH and LINK faucets here: https://docs.chain.link/docs/link-token-contracts/
*/

/**
* THIS IS AN EXAMPLE CONTRACT THAT USES HARDCODED VALUES FOR CLARITY.
* THIS IS AN EXAMPLE CONTRACT THAT USES UN-AUDITED CODE.
* DO NOT USE THIS CODE IN PRODUCTION.
*/

contract VRFD20 is VRFConsumerBaseV2 {
uint256 private constant ROLL_IN_PROGRESS = 42;

VRFCoordinatorV2Interface COORDINATOR;

// Your subscription ID.
uint64 public s_subscriptionId;

// Sepolia coordinator. For other networks,
// see https://docs.chain.link/docs/vrf-contracts/#configurations
address vrfCoordinator = 0x8103B0A8A00be2DDC778e6e7eaa21791Cd364625;

// The gas lane to use, which specifies the maximum gas price to bump to.
// For a list of available gas lanes on each network,
// see https://docs.chain.link/docs/vrf-contracts/#configurations
bytes32 s_keyHash =
0x474e34a077df58807dbe9c96d3c009b23b3c6d0cce433e59bbf5b34f823bc56c;

// Depends on the number of requested values that you want sent to the
// fulfillRandomWords() function. Storing each word costs about 20,000 gas,
// so 40,000 is a safe default for this example contract. Test and adjust
// this limit based on the network that you select, the size of the request,
// and the processing of the callback request in the fulfillRandomWords()
// function.
uint32 callbackGasLimit = 40000;

// The default is 3, but you can set this higher.
uint16 requestConfirmations = 3;

// For this example, retrieve 1 random value in one request.
// Cannot exceed VRFCoordinatorV2.MAX_NUM_WORDS.
uint32 numWords = 1;
address public s_owner;

// map rollers to requestIds
mapping(uint256 => address) private s_rollers;
// map vrf results to rollers
mapping(address => uint256) private s_results;

event DiceRolled(uint256 indexed requestId, address indexed roller);
event DiceLanded(uint256 indexed requestId, uint256 indexed result);

/**
* @notice Constructor inherits VRFConsumerBaseV2
*
* @dev NETWORK: Sepolia
*
* @param subscriptionId subscription id that this consumer contract can use
*/
constructor(uint64 subscriptionId) payable VRFConsumerBaseV2(vrfCoordinator) {
COORDINATOR = VRFCoordinatorV2Interface(vrfCoordinator);
// require(msg.value > 0);
s_owner = msg.sender;
s_subscriptionId = subscriptionId;
}

/**
* @notice Requests randomness
* @dev Warning: if the VRF response is delayed, avoid calling requestRandomness repeatedly
* as that would give miners/VRF operators latitude about which VRF response arrives first.
* @dev You must review your implementation details with extreme care.
*
* @param roller address of the roller
*/
function rollDice(
address roller
) public onlyOwner returns (uint256 requestId) {
require(s_results[roller] == 0, "Already rolled");
// Will revert if subscription is not set and funded.
requestId = COORDINATOR.requestRandomWords(
s_keyHash,
s_subscriptionId,
requestConfirmations,
callbackGasLimit,
numWords
);

s_rollers[requestId] = roller;
s_results[roller] = ROLL_IN_PROGRESS;
emit DiceRolled(requestId, roller);
}

/**
* @notice Callback function used by VRF Coordinator to return the random number to this contract.
*
* @dev Some action on the contract state should be taken here, like storing the result.
* @dev WARNING: take care to avoid having multiple VRF requests in flight if their order of arrival would result
* in contract states with different outcomes. Otherwise miners or the VRF operator would could take advantage
* by controlling the order.
* @dev The VRF Coordinator will only send this function verified responses, and the parent VRFConsumerBaseV2
* contract ensures that this method only receives randomness from the designated VRFCoordinator.
*
* @param requestId uint256
* @param randomWords uint256[] The random result returned by the oracle.
*/
function fulfillRandomWords(
uint256 requestId,
uint256[] memory randomWords
) internal override {
uint256 d20Value = (randomWords[0] % 20) + 1;
s_results[s_rollers[requestId]] = d20Value;
emit DiceLanded(requestId, d20Value);
}

/**
* @notice Get the value rolled by a player once the address has rolled
* @param player address
* @return id as a string
*/
function getRolledValueForPlayer(address player) public view returns (uint256) {
require(s_results[player] != 0, "Dice not rolled");
require(s_results[player] != ROLL_IN_PROGRESS, "Roll in progress");
return s_results[player];
}

modifier onlyOwner() {
require(msg.sender == s_owner);
_;
}
}
Loading

0 comments on commit f1d3067

Please sign in to comment.