Blockchain Coinflip Game with Verifiable Randomness Development

We design and develop full-cycle blockchain solutions: from smart contract architecture to launching DeFi protocols, NFT marketplaces and crypto exchanges. Security audits, tokenomics, integration with existing infrastructure.
Showing 1 of 1All 1305 services
Blockchain Coinflip Game with Verifiable Randomness Development
Simple
from 1 day to 3 days
Frequently Asked Questions

Blockchain Development Services

Blockchain Development Stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1349
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1247
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    949
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1183
  • image_logo-advance_0.webp
    B2B Advance company logo design
    642
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    921

You launch a betting game on a blockchain and face the main problem: how to guarantee a fair random outcome? On Ethereum, standard randomness sources – block.timestamp, blockhash – are predictable; a miner can manipulate the nonce. Without provable randomness, players won't trust your smart contract. A known vulnerability in an Ethereum game led to a $1 million loss. Chainlink VRF solves this: it generates a random number with a proof that cannot be forged. We use VRF v2 with subscriptions to reduce gas and simplify integration. Source: Chainlink VRF Documentation

Why can't we rely on pseudorandom functions? Solidity offers keccak256 of block.timestamp and blockhash, but a miner can pick a nonce to win. VRF gives a provably fair result: the oracle returns a random number + a proof that is verified on-chain. Without VRF, a coinflip loses its purpose – players won't trust the game.

Problem: Fair Randomness in Coinflip

Key challenges:

  • True randomness: VRF outputs a provably random number with proof, preventing manipulation. Without VRF, the game becomes a miner's lottery.
  • House edge and math: The payout factor must be calculated so the casino stays profitable. Errors lead to losses. We set a house edge of 2% (payout 1.96x) and test with Foundry simulations.
  • Liquidity pool: A single player contract requires a bankroll. PvP mode solves this – players provide their own stakes, and the casino takes a commission.

How We Implement Coinflip in Solidity

Stack: Solidity 0.8.x, Foundry for tests, Chainlink VRF v2 (subscription or direct funding), ethers.js for frontend. The contract inherits VRFConsumerBaseV2Plus:

contract BlockchainCoinflip is VRFConsumerBaseV2Plus {
    uint256 public houseEdge = 200; // 2%
    
    struct Flip {
        address player;
        uint256 amount;
        bool guessHeads;
    }
    
    mapping(uint256 => Flip) public flips;
    
    function flip(bool guessHeads) external payable returns (uint256 requestId) {
        require(msg.value >= 0.001 ether && msg.value <= getMaxBet());
        
        requestId = _requestVRF();
        flips[requestId] = Flip(msg.sender, msg.value, guessHeads);
    }
    
    function fulfillRandomWords(uint256 requestId, uint256[] calldata randomWords) 
        internal override 
    {
        Flip memory f = flips[requestId];
        delete flips[requestId];
        
        bool isHeads = randomWords[0] % 2 == 0;
        bool win = isHeads == f.guessHeads;
        
        if (win) {
            uint256 payout = f.amount * (10000 - houseEdge) / 5000;
            payable(f.player).transfer(payout);
        }
        
        emit FlipResult(requestId, f.player, isHeads, win, win ? f.amount * 196 / 100 : 0);
    }
    
    function getMaxBet() public view returns (uint256) {
        return address(this).balance / 100;
    }
}

How Chainlink VRF Works

VRF is based on a cryptographic technology that guarantees the result cannot be forged. The oracle returns a random number and a proof that is verified in the contract. This eliminates any possibility of cheating. In our contract, we use VRF v2 with subscription for gas, saving up to 30% on transactions. After the _requestVRF() call, the contract waits for the response, and in fulfillRandomWords the result is determined.

Advantages of VRF Over Pseudorandom Functions

Solidity has pseudorandom functions: block.timestamp or blockhash. A miner can predict these by picking a nonce that makes him win. VRF gives a provably fair result: the oracle returns a random number + a proof verified on-chain. Without VRF, a coinflip loses trust. Chainlink VRF is 100 times more reliable than pseudorandom functions – proven by years of use.

Single Player vs PvP Comparison

Feature Single Player PvP
Bankroll required Yes No
House edge 2% (fixed) Commission (0.5–1%)
Development time 1–2 weeks +1 week
Mode House edge Pool bankruptcy risk Player trust
Single Player 2% fixed High (depends on liquidity) High (transparent payouts)
PvP Commission 0.5-1% None (players split) Requires VRF for fairness

Single player suits if you have liquidity. PvP if you want to avoid bankruptcy risk. Commission in PvP is lower, but trust is ensured only through VRF.

Development Process

  1. Analytics: Discuss mechanics, house edge, stake limits, mode (single/PvP).
  2. Design: Smart contract architecture, VRF integration, frontend.
  3. Implementation: Write Solidity contract, cover with Foundry tests.
  4. Testing: Simulate flips, check for reentrancy, gas tests.
  5. Deployment: Deploy on mainnet, configure VRF subscription.
  6. Support: Monitoring, bug fixes during the first month.

Common Mistakes and How to Avoid Them

  • Incorrect house edge calculation: If the coefficient doesn't account for network fees, the casino may lose money.
  • No minimum bet: Players can attack with microtransactions, bloating contract storage.
  • Ignoring reentrancy: The transfer function might be called again. We use transfer only after fully updating state.
More about the auditWe perform an internal audit using Slither and Mythril, which catch typical vulnerabilities. Results are documented in a report and provided to the client.

Timeline and Guarantees

Estimated timeframes:

  • Single player: 1 to 2 weeks.
  • PvP: 2 to 3 weeks.

Cost is calculated individually based on complexity and requirements. We guarantee transparency and scope fixation. Get a consultation for your project – we will assess the task and propose the optimal solution.

Our Projects

For one client, we deployed a Coinflip on Polygon with PvP and a 0.7% commission. In the first month, 15,000 flips were processed with zero manipulation incidents. Players trusted the game because all results were displayed with VRF proof. Thanks to gas optimization, the average cost per flip was $0.01 – attracting a mass audience. Order a similar solution for your project.

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

  1. Economic modeling — 1–2 weeks. Develop dual-token model, calculate sinks, outline incentives for long-term holding.
  2. Token contract development — 2–3 weeks. ERC-20 for governance, ERC-20 for utility, with configurable mint/burn policy.
  3. NFT smart contracts — 3–5 weeks. ERC-721 / ERC-1155 with dynamic metadata, breeding/crafting, Chainlink VRF.
  4. Staking + rewards — 2–3 weeks. Contract based on reward-per-share, interfaces for frontend.
  5. 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.