随机性的来源
随机性是一个很难的问题。计算机运行的代码是由程序员编写的,并遵循一个特定的步骤序列。因此,要设计一个能给你一个 "随机 "数字的算法是非常困难的,因为这个随机数字必须来自一个遵循一定步骤序列的算法。现在,当然,有些函数比其他函数更好。
在这种情况下,我们将具体看看为什么你不能相信链上数据作为随机性的来源(也是我们在 Junior 中使用的 Chainlink VRF 的原因)。
要求
- 我们将建立一个游戏,其中有一包牌。
- 每张牌都有一个与之相关的数字,范围从 0 到 2²⁵⁶-1。
- 玩家将猜测一个将被选中的数字。
- 然后庄家会随机从牌包中抽出一张牌。
- 如果有人猜对了数字,他们将赢得 0.1 ETH。
- 我们今天将破解这个游戏 :)
构建
为了构建智能合约,我们将使用 Hardhat。Hardhat 是一个 Ethereum 开发环境和框架,为 Solidity 的全栈开发而设计。简单地说,你可以编写你的智能合约,部署它们,运行测试,并调试你的代码。
创建项目
npm init --yes
npm install --save-dev hardhat
npx hardhat
选择创建一个基本样本项目 对已经指定的 Hardhat 项目根按回车键 在是否要添加.gitignore 的问题上按回车键 在 "是否要用 npm 安装这个样本项目的依赖项(@nomiclabs/hardhat-waffle ethereum-waffle chai @nomiclabs/hardhat-ethers ethers)? 现在你已经有了一个 Hardhat 项目,可以开始使用了!