通过地址生成随机数(VRF)

Generate a random number by address (VRF)

我想知道是否可以为每个地址生成一个唯一的数字,我尝试映射但它不起作用

contract RandomNumberConsumer is VRFConsumerBase {

bytes32 internal keyHash;
uint256 internal fee;
uint256 public randomResult;


mapping(address => uint) public random;


constructor() 
    VRFConsumerBase(
        0x8C7382F9D8f56b33781fE506E897a4F1e2d17255, // VRF Coordinator
        0x326C977E6efc84E512bB9C30f76E30c160eD06FB  // LINK Token
    )
{
    keyHash = 0x6e75b569a01ef56d18cab6a8e71e6600d6ce853834d4a5748b720d06f878b3a4;
    fee = 0.0001 * 10 ** 18; // 0.0001 LINK (Varies by network)
}

function getRandomNumber() public returns (bytes32 requestId) {
    require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
    return requestRandomness(keyHash, fee);
}

function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
    randomResult = randomness;
    random[msg.sender] = randomness;
}

}

这是映射

mapping(address => uint) public random;
random[msg.sender] = randomness;

谢谢!

你已经接近目前所拥有的。我对合同做了一些更新,并在下面添加了注释。主要变化是用于存储请求 ID -> 地址的新映射。这让 fulfillRandomness 函数更新正确的地址 -> randomNumber 映射。

pragma solidity  ^0.8.0;
import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol";

contract RandomNumberConsumer is VRFConsumerBase {

    bytes32 internal keyHash;
    uint256 internal fee;
    uint256 public randomResult;

    // ** New mapping to store requests
    mapping(bytes32 => address) public requestIdToAddress;
    mapping(address => uint) public random;


    constructor() 
        VRFConsumerBase(
            0x8C7382F9D8f56b33781fE506E897a4F1e2d17255, // VRF Coordinator
            0x326C977E6efc84E512bB9C30f76E30c160eD06FB  // LINK Token
        )
    {
        keyHash = 0x6e75b569a01ef56d18cab6a8e71e6600d6ce853834d4a5748b720d06f878b3a4;
        fee = 0.0001 * 10 ** 18; // 0.0001 LINK (Varies by network)
    }

    function getRandomNumber() public {
        require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
        // ** Store the random request in requestID
        bytes32 requestId = requestRandomness(keyHash, fee);
        // ** Map requestId to the sender's address
        requestIdToAddress[requestId] = msg.sender;
    }

    function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
        // ** Find the sender address based on the request
        address _sender = requestIdToAddress[requestId];
        // ** Update sender's mapping for randomness
        random[_sender] = randomness;
    }
}