[Chainlink] 如何在Polygon上获取随机数

AI数据  收藏
0 / 409

[Chainlink] How To Get A Random Number On Polygon

Breaking News

By Chainlink News 03/30/21 5:49 PM

How to Get a Random Number on Polygon

Polygon (formerly known as Matic Network) is a protocol and a framework for building and connecting Ethereum-compatible blockchain networks. Initially focusing on Ethereum scaling solutions that utilize Proof of Stake (PoS) sidechains and a Plasma framework, in rebranding to Polygon, they’ve also added other major scaling solutions such as zk-Rollups and Optimistic Rollups, as well as inter-chain communication protocols.
Polygon (以前称为Matic Network)是用于建立和连接以太坊兼容区块链网络的协议和框架。 最初侧重于利用权益证明(PoS)侧链和等离子框架的以太坊扩展解决方案,在更名为Polygon之后,他们还添加了其他主要的扩展解决方案,例如zk-Rollups和Optimistic Rollups,以及链间通信协议。

As the most widely adopted decentralized oracle network, Chainlink is the preferred oracle network within Polygon for securely obtaining external data and using tamper-proof data feeds. Recently, Chainlink VRF went live on Polygon mainnet, offering developers the ability to request verifiably random numbers in their smart contracts. In this technical tutorial, we’ll show you how to deploy a smart contract to Polygon and obtain a provably random number using Chainlink VRF.

多边形(以前称为Matic Network)是用于建立和连接以太坊兼容区块链网络的协议和框架。 最初侧重于利用权益证明(PoS)侧链和等离子框架的以太坊扩展解决方案,在更名为Polygon之后,他们还添加了其他主要的扩展解决方案,例如zk-Rollups和Optimistic Rollups,以及链间通信协议。作为最广泛采用的分散式Oracle网络,Chainlink是Polygon中首选的Oracle网络,用于安全地获取外部数据并使用防篡改数据源。 最近,Chainlink VRF在Polygon主网上上线,为开发人员提供了在其智能合约中请求可验证的随机数的功能。 在本技术教程中,我们将向您展示如何将智能合约部署到Polygon并使用Chainlink VRF获得可证明的随机数。

The Need for Verifiable Randomness 为什么需要可以验证的随机性

Chainlink VRF is a provably fair and verifiable source of randomness designed for smart contracts. Solidity developers can use it as a tamper-proof random number generator to build safe and reliable smart contracts for Ethereum applications that rely on unpredictable outcomes. Critically, Chainlink VRF not only provides random numbers, but also cryptographic proof that the number has not been tampered with to generate certain predictable outcomes.

Chainlink VRF是为智能合约设计的可证明公平且可验证的随机性来源。Solidity 开发人员可以将其用作防篡改随机数生成器,为依赖不可预测结果的以太坊应用程序构建安全可靠的智能合约。至关重要的是,Chainlink VRF 不仅提供随机数,而且还提供加密证明该数字未被篡改以产生某些可预测的结果。

Having verifiably random numbers in smart contracts enables developers to build for a wide array of use cases, such as randomness in gaming, random rewards in NFTs, lotteries, and Fair Participant or Random Node Selection.

在智能合约中具有可验证的随机数使开发人员能够构建广泛的用例,例如游戏中的随机性、NFT 中的随机奖励、彩票以及公平参与者或随机节点选择

One noteworthy real-world example is the NFT gaming dApp Aavegotchi, which integrated Chainlink VRF as its source of provably fair randomness to help determine an Aavegotchi’s unique characteristics, generate unpredictable game scenarios, and randomly select DAO jurors. Aavegotchi has launched on Polygon’s layer 2 PoS chain, allowing them to cost-effectively scale to meet user demand thanks to near zero transaction fees and fast settlement times.

一个值得注意的现实例子是NFT游戏 dApp ​​Aavegotchi,它集成了Chainlink VRF作为可证明公平随机性的来源,以帮助确定 Aavegotchi 的独特特征,生成不可预测的游戏场景,并随机选择 DAO 陪审员。Aavegotchi 已在 Polygon 的第 2 层 PoS 链上推出,由于接近零的交易费用和快速的结算时间,使他们能够经济高效地扩展以满足用户需求。

Now that we understand the use cases that benefit from verifiable randomness, we’ll walk through how to obtain a verifiable random number on a smart contract on the Polygon Mumbai Testnet.

现在我们了解了受益于可验证随机性的用例,我们将介绍如何在 Polygon Mumbai 测试网上的智能合约上获取可验证的随机数。

Connecting to Polygon Mumbai Testnet 连接Mumbai 测试网

The first step in using Chainlink VRF on Polygon’s PoS chain is to set up your MetaMask wallet to connect to the Matic Mumbai Testnet. You can do this by selecting ‘Networks’, then choosing ‘Custom RPC’ and entering the following details:

在Polygon的PoS链上使用Chainlink VRF的第一步是设置您的MetaMask钱包,以连接到Matic Mumbai Testnet。 您可以通过选择“网络”,然后选择“自定义RPC”并输入以下详细信息来执行此操作:

How to Get a Random Number on Polygon
Entering the Mumbai Testnet details

MATIC is the native token of the Polygon network and is needed to interact with the network, similar to how ETH is used as gas for Ethereum. To obtain Mumbai Testnet MATIC, head over to the MATIC Faucet, select the MATIC token and the Mumbai Testnet network, enter in your MetaMask Wallet address and press Submit.

MATIC是Polygon网络的原生令牌,与网络交互需要它,类似于ETH 被用作以太坊气体的方式。 要获取孟买Testnet MATIC,请转到MATIC龙头,选择MATIC令牌和Mumbai Testnet网络,输入您的MetaMask电子钱包地址,然后按Submit。

Similar to the MATIC token, the LINK token is required as payment to the VRF coordinator for fulfilling a random number request. To obtain testnet LINK, simply choose the LINK token in the faucet instead of the MATIC token.

与MATIC令牌类似,需要LINK令牌作为向VRF协调器支付的费用,以实现随机数请求。 要获得testnet LINK,只需在水龙头中选择LINK令牌而不是MATIC令牌。

How to Get a Random Number on Polygon

image.png

Obtaining Mumbai Testnet MATIC and LINK

While the process for using the faucet to obtain LINK on the Mumbai Testnet is relatively simple, it’s a little more involved when moving to Polygon’s Mainnet. This is because the LINK provided by the Polygon Bridge is not ERC-677 compatible, so it cannot be used with Chainlink oracles. However, it can be converted to the official LINK token on Polygon using Chainlink’s PegSwap service, essentially creating a wrapped version of the LINK token.

虽然使用水龙头在Mumbai Testnet上获取LINK的过程相对简单,但在移至Polygon的Mainnet时涉及的过程要多一些。 这是因为Polygon Bridge提供的LINK与ERC-677不兼容,因此不能与Chainlink oracles一起使用。 但是,可以使用Chainlink的PegSwap服务将其转换为Polygon上的官方LINK令牌,实质上是创建LINK令牌的包装版本。

https://faucet.polygon.technology/

Building the Smart Contract 建立智能合约

The easiest way to start building a smart contract that uses Chainlink VRF on Polygon is to begin with the standard Chainlink VRFConsumer contract. This is a basic standardized contract for initiating requests for a random number via a Chainlink oracle. So we will open this contract in Remix via the link above and modify it accordingly.

开始在Polygon上使用Chainlink VRF建立智能合约的最简单方法是从标准Chainlink VRFConsumer合约开始。 这是用于通过Chainlink oracle发起对随机数的请求的基本标准化合同。 因此,我们将通过上面的链接在Remix中打开此合同,并进行相应的修改。

  • The VRF Coordinator for Mumbai Testnet is 0x8C7382F9D8f56b33781fE506E897a4F1e2d17255
  • The address of the LINK token on the Mumbai Testnet is 0x326C977E6efc84E512bB9C30f76E30c160eD06FB
  • The KeyHash for Mumbai Testnet is 0x6e75b569a01ef56d18cab6a8e71e6600d6ce853834d4a5748b720d06f878b3a4
  • The fee for making a VRF request on the Mumbai Testnet is 100000000000000 (0.0001 LINK)
  • Mumbai测试网的VRF协调器为0x8C7382F9D8f56b33781fE506E897a4F1e2d17255
  • Mumbai测试网上的LINK令牌地址为0x326C977E6efc84E512bB9C30f76E30c160eD06FB
  • Mumbai测试网的KeyHash为0x6e75b569a01ef56d18cab6a8e71e6600d6ce853834d4a5748b720d06f878b3a4
  • 在Mumbai测试网上提出VRF请求的费用为100000000000000(0.0001 LINK)
constructor() 
        VRFConsumerBase(
            0x8C7382F9D8f56b33781fE506E897a4F1e2d17255
            0x326C977E6efc84E512bB9C30f76E30c160eD06FB
        ) public
    {
        keyHash = 0x6e75b569a01ef56d18cab6a8e71e6600d6ce853834d4a5748b720d06f878b3a4;
        fee = 100000000000000; // 0.0001 LINK
    }

Now our contract is ready to be compiled and deployed to the Mumbai Testnet.
现在,我们的合同已准备好进行编译,并部署到MumbaiTestnet。

Deploying and Testing the Smart Contract 部署和测试智能合约

Compile the contract in Remix, then on the deployment tab, change the environment to “Injected Web3”, and ensure the wallet address below is the one in your MetaMask wallet that contains your MATIC and LINK tokens, press the deploy button, and follow the steps. The end result is you have your smart contract deployed to the Mumbai Testnet. You should take note of the deployed contract address via the transaction output in the Remix console.

在Remix中编译合同,然后在“部署”选项卡上,将环境更改为“ Injected Web3”,并确保下面的钱包地址是您的MetaMask钱包中包含MATIC和LINK令牌的钱包地址,按部署按钮,然后按照脚步。 最终结果是您将智能合约部署到了孟买Testnet。 您应该通过Remix控制台中的事务输出记录已部署的合同地址。

The next step is to fund the contract with LINK so it can send requests to the VRF Coordinator. To do this, simply take the deployed contract address from the step above, and then send it at least 0.0001 LINK from your MetaMask wallet.

下一步是使用LINK为合同提供资金,以便它可以将请求发送到VRF协调器。 为此,只需从上述步骤中获取已部署的合同地址,然后从您的MetaMask钱包中至少发送0.0001 LINK。

How to Get a Random Number on Polygon

Funding the contract with LINK

Once the contract is deployed and funded with LINK, we can request a random number by executing the getRandomNumber function, passing in a given seed as the parameter. This will send the request along with the seed to the VRF coordinator. Remember it’s extremely important to choose a seed that is difficult to influence or predict.

Entering a seed and sending a request to the VRF CoordinatorOnce this transaction has been processed, we then wait a few seconds for the Chainlink oracle to fulfill the request for a random number, and then call the fulfillRandomness function we created earlier to return the random number back to our consumer contract.

处理完该交易后,我们将等待几秒钟,让Chainlink oracle完成对随机数的请求,然后调用我们之前创建的fulfillRandomness函数,将随机数返回给我们的消费者合同。

We then call the randomResult getter function to see the result of the verifiable random number that was generated by the Chainlink oracle with the given seed. We now successfully have a random number in our smart contract deployed to the Polygon Mumbai Testnet that was verifiably created using the given seed.

然后,我们调用randomResult getter函数,以查看由Chainlink oracle使用给定种子生成的可验证随机数的结果。 现在,我们已经成功地将智能合约中的随机数部署到了Polygon Mumbai Testnet中,该随机数是使用给定种子进行验证创建的。

How to Get a Random Number on Polygon
Viewing the returned random number

Summary

Poygon’s PoS Chain offers a viable layer 2 solution with its fast, cheap, and reliable transactions, and with the addition of Chainlink VRF, developers can now build various scalable dApps that make use of verifiable random numbers.

Poygon的PoS Chain通过其快速,廉价和可靠的交易提供了可行的第2层解决方案,并且通过添加Chainlink VRF,开发人员现在可以利用可验证的随机数构建各种可扩展的dApp。

If you’re a smart contract developer and want to take advantage of the Chainlink VRF feature, visit the Chainlink developer documentation and join the technical discussion on Discord.

如果您是精明的合同开发人员,并且想利用Chainlink VRF功能,请访问Chainlink开发人员文档,并加入有关Discord的技术讨论。

EXPLORE CHAINLINK DOCS
JOIN THE CHAINLINK DISCORD

More on This Topic

https://azcoinnews.com/chainlink-how-to-get-a-random-number-on-polygon.html


在Ropsten上产生随机数

随机数和区块链一直存在分歧。到目前为止,区块链上还没有可验证的随机函数。

问题源于以下事实:交易被挖掘时,需要由网络上的多个节点来确认。这意味着每个节点都必须得出相同的共识。因此如果函数确实是随机的,则每个节点将得出不同的共识,从而导致未能确认的事务。

chainlink介绍

区块链和智能合约非常适合根据一组不可变的规则执行计算。问题在于规则只能应用于系统内部的数据。从系统外部获取可验证的数据非常困难。

Chainlink的任务是通过提供分散的预言来解决此问题,使区块链能够访问其生态系统之外的数据。预言机实质上是区块链和外部世界之间的桥梁。

在最近的一篇文章中,Chainlink宣布发布了其新的可验证随机函数(VRF)。开发人员现在可以使用该功能将其集成到多个测试网上的DApp中,从而使智能合约能够检索可在链上验证的随机数。这意味着不再有漏洞,并保证了随机性。

那么该功能如何实现的?

如果您想在Javascript中生成一个随机数,代码非常简单:

Math.random();

在一行的单次执行中,检索一个随机数。这不是VRF的工作原理。与Javascript不同,VRF处理一些事务。

以下是事件的顺序:

  1. 您的智能合约通过交易向VRF请求一个随机数。
  2. VRF会生成该数字并进行验证。
  3. VRF准备响应。
  4. VRF通过另一笔交易将号码发送回您的智能合约。

为了使第4点成功,您的合同需要实现一个已知函数,以便VRF可以返回结果验证。但是如何在您的项目中实现呢?

如何实现随机性

让我们创建一个名为RandomGenerator的新智能合约,在这里我们将调用VRF并接收结果。

步骤1:创建消费者合约

我们将使用Chainlink提供的名为VRFConsumerBase的合约,这是一个抽象合约,它定义了消耗VRF所需的最少函数。让我们这样定义“ RandomGenerator.sol”文件的开头:

pragma solidity ^0.6.2;
import "https://raw.githubusercontent.com/smartcontractkit/
chainlink/develop/evm-contracts/src/v0.6/VRFConsumerBase.sol";
contract RandomGenerator is VRFConsumerBase {
constructor(address _vrfCoordinator, address _link)
VRFConsumerBase(_vrfCoordinator, _link) public {
}
}

VRFConsumerBase仍在后期测试中,因此软件包尚为对外提供。这就是为什么我们使用Github的HTTP URL进行导入的原因。

基本合约采用两个参数,分别代表协调器(coordinator)和LINK ERC20令牌的地址。这些是每个网络上的固定地址(稍后会详细介绍)。

步骤2:重写函数

VRFConsumerBase附带了两个对VRF流程至关重要的函数。

第一个叫做requestRandomness,它已经实现了,我们不需要重写。这是对VRF进行初始调用的函数。

另一个叫做fulfillRandomness,这是VRF在生成数字时调用的函数。我们可以重写它,以便在调用随机数时对其执行操作。

我们的智能合约只是将生成的随机数存储在一个名为randomNumber的状态变量中,以便我们可以在完成时查询它。它看起来应该像这样:

pragma solidity ^0.6.2;
import "https://raw.githubusercontent.com/smartcontractkit/
chainlink/develop/evm-contracts/src/v0.6/VRFConsumerBase.sol";
contract RandomGenerator is VRFConsumerBase {
bytes32 public reqId;
uint256 public randomNumber;
constructor(address _vrfCoordinator, address _link)
VRFConsumerBase(_vrfCoordinator, _link) public {
}
function fulfillRandomness(bytes32 requestId, uint256 randomness) external override {
reqId = requestId;
randomNumber = randomness;
}
}

我们为fulfillRandomness函数添加了重写功能,并将状态变量reqId和randomNumber设置为等于该函数接收的值。

步骤3:生成随机数

正如我在步骤1前面提到的,函数调用需要传递一些地址和其他值作为参数。

部署智能合约并调用构造函数时,它需要VRF协调器(coordinator)地址和网络上LINK令牌的地址。在Ropsten测试网上:

· VRF coordinator: 0xf720CF1B963e0e7bE9F58fd471EFa67e7bF00cfb
· LINK address: 0x20fE562d797A42Dcb3399062AE9546cd06f63280

调用requestRandomness函数时,我们需要传递生成随机性的Key hash,生成随机数的fee(使用LINK令牌)和针对生成随机性的seed(这是我们提供的最后一个)。函数签名如下所示:

function requestRandomness(bytes32 _keyHash, uint256 _fee, uint256 _seed) public returns (bytes32 requestId)

在Ropsten上,参数值为:

· Key hash: 0xced103054e349b8dfb51352f0f8fa9b5d20dde3d06f9f43cb2b85bc64b238205
· Fee (1 LINK): 1000000000000000000
· Seed: [whatever_you_want_your_seed_to_be]

因此我们的调用代码将如下所示:

// set ropsten key hash
bytes32 keyHash = "0xced103054e349b8dfb51352f0f8fa9b5d20dde3d06f9f43cb2b85bc64b238205";
// set ropsten LINK fee
fee = 1000000000000000000;
// set example seed
seed = 123456789;
// make call to request randomness
bytes32 reqId = rand.requestRandomness(keyHash, fee, seed);

当结果返回时,该值将存在并且可以通过调用以下方法进行检索:

rand.randomNumber;

本节将逐步介绍如何使用Remix IDE和Metamask从VRF获取随机数。在继续之前,请确保已在浏览器上安装了Metamask扩展。

· 前往Remix IDE。
· 如果您以前从未使用过Remix,请确保使用的是Solidity,如图3所示。

创建一个名为RandomGenerator的新文件,并粘贴图2中的代码。

使用左侧菜单,单击Solidity图标,然后选择0.6.2编译器版本,如图4所示。

然后单击下面的按钮,并在下拉列表中选择“Injected web3”,如图5所示。

这将提示您应接受的来自Metamask的连接请求。

确保您正在使用Metamask上的Ropsten测试网,如图6所示。

确保您的Metamask帐户中有一些Ropsten Ether。

回到Remix,在同一选项卡上,您应该看到橙色的“ Deploy”按钮,单击该按钮并接受来自Metamask的合约部署请求。

部署后,我们需要确保智能合约具有LINK令牌,以便它可以请求随机数。在Ropsten LINK龙头上,然后粘贴您的Metamask地址,以便您在Metamask中收到100 LINK。

Metamask不知道LINK令牌在Ropsten上的位置,因此我们需要添加它。在“ Metamask”中,在您的帐户名称左侧,单击burger符号,然后单击底部的“Add Token”。

在“Custom Token”下,添加地址:0x20fE562d797A42Dcb3399062AE9546cd06f63280。其余详细信息应自动填写。提交后,如果您要求LINK到正确的地址,那么您的帐户中应该会看到100 LINK。图7显示了一个具有70 LINK的帐户。

返回到Remix,单击图8中带圆圈的按钮,复制已部署合约的地址。

现在我们将向合约发送一些LINK。回到Metamask,然后单击100 LINK旁边的3个点。粘贴合约地址并发送10 LINK。确认交易后,请继续下一步。

在Remix中,我们现在可以请求随机性。在同一选项卡中,向下滚动您会发现更多代表公共功能的橙色按钮,如图9所示。单击requestRandomness右侧的箭头以展开参数。

按顺序将这些值粘贴到三个输入框中:0xced103054e349b8dfb51352f0f8fa9b5d20dde3d06f9f43cb2b85bc64b238205、10000000000000000000000、123456789(或您希望的seed是什么)。然后点击“Transact”!

这可能需要一些时间,因此您应该关注输出终端提供给您的Etherscan中的事务。

交易完成后,我们需要等待VRF生成随机数并将其发送回我们的合约。几分钟后,单击我们在Remix中发送交易的橙色按钮下方的蓝色“ randomNumber”按钮,检查您的合约是否收到了随机数,如图12所示。

如果一切顺利,您应该有一个像我这样的随机数,它是30207470459964961279215818016791723193587102244018403859363363849439350753829。

结 论

Chainlink证明,现在智能合约中可以使用可验证的随机数。我们已经解释了该机制的工作原理,如何将代码集成到智能合约中以及如何使用Remix IDE检索随机数的演示。