当前位置: 首页 > 工具软件 > chainlink > 使用案例 >

chainlink 预言机的使用

周玺
2023-12-01

获取 价格

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;

import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";

contract PriceConsumerV3 {

    AggregatorV3Interface internal priceFeed;

    /**
     * Network: Goerli
     * Aggregator: ETH/USD
     * Address: 0xD4a33860578De61DBAbDc8BFdb98FD742fA7028e
     */
    constructor() {
        priceFeed = AggregatorV3Interface(0x779877A7B0D9E8603169DdbD7836e478b4624789);
    }

    /**
     * Returns the latest price
     */
    function getLatestPrice() public view returns (int) {
        (
            /*uint80 roundID*/,
            int price,
            /*uint startedAt*/,
            /*uint timeStamp*/,
            /*uint80 answeredInRound*/
        ) = priceFeed.latestRoundData();
        return price;
    }
}

1 link -0x326C977E6efc84E512bB9C30f76E30c160eD06FB
水龙头-https://faucets.chain.link/
2 构造函数初始化AggregatorV3Interface 对象:参数-地址 -你需要对应数据的地址。
3 返回一个数组
/*uint80 roundID*/, int price, /*uint startedAt*/, /*uint timeStamp*/, /*uint80 answeredInRound*/ ) = priceFeed.latestRoundData()

获取随机数

1 订阅地址:https://xie.infoq.cn/link?target=https%3A%2F%2Fvrf.chain.link%2Fgoerli
– 获取did
文档地址https://xie.infoq.cn/link?target=https%3A%2F%2Fdocs.chain.link%2Fdocs%2Fvrf%2Fv2%2Fsubscription%2Fsupported-networks%2F

2 部署合约,通过 订阅 ID 初始化(构造函数完成)VRF 的接口
3 将合约地址通过网页指定调用随机数的合约
4 编写合约注意:
1 override fulfillRandomWords函数,接受随机数
2 请求函数 参数 随机数个数,gaslimit , 交易确认数,gas费

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.8.7;

import "@chainlink/contracts/src/v0.8/interfaces/VRFCoordinatorV2Interface.sol";
import "@chainlink/contracts/src/v0.8/VRFConsumerBaseV2.sol";

contract ChainLinkVRFDemo is VRFConsumerBaseV2{
    VRFCoordinatorV2Interface VRFInterface;
    uint64 subId;//订阅号
    address owner;
    address vrfCoordinatorAddr=0x2Ca8E0C643bDe4C2E08ab1fA0da3401AdAD7734D;
    //选择不同的 gwei  可以快和慢,低一点慢 高一点快
    bytes32 keyHash=0x79d3d8832d904592c0bf9818b621522c988bb8b0c05cdc3b15aea1b6e8db0c15;
    //认为多少个交易以后交易就成功了,一般是12
    uint16 requestConfirmations=3;
    //gas limit上限
    uint32 callbackGasLimit=100000;
    //请求多少个随机数,上限是500
    uint32 numWords=3;
    //存储随机数
    uint256[] public s_randomWords;
    //第几次请求的数据
    uint256 public requestID;
    
    constructor(uint64 _subId)VRFConsumerBaseV2(vrfCoordinatorAddr){
        VRFInterface=VRFCoordinatorV2Interface(vrfCoordinatorAddr);
        subId=_subId;
    }

    //接收方法
    function fulfillRandomWords(uint256 requestID,uint256[] memory randomWords) internal override{
        s_randomWords=randomWords;
    }
  
    function requestRandomWords() external{
        require(msg.sender==owner);
        requestID=VRFInterface.requestRandomWords(
            keyHash,
            subId,
            requestConfirmations,
            callbackGasLimit,
            numWords
        );
    }
}

 类似资料: