How to Ensure Provably Fair Randomness in On-Chain Roulette?
Developing a provably fair on-chain roulette game requires a Solidity smart contract with Chainlink VRF for randomness, and a React frontend for an engaging user experience. This covers everything from smart contract development to deployment on Ethereum and L2 networks like Polygon and Arbitrum.
Achieving randomness without predictability in a roulette smart contract is a complex challenge. Simple approaches using block.timestamp or block.prevrandao are vulnerable to miner/validator exploitation, where a node can decide whether to include a transaction based on the block outcome. This is known as an MEV attack on randomness. Our solution relies on verifiable randomness—either via Chainlink VRF or a commit-reveal scheme. The former offers full decentralization at a higher cost, while the latter is faster but requires a trusted server. For projects requiring high security, we always recommend Chainlink VRF as it is 100x more secure than alternative methods.
Overall Architecture
Over five years and 20+ launched projects (including gaming platforms with 50,000+ monthly active users), we've refined a modular architecture that separates concerns: smart contract logic, randomness oracle, and frontend animation. The choice of L1/L2 chain depends on your target audience and budget. Below is a table comparing common bet types and their payouts.
| Bet Type |
Payout Ratio |
Example |
House Edge |
| Straight Up (single number) |
35:1 |
Bet $10 on 7 → win $350 |
2.7% (European) |
| Split (two numbers) |
17:1 |
Bet $10 on 16-17 → win $170 |
2.7% |
| Street (three numbers) |
11:1 |
Bet $10 on 1-3 → win $110 |
2.7% |
| Corner (four numbers) |
8:1 |
Bet $10 on 25-28 → win $80 |
2.7% |
| Red/Black |
1:1 |
Bet $10 on red → win $10 |
2.7% |
What's Included in Our Development Package?
- Smart contract development in Solidity with gas optimizations (up to 40% reduction in transaction costs compared to standard implementations)
- Chainlink VRF integration (v2.5) with subscription management
- React frontend with animated wheel spin (Three.js) and real-time balance updates
- Deployment on Ethereum, Polygon, Arbitrum, Base, or Avalanche
- Smart contract audit using Slither and Mythril
- Documentation and 3-month warranty for any contract issues
- Training session (2 hours) for your team
Why Choose Us?
| Metric |
Value |
| Years in blockchain development |
5+ |
| Launched projects |
25+ |
| Smart contracts audited |
50+ |
| Clients satisfied |
98% retention rate |
Chainlink VRF Integration
Cryptographically secure and verifiable random numbers are provided by a decentralized oracle network using Chainlink VRF. Neither the casino operator nor the player can influence the outcome, and the proof is verified on-chain. The following Solidity contract snippet demonstrates the spin function. Note the use of requestRandomWords for transparent randomness.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { VRFConsumerBaseV2Plus } from "@chainlink/contracts/src/v0.8/vrf/VRFConsumerBaseV2Plus.sol";
import { ConfirmedOwner } from "@chainlink/contracts/src/v0.8/shared/access/ConfirmedOwner.sol";
contract Roulette is VRFConsumerBaseV2Plus, ConfirmedOwner {
uint256 private s_subscriptionId;
bytes32 private s_keyHash;
uint32 private s_callbackGasLimit = 500000;
uint16 private s_requestConfirmations = 3;
uint32 private s_numWords = 1;
constructor(uint256 subscriptionId, bytes32 keyHash) VRFConsumerBaseV2Plus(0xYourCoordinator) ConfirmedOwner(msg.sender) {
s_subscriptionId = subscriptionId;
s_keyHash = keyHash;
}
function spin(uint256 betAmount, uint8 betType, uint256[] calldata numbers) external onlyOwner {
// Validate bet and deduct balance
// Request randomness
uint256 requestId = s_vrfCoordinator.requestRandomWords(
s_keyHash,
s_subscriptionId,
s_requestConfirmations,
s_callbackGasLimit,
s_numWords
);
// Store request with bet details
}
function fulfillRandomWords(uint256 requestId, uint256[] calldata randomWords) internal override {
uint256 result = randomWords[0] % 37; // 0-36 for European roulette
// Determine outcome based on betType and numbers
// Distribute winnings
}
}
The full contract includes bet validation, payout calculation, and owner management. Gas optimization techniques like packing and using uint256 for state variables reduce average transaction cost by 30%.
Additional Considerations
- Gas optimization: We apply batching and packing techniques to reduce transaction costs. For example, storing bet type and numbers in a single
uint256 saves 15% gas.
- Player experience: The React frontend features animated wheel spins (using Three.js) and real-time balance updates via WebSocket.
- Compliance: For jurisdictions requiring KYC, we integrate with identity providers (e.g., Civic, Onfido).
How to Integrate Chainlink VRF in 5 Steps
- Create a VRF subscription on Chainlink and fund it with LINK.
- Deploy your Roulette contract inheriting VRFConsumerBaseV2Plus.
- Add the contract as a consumer in the VRF subscription.
- Implement the spin function to request randomness and store bet details.
- Handle the fulfillment in fulfillRandomWords to determine the outcome and pay out.
Commercial Comparison: VRF vs Blockhash
| Method |
Security Level |
Cost per Request |
Decentralization |
| Blockhash (block.difficulty) |
Low (MEV attacks) |
Free |
None |
| Commit-Reveal |
Medium (server trust) |
Low gas |
Partial |
| Chainlink VRF |
High (cryptographic) |
0.01-0.1 LINK |
Full |
In summary, building a provably fair blockchain roulette requires careful selection of randomness source, thorough testing, and a responsive UI. Our methodology has been validated across networks with over 100,000 spins processed without incident. If you're looking for a turnkey solution, our package delivers a complete, audited game in 4-6 weeks.
Game Economy, Contracts, and On-Chain Mechanics
We’ve seen this scenario multiple times. Axie Infinity generated substantial revenue monthly at its peak, but within 18 months the token crashed by 98% and the audience by 95%. The cause—lack of sinks: players earned SLP and cashed out, while burn mechanisms were insufficient. An analysis of Axie’s economy (Collins Dictionary) confirmed the model turned into a Ponzi scheme. We provide end-to-end GameFi development: from tokenomics to smart contracts, so your economy doesn’t repeat this mistake. Let’s evaluate your project at a meetup or online.
Play-to-Earn Economy Break Points
Inflationary tokenomics without sinks. Players earn tokens through gameplay. If sinks (burn or consumption mechanisms) are insufficient, supply outpaces demand. Price drops. Player fiat income declines. Players leave. A death spiral.
The right structure is a dual-token model with clear separation: a governance/value token with limited supply and a utility/reward token for in-game economy. The utility token must be actively consumed: item crafting, upgrades, entry fees, breeding. Examples: GODS/FLUX in Gods Unchained, AXS/SLP in Axie (though sinks were insufficient there). Historical data shows that without sinks, token supply inflates by 5–10% monthly, leading to price collapse within 6–9 months.
Effective Sink Mechanisms
- Breeding/crafting — burning utility token to create a new NFT (e.g., Axie). Typical burn costs range from $5–$15 per action, removing 0.5–2% of total supply annually.
- Character upgrades — each evolution requires token burning, consuming 0.1–0.3% of circulating supply per upgrade cycle.
- PvP entry fee — token burn for tournament entry, part goes to prize pool. This can burn up to 0.5% of supply per week in active games.
- Item durability — item breaks after N battles, token spent on repair. Cost per repair ~$0.50–$2.
- Financial mechanics — staking with lock-up, removing tokens from circulation for a period. Typical lock-up periods of 30–90 days reduce circulating supply by 15–25%.
On-Chain vs Off-Chain: Boundary and Trade-offs
It’s not necessary to put all game logic on-chain—each transaction costs gas and takes 12 seconds. A game cycle is milliseconds. Balance:
| Component |
On-chain |
Off-chain |
Examples |
| Asset Ownership |
+ |
– |
NFT items, land |
| Transfer/Trading |
+ |
– |
Marketplaces |
| Finance (staking, rewards) |
+ |
– |
Staking vaults, DAO |
| Random generation |
+ (via VRF) |
– |
Chainlink VRF |
| Gameplay |
– |
+ |
Battle system, movement |
| Game world state |
– |
+ |
Coordinates, health points |
| Matchmaking |
– |
+ |
Server-side logic |
Gameplay results are transferred to blockchain via signed messages from server or ZK-proof. Verifiable off-chain with ZK: game server generates ZK-proof of session correctness, contract verifies proof and issues rewards. Implementations: Cartridge (Starknet), zkSync game rollups. Gas savings from batching proofs can reach 90% compared to per-action on-chain validation.
How Does Dual-Token Model Prevent Economic Collapse?
Governance token (limited supply) acts as value store and is used for major decisions. Utility token (minted via gameplay) is consumed by sink mechanisms, ensuring deflationary pressure. The ratio of governance to utility tokens in the initial pool should be 1:10 to 1:20. Simulation shows that a 30% burn rate on utility token keeps supply growth below 3% per year, preserving player income and token price.
Implementation of NFT Game Items
Standard: ERC-1155 for fungible items (resources, consumables) + ERC-721 for unique (characters, land). ERC-1155 provides up to 60% gas savings on batch transfers.
How to Implement Dynamic NFTs Without Overloading the Blockchain?
Item attributes change during gameplay (experience, durability, upgrades). Two approaches:
- Fully on-chain: attributes stored in contract mapping,
tokenURI generated from attributes via SVG/JSON encoding. Expensive in gas with frequent updates (e.g., $0.50 per update). Used for land and key assets.
- Hybrid: attributes stored off-chain,
tokenURI contains state hash. Updates signed by server, verified on-chain during transfer or sale. Cheaper ($0.02 per update) but requires server trust or ZK.
Breeding and crafting. Contract: two parent NFTs → pay utility token (burn) → mint new NFT with attributes dependent on parents + Chainlink VRF for randomness. Without VRF, miners can manipulate randomness via block selection.
// Simplified breeding with Chainlink VRF
function breed(uint256 parent1Id, uint256 parent2Id) external {
require(ownerOf(parent1Id) == msg.sender);
require(ownerOf(parent2Id) == msg.sender);
require(breedingToken.burnFrom(msg.sender, BREEDING_COST));
uint256 requestId = vrfCoordinator.requestRandomWords(...);
pendingBreeds[requestId] = BreedRequest(parent1Id, parent2Id, msg.sender);
}
function fulfillRandomWords(uint256 requestId, uint256[] memory randomWords) internal override {
BreedRequest memory req = pendingBreeds[requestId];
uint256 childAttributes = deriveAttributes(req.parent1Id, req.parent2Id, randomWords[0]);
_mintWithAttributes(req.requester, childAttributes);
}
Marketplace and Royalties
An integrated marketplace gives control over fee structure and custom logic (e.g., banning item trading below a certain level). Royalties per EIP-2981 are standard but not enforceable: Blur and other marketplaces ignore on-chain royalties. For enforcement—whitelist-only transfer (only through contracts that pay royalties). Sacrifice composability for rights protection. Typical marketplace fee is 2.5–5% per transaction, generating recurring revenue.
Staking and Rewards Distribution
Staking NFTs is a mechanic for player retention. Problem: distributing rewards with thousands of stakers requires constant transactions (expensive). Solution—reward-per-share pattern (as in MasterChef from SushiSwap): global accRewardPerShare, upon claim or state change, debt is recalculated by formula pendingReward = stakedAmount * (accRewardPerShare - userRewardDebt). O(1) complexity regardless of staker count. Gas savings up to 70% compared to per-element distribution. Over a year with 10,000 stakers, this translates to roughly $40,000 saved in gas.
Why Is Reward-Per-Share Pattern Critical for Scalability?
Direct per-user reward updates cost O(n) per block, consuming more than 200,000 gas for 1,000 stakers. Reward-per-share reduces this to 30,000–50,000 gas per user claim, enabling thousands of stakers. Many early P2E games collapsed under gas costs that exceeded reward value. This pattern scales to tens of thousands without infrastructure overhead.
Process and Timelines
We start with a game economics document: token flows, mint/burn mechanics, projected supply schedule, sink analysis. Before writing code, the economy is modeled (Cadence, Python simulation).
GameFi Building Process: 5 Stages
- Economic modeling — 1–2 weeks. Develop dual-token model, calculate sinks, outline incentives for long-term holding.
- Token contract development — 2–3 weeks. ERC-20 for governance, ERC-20 for utility, with configurable mint/burn policy.
- NFT smart contracts — 3–5 weeks. ERC-721 / ERC-1155 with dynamic metadata, breeding/crafting, Chainlink VRF.
- Staking + rewards — 2–3 weeks. Contract based on reward-per-share, interfaces for frontend.
- Marketplace (optional) — 2–4 weeks. Custom marketplace with enforced royalty.
Work Deliverables
- Source code for all smart contracts with tests (Foundry/Hardhat)
- Architecture and economics documentation
- Integration with Chainlink, Tenderly for monitoring
- Code audit and formal verification (Slither, Mythril, Echidna)
- Team training on contract interaction
- Post-deployment support (3 months)
Basic GameFi stack (tokens + NFTs + staking + marketplace) — 8 to 16 weeks. Full game with on-chain randomness, breeding, dynamic NFTs — 4–8 months. ZK-based verifiable gameplay — a separate project from 6 months.
Contact us for an audit of your tokenomics—we’ll assess risks and refine sink mechanisms. Order GameFi project development—receive a ready product with proven economy. We guarantee contract stability and code transparency. Our experience includes dozens of implemented Web3 projects, including audits of 15+ P2E games. Get a consultation to start your project.