You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
## Randomness Tradeoffs in Blockchain Applications
10
-
11
10
Randomness is a critical component in blockchain applications, enabling fair and unpredictable outcomes for use cases like gaming, lotteries, and cryptographic protocols. The most basic approach to generating a random number on EVM chains is to utilize block hashes, which combines the block hash with a user-provided seed and hashes them together. The resulting hash can be used as a pseudo-random number. However, this approach has limitations:
12
11
13
-
1.**Predictability**: Miners can potentially manipulate the block hash to influence the generated random number.
14
-
2.**Replay attacks**: In case of block reorganizations, the revealed answers will not be re-used again.
15
-
16
-
[Chainlink VRF](https://docs.chain.link/vrf) is a popular tool that improves on this by providing another approach for generating provably random values on Ethereum and other blockchains by relying on a decentralized oracle network to deliver cryptographically secure randomness from off-chain sources. However, this dependence on external oracles introduces several weaknesses, such as cost, latency, and scalability concerns.
12
+
1. Predictability: Miners can potentially manipulate the block hash to influence the generated random number.
13
+
2. Replay attacks: In case of block reorganizations, the revealed answers will not be re-used again.
17
14
18
-
In contrast, Flow offers a simpler and more integrated approach with its **Random Beacon contract**, which provides native on-chain randomness at the protocol level, eliminating reliance on external oracles and sidestepping their associated risks. Via a commit-and-reveal scheme, Flow's protocol-native secure randomness can be used within both Cadence and Solidity smart contracts.
15
+
[Chainlink VRF][chainlink-vrf] is a popular tool that improves on this by providing another approach for generating provably random values on Ethereum and other blockchains by relying on a decentralized oracle network to deliver cryptographically secure randomness from off-chain sources. However, this dependence on external oracles introduces several weaknesses, such as cost, latency, and scalability concerns.
19
16
17
+
In contrast, Flow offers a simpler and more integrated approach with its Random Beacon contract, which provides native on-chain randomness at the protocol level, eliminating reliance on external oracles and sidestepping their associated risks. Via a commit-and-reveal scheme, Flow's protocol-native secure randomness can be used within both Cadence and Solidity smart contracts.
20
18
21
19
## Objectives
22
20
23
-
In this guide, we will explore how to use a commit-reveal scheme in conjunction with Flow’s Random Beacon to achieve secure, non-revertible randomness. This mechanism mitigates post-selection attacks, where participants attempt to manipulate or reject unfavorable random outcomes after they are revealed.
21
+
By the end of this guide, you will be able to:
24
22
25
-
To illustrate this concept, we will build a Coin Toss game on Flow, demonstrating how smart contracts can leverage commit-reveal randomness for fair, tamper-resistant results.
23
+
- Deploy a Cadence smart contract on the Flow blockchain
24
+
- Implement commit-reveal randomness to ensure fairness
25
+
- Interact with Flow’s on-chain randomness features
26
+
- Build and test the Coin Toss game using Flow’s Testnet
26
27
27
-
### **What is the Coin Toss Game?**
28
-
The **Coin Toss Game** is a decentralized betting game that showcases Flow’s **commit-reveal randomness**. Players place bets without knowing the random outcome, ensuring fairness and resistance to manipulation.
28
+
## Prerequisites
29
29
30
-
The game consists of two distinct phases:
30
+
You’ll need the following:
31
31
32
-
1.**Commit Phase** – The player places a bet by sending Flow tokens to the contract. The contract records the commitment and requests a **random value** from Flow’s **Random Beacon**. The player receives a **Receipt**, which they will use to reveal the result later.
33
-
34
-
2.**Reveal Phase** – Once the **random value** becomes available in `RandomBeaconHistory`, the player submits their **Receipt** to determine the outcome:
35
-
- If the result is **0**, the player **wins** and receives **double their bet**.
36
-
- If the result is **1**, the player **loses**, and their bet remains in the contract.
32
+
- Flow Testnet Account: An account on the Flow Testnet with test FLOW tokens for deploying contracts and executing transactions (e.g., via [Flow Faucet][flow-faucet]).
33
+
- Flow CLI or Playground: The Flow CLI or Flow Playground for deploying and testing contracts (install via [Flow Docs][flow-docs]).
37
34
38
-
### **Why Use Commit-Reveal Randomness?**
39
-
-**Prevents manipulation** – Players cannot selectively reveal results after seeing the randomness.
-**Reduces reliance on external oracles** – The randomness is generated **natively on-chain**, avoiding additional complexity, third party risk and cost.
35
+
## Overview
42
36
43
-
### **What You Will Learn**
44
-
By the end of this guide, you will be able to:
37
+
In this guide, we will explore how to use a commit-reveal scheme in conjunction with Flow’s Random Beacon to achieve secure, non-revertible randomness. This mechanism mitigates post-selection attacks, where participants attempt to manipulate or reject unfavorable random outcomes after they are revealed.
45
38
46
-
- Deploy a Cadence smart contract** on the Flow blockchain
47
-
- Implement commit-reveal randomness** to ensure fairness
48
-
- Interact with Flow’s on-chain randomness features**
49
-
- Build and test the Coin Toss game using Flow’s Testnet
39
+
To illustrate this concept, we will build a Coin Toss game on Flow, demonstrating how smart contracts can leverage commit-reveal randomness for fair, tamper-resistant results.
50
40
51
-
## Prerequisites
41
+
### What is the Coin Toss Game?
42
+
The Coin Toss Game is a decentralized betting game that showcases Flow’s commit-reveal randomness. Players place bets without knowing the random outcome, ensuring fairness and resistance to manipulation.
52
43
53
-
You’ll need the following:
44
+
The game consists of two distinct phases:
54
45
55
-
-**Flow Testnet Account**: An account on the Flow Testnet with test FLOW tokens for deploying contracts and executing transactions (e.g., via [Flow Faucet](https://testnet-faucet.onflow.org/)).
56
-
-**Flow CLI or Playground**: The Flow CLI or Flow Playground for deploying and testing contracts (install via [Flow Docs](https://docs.onflow.org/flow-cli/install/)).
46
+
1. Commit Phase – The player places a bet by sending Flow tokens to the contract. The contract records the commitment and requests a random value from Flow’s Random Beacon. The player receives a Receipt, which they will use to reveal the result later.
47
+
48
+
2. Reveal Phase – Once the random value becomes available in `RandomBeaconHistory`, the player submits their Receipt to determine the outcome:
49
+
- If the result is 0, the player wins and receives double their bet.
50
+
- If the result is 1, the player loses, and their bet remains in the contract.
57
51
52
+
### Why Use Commit-Reveal Randomness?
53
+
- Prevents manipulation – Players cannot selectively reveal results after seeing the randomness.
- Reduces reliance on external oracles – The randomness is generated natively on-chain, avoiding additional complexity, third party risk and cost.
58
56
59
57
## Building the Coin Toss Contract
60
58
61
-
In this section, we’ll walk through constructing the `CoinToss.cdc` contract, which contains the core logic for the Coin Toss game. To function properly, the contract relies on **supporting contracts and a proper deployment setup**.
59
+
In this section, we’ll walk through constructing the `CoinToss.cdc` contract, which contains the core logic for the Coin Toss game. To function properly, the contract relies on supporting contracts and a proper deployment setup.
62
60
63
-
This tutorial will focus specifically on writing and understanding the `CoinToss.cdc` contract, while additional setup details can be found in the [original GitHub repo](https://github.com/onflow/random-coin-toss).
61
+
This tutorial will focus specifically on writing and understanding the `CoinToss.cdc` contract, while additional setup details can be found in the [original GitHub repo][github-repo].
64
62
65
63
66
64
### Step 1: Defining the `CoinToss.cdc` Contract
@@ -109,7 +107,7 @@ access(all) fun flipCoin(bet: @{FungibleToken.Vault}): @Receipt {
109
107
110
108
### Step 3: Implementing the Reveal Phase With `revealCoin`
111
109
112
-
Now we implement the reveal phase with the `revealCoin` function. Here the caller provides the Receipt given to them at commitment. The contract then "flips a coin" with `_randomCoin()` providing the Receipt's contained Request. If result is **1**, user loses, but if it's **0** the user doubles their bet. Note that the caller could condition the revealing transaction, but they've already provided their bet amount so there's **no loss** for the contract if they do.
110
+
Now we implement the reveal phase with the `revealCoin` function. Here the caller provides the Receipt given to them at commitment. The contract then "flips a coin" with `_randomCoin()` providing the Receipt's contained Request. If result is 1, user loses, but if it's 0 the user doubles their bet. Note that the caller could condition the revealing transaction, but they've already provided their bet amount so there's no loss for the contract if they do.
113
111
114
112
```cadence
115
113
access(all) fun revealCoin(receipt: @Receipt): @{FungibleToken.Vault} {
@@ -137,23 +135,18 @@ access(all) fun revealCoin(receipt: @Receipt): @{FungibleToken.Vault} {
137
135
}
138
136
```
139
137
140
-
The final version of `CoinToss.cdc` should look like this: [https://github.com/onflow/random-coin-toss/blob/main/contracts/CoinToss.cdc](https://github.com/onflow/random-coin-toss/blob/main/contracts/CoinToss.cdc).
141
-
142
-
143
-
<!-- 1. **[Xorshift128plus](https://github.com/onflow/random-coin-toss/blob/main/contracts/Xorshift128plus.cdc)**: A base contract that implements the Xorshift128+ pseudo-random number generator (PRG) algorithm.
144
-
2. **[RandomBeaconHistory](https://contractbrowser.com/A.e467b9dd11fa00df.RandomBeaconHistory)**: A base contract that stores the history of random sources generated by the Flow network. The defined `Heartbeat` resource is updated by the Flow Service Account at the end of every block with that block's source of randomness.
145
-
3. **[CadenceRandomConsumer](https://github.com/onflow/random-coin-toss/blob/main/contracts/RandomConsumer.cdc)**: A base contract for secure consumption of Flow's protocol-native randomness via the `RandomBeaconHistory` contract. Implementing contracts benefit from the commit-reveal scheme, ensuring that callers cannot revert on undesirable random results. -->
138
+
The final version of `CoinToss.cdc` should look like [this contract code][coin-toss-contract-code].
146
139
147
140
## Testing CoinToss on Flow Testnet
148
141
149
-
To make things easy, we’ve already deployed the `CoinToss.cdx` contract for you at this address: [0xb6c99d7ff216a684](https://contractbrowser.com/A.b6c99d7ff216a684.CoinToss). We’ll walk through placing a bet and revealing the result using [run.dnz](https://run.dnz.dev/), a Flow-friendly tool similar to Ethereum’s Remix.
142
+
To make things easy, we’ve already deployed the `CoinToss.cdx` contract for you at this address: [0xb6c99d7ff216a684][coin-toss-contract]. We’ll walk through placing a bet and revealing the result using [run.dnz][run-dnz], a Flow-friendly tool similar to Ethereum’s Remix.
150
143
151
144
### Placing a Bet with flipCoin
152
145
153
146
First, you’ll submit a bet to the CoinToss contract by withdrawing Flow tokens and storing a receipt. Here’s how to get started:
154
147
155
-
1.**Open Your Dev Environment:** Head to [run.dnz](https://run.dnz.dev/).
156
-
2.**Enter the Transaction Code:** Paste the following Cadence code into the editor:
148
+
1. Open Your Dev Environment: Head to [run.dnz][run-dnz].
149
+
2. Enter the Transaction Code: Paste the following Cadence code into the editor:
3.**Set Your Bet:** A modal will pop up asking for the betAmount. Enter a value (e.g., 1.0 for 1 Flow token) and submit
187
-
4.**Execute the Transaction:** Click "Run," and a WalletConnect window will appear. Choose Blocto, sign in with your email, and hit "Approve" to send the transaction to Testnet.
179
+
3. Set Your Bet: A modal will pop up asking for the betAmount. Enter a value (e.g., 1.0 for 1 Flow token) and submit
180
+
4. Execute the Transaction: Click "Run," and a WalletConnect window will appear. Choose Blocto, sign in with your email, and hit "Approve" to send the transaction to Testnet.
188
181
189
182

190
183
191
-
5.**Track it:** You can take the transaction id to [FlowDiver](https://testnet.flowdiver.io/)[.io](https://testnet.flowdiver.io/tx/9c4f5436535d36a82d4ae35467b37fea8971fa0ab2409dd0d5f861f61e463d98) to have a full view of everything that's going on with this `FlipCoin` transaction.
184
+
5. Track it: You can take the transaction id to [FlowDiver][flow-diver][.io](https://testnet.flowdiver.io/tx/9c4f5436535d36a82d4ae35467b37fea8971fa0ab2409dd0d5f861f61e463d98) to have a full view of everything that's going on with this `FlipCoin` transaction.
192
185
193
186
194
187
195
188
### Revealing the Coin Toss Result
196
189
197
190
Let's reveal the outcome of your coin toss to see if you’ve won. This step uses the receipt from your bet, so ensure you’re using the same account that placed the bet. Here’s how to do it:
198
191
199
-
1.**Return to your Dev Environment:** Open [run.dnz](https://run.dnz.dev/) again.
200
-
2.**Enter the Reveal Code:** Paste the following Cadence transaction into the editor:
192
+
1. Return to your Dev Environment: Open [run.dnz][run-dnz] again.
193
+
2. Enter the Reveal Code: Paste the following Cadence transaction into the editor:
201
194
202
195
```cadence
203
196
import FlowToken from 0x7e60df042a9c0868
@@ -227,7 +220,7 @@ transaction {
227
220
```
228
221
After running this transaction, we reveal the result of the coin flip and it's 1! Meaning we have won nothing this time, but keep trying!
229
222
230
-
You can find the full transaction used for this example, with its result and events, at [FlowDiver.io/tx/](https://testnet.flowdiver.io/tx/a79fb2f947e7803eefe54e48398f6983db4e0d4d5e217d2ba94f8ebdec132957).
223
+
You can find the full transaction used for this example, with its result and events, at [FlowDiver.io/tx/][flow-diver-tx].
231
224
232
225
233
226
## Conclusion
@@ -238,6 +231,23 @@ The commit-reveal scheme, implemented within the context of Flow's Random Beacon
238
231
- Resistant to manipulation: Protects against post-selection attacks.
239
232
- Immune to replay attacks: A common pitfall in traditional random number generation on other blockchains.
240
233
241
-
The example of the CoinToss game illustrates the practical implementation of these concepts, demonstrating how simple yet effective this approach can be. As blockchain technology continues to evolve, adopting such best practices is crucial for fostering a secure and trustworthy ecosystem. This encourages developers to innovate while adhering to the core principles of decentralization and fairness.
234
+
The CoinToss game serves as a practical example of these principles in action. By walking through its implementation, you’ve seen firsthand how straightforward yet effective this approach can be—balancing simplicity for developers with robust security for users. As blockchain technology advances, embracing such best practices is essential to creating a decentralized ecosystem that upholds fairness and integrity, empowering developers to innovate with confidence.
235
+
236
+
This tutorial has equipped you with hands-on experience and key skills:
237
+
238
+
- You deployed a Cadence smart contract on the Flow blockchain.
239
+
- You implemented commit-reveal randomness to ensure fairness.
240
+
- You interacted with Flow’s on-chain randomness features.
241
+
- You built and tested the Coin Toss game using Flow’s Testnet.
242
+
243
+
By harnessing Flow’s built-in capabilities, you can now focus on crafting engaging, user-centric experiences without grappling with the complexities or limitations of external systems. This knowledge empowers you to create secure, scalable, and fair decentralized applications.
242
244
243
-
By utilizing Flow’s native capabilities, developers can focus more on creating engaging user experiences without the complexities and limitations often tied to external oracles.
Copy file name to clipboardExpand all lines: docs/tutorials/deploy-solidity-contract.md
+5-2
Original file line number
Diff line number
Diff line change
@@ -219,9 +219,12 @@ The `awardItem` function is called with a test address and a string parameter. I
219
219
220
220
## Conclusion
221
221
222
-
Deploying a Solidity contract within a Cadence environment on the Flow blockchain is not only feasible but also presents an exciting opportunity for developers to harness the strengths of both programming languages. Throughout this guide, we have navigated the critical steps involved in the deployment process, from compiling the Solidity contract using Remix to executing transactions with Overflow and Cadence scripts.
222
+
Deploying a Solidity contract within a Cadence environment on the Flow blockchain is not only feasible but also presents an exciting opportunity for you to harness the strengths of both programming languages. Throughout this guide, you’ve navigated the critical steps involved in the deployment process, from compiling your Solidity contract using Remix to executing transactions with Overflow and Cadence scripts. By completing this guide, you’ve achieved the following:
223
223
224
-
As the blockchain landscape continues to evolve, the ability to bridge diverse smart contract languages and platforms will be essential for innovation and collaboration. We encourage you to explore further and experiment with the tools and methodologies presented in this guide, paving the way for new possibilities in decentralized application development.
224
+
- Deployed a Solidity contract on Flow EVM using Cadence: You compiled and deployed your Solidity contract to Flow’s EVM layer via a Cadence transaction.
225
+
- Called functions from Cadence: You used a Cadence script to mint an NFT by invoking the `awardItem` function on your deployed contract.
226
+
227
+
As blockchain technology continues to evolve, adopting these best practices is crucial for fostering a secure and trustworthy ecosystem. This empowers you to innovate while staying true to the core principles of decentralization and fairness.
0 commit comments