forked from AmazingAng/WTF-Solidity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRandomNumberConsumer.sol
63 lines (53 loc) · 2.28 KB
/
RandomNumberConsumer.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.21;
import "@chainlink/contracts/src/v0.8/interfaces/VRFCoordinatorV2Interface.sol";
import "@chainlink/contracts/src/v0.8/VRFConsumerBaseV2.sol";
contract RandomNumberConsumer is VRFConsumerBaseV2{
//请求随机数需要调用VRFCoordinatorV2Interface接口
VRFCoordinatorV2Interface COORDINATOR;
// 申请后的subId
uint64 subId;
//存放得到的 requestId 和 随机数
uint256 public requestId;
uint256[] public randomWords;
/**
* 使用chainlink VRF,构造函数需要继承 VRFConsumerBaseV2
* 不同链参数填的不一样
* 具体可以看:https://docs.chain.link/vrf/v2/subscription/supported-networks
* 网络: Sepolia测试网
* Chainlink VRF Coordinator 地址: 0x8103B0A8A00be2DDC778e6e7eaa21791Cd364625
* LINK 代币地址: 0x01BE23585060835E02B77ef475b0Cc51aA1e0709
* 30 gwei Key Hash: 0x474e34a077df58807dbe9c96d3c009b23b3c6d0cce433e59bbf5b34f823bc56c
* Minimum Confirmations 最小确认块数 : 3 (数字大安全性高,一般填12)
* callbackGasLimit gas限制 : 最大 2,500,000
* Maximum Random Values 一次可以得到的随机数个数 : 最大 500
*/
address vrfCoordinator = 0x8103B0A8A00be2DDC778e6e7eaa21791Cd364625;
bytes32 keyHash = 0x474e34a077df58807dbe9c96d3c009b23b3c6d0cce433e59bbf5b34f823bc56c;
uint16 requestConfirmations = 3;
uint32 callbackGasLimit = 200_000;
uint32 numWords = 3;
constructor(uint64 s_subId) VRFConsumerBaseV2(vrfCoordinator){
COORDINATOR = VRFCoordinatorV2Interface(vrfCoordinator);
subId = s_subId;
}
/**
* 向VRF合约申请随机数
*/
function requestRandomWords() external {
requestId = COORDINATOR.requestRandomWords(
keyHash,
subId,
requestConfirmations,
callbackGasLimit,
numWords
);
}
/**
* VRF合约的回调函数,验证随机数有效之后会自动被调用
* 消耗随机数的逻辑写在这里
*/
function fulfillRandomWords(uint256 requestId, uint256[] memory s_randomWords) internal override {
randomWords = s_randomWords;
}
}