Fair Random Crash Game on Blockchain

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
Fair Random Crash Game on Blockchain
Medium
~5 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

Developing a blockchain Crash game is not just a smart contract with randomness. The core dilemma: how to give players absolute confidence in the fairness of the result without sacrificing speed? Classic solutions on Ethereum L1 drown in gas and delays — a cashout transaction takes 12 seconds, while a crash can occur in 100 ms. L2 networks (Arbitrum, Polygon) and hybrid architectures with off-chain signatures solve this. We bet on provably fair via Chainlink VRF and batch settlement — this allows processing millions of rounds with a fee of less than $0.01 per transaction.

Crash is a game where the multiplier grows from 1x upward and randomly "crashes" at some point. The player must withdraw the bet before the crash. In a decentralized version, the round result must be provably fair: the player can mathematically verify that the multiplier was not rigged. This is achieved via a commitment scheme and on-chain randomness from Chainlink. The cashout architecture is critically important — it determines the economy and user experience. Below we break down the key nodes.

How to implement provably fair in a blockchain Crash game?

Commitment + Reveal scheme (without oracle)

Classic scheme: the operator pre-publishes the hash of the next seed, then reveals the seed after bets close.

contract CrashGame {
    struct Round {
        bytes32 seedHash;
        bytes32 seed;
        uint64 crashPoint;
        uint256 totalBets;
        uint256 startTime;
        RoundStatus status;
    }
    
    enum RoundStatus { ACCEPTING_BETS, IN_PROGRESS, CRASHED, CASHOUT_PHASE }
    
    function commitNextRound(bytes32 seedHash) external onlyOperator {
        require(rounds[nextRoundId].status == RoundStatus.CRASHED, "Previous not finished");
        rounds[nextRoundId + 1].seedHash = seedHash;
    }
    
    function revealAndStart(uint256 roundId, bytes32 seed) external onlyOperator {
        Round storage round = rounds[roundId];
        require(round.status == RoundStatus.ACCEPTING_BETS, "Wrong status");
        require(keccak256(abi.encodePacked(seed)) == round.seedHash, "Seed mismatch");
        
        round.seed = seed;
        round.crashPoint = _calculateCrashPoint(seed, roundId);
        round.status = RoundStatus.IN_PROGRESS;
        round.startTime = uint64(block.timestamp);
        
        emit RoundStarted(roundId, round.crashPoint);
    }
}

Problem with commitment scheme: the operator knows the seed in advance and may refuse to reveal an unfavorable one (griefing). Solution — VRF.

Chainlink VRF V2 Plus: trustless random

import {VRFConsumerBaseV2Plus} from "@chainlink/contracts/src/v0.8/vrf/dev/VRFConsumerBaseV2Plus.sol";

contract CrashGame is VRFConsumerBaseV2Plus {
    uint256 private immutable s_subscriptionId;
    bytes32 private immutable s_keyHash;
    
    mapping(uint256 => uint256) public roundToVrfRequest;
    mapping(uint256 => uint256) public vrfRequestToRound;
    
    function closeAndRequestRandom(uint256 roundId) external onlyOperator {
        Round storage round = rounds[roundId];
        require(round.status == RoundStatus.ACCEPTING_BETS, "Wrong status");
        
        round.status = RoundStatus.IN_PROGRESS;
        
        uint256 requestId = s_vrfCoordinator.requestRandomWords(
            VRFV2PlusClient.RandomWordsRequest({
                keyHash: s_keyHash,
                subId: s_subscriptionId,
                requestConfirmations: 1,
                callbackGasLimit: 100_000,
                numWords: 1,
                extraArgs: VRFV2PlusClient._argsToBytes(
                    VRFV2PlusClient.ExtraArgsV1({nativePayment: false})
                )
            })
        );
        
        roundToVrfRequest[roundId] = requestId;
        vrfRequestToRound[requestId] = roundId;
    }
    
    function fulfillRandomWords(
        uint256 requestId,
        uint256[] calldata randomWords
    ) internal override {
        uint256 roundId = vrfRequestToRound[requestId];
        Round storage round = rounds[roundId];
        
        uint256 rand = randomWords[0];
        round.crashPoint = _calculateCrashPoint(rand);
        round.seed = bytes32(rand);
        
        emit RoundActive(roundId, round.startTime = uint64(block.timestamp));
    }
}

Chainlink VRF documentation: "VRF provides cryptographic proofs that the random number was generated using the block data and the oracle's secret key."

Crash point formula

Crash point math with 1% house edge

Target distribution: P(crash >= X) = 0.99/X. Minimum crash = 1.00x.

function _calculateCrashPoint(uint256 rand) internal pure returns (uint64) {
    uint256 h = rand % 1_000_000_000;
    
    if (h < 10_000_000) return 100; // 1.00x
    
    uint256 crashPoint = 990_000_000 * 100 / h;
    
    if (crashPoint < 100) return 100;
    if (crashPoint > 100_000) return 100_000;
    
    return uint64(crashPoint);
}

Verification: any player can take the VRF randomWords[0] from on-chain data and reproduce the formula — they will get the same crash point.

Why manual cashout is a bottleneck and how to bypass it?

Bet and cashout mechanics

struct Bet {
    address player;
    uint256 amount;
    uint64 autoCashoutAt;
    bool cashedOut;
    uint64 cashoutMultiplier;
}

mapping(uint256 => mapping(address => Bet)) public bets;

function placeBet(uint256 roundId, uint64 autoCashoutAt) external payable {
    Round storage round = rounds[roundId];
    require(round.status == RoundStatus.ACCEPTING_BETS, "Not accepting bets");
    require(msg.value >= MIN_BET && msg.value <= MAX_BET, "Invalid amount");
    require(bets[roundId][msg.sender].amount == 0, "Already bet");
    
    bets[roundId][msg.sender] = Bet({
        player: msg.sender,
        amount: msg.value,
        autoCashoutAt: autoCashoutAt,
        cashedOut: false,
        cashoutMultiplier: 0
    });
    
    rounds[roundId].totalBets += msg.value;
    emit BetPlaced(roundId, msg.sender, msg.value, autoCashoutAt);
}

function cashout(uint256 roundId) external {
    Round storage round = rounds[roundId];
    Bet storage bet = bets[roundId][msg.sender];
    
    require(round.status == RoundStatus.IN_PROGRESS, "Round not active");
    require(bet.amount > 0 && !bet.cashedOut, "No active bet");
    
    uint64 currentMultiplier = _getCurrentMultiplier(round.startTime);
    require(currentMultiplier <= round.crashPoint, "Round already crashed");
    
    bet.cashedOut = true;
    bet.cashoutMultiplier = currentMultiplier;
    
    uint256 payout = bet.amount * currentMultiplier / 100;
    payable(msg.sender).transfer(payout);
    
    emit CashedOut(roundId, msg.sender, currentMultiplier, payout);
}

function _getCurrentMultiplier(uint64 startTime) public view returns (uint64) {
    uint256 elapsed = block.timestamp - startTime;
    uint256 multiplier = 100 + (elapsed * elapsed * 2);
    return uint64(multiplier > 100_000 ? 100_000 : multiplier);
}

Manual cashout on-chain has latency. The player clicks cashout in the UI → transaction goes to mempool → gets included in a block (10–12 sec on Ethereum). During that time, the round may crash. On L2 (Arbitrum: 250 ms, Solana: 400 ms) this is more acceptable, but still not ideal. Transaction fee on Arbitrum is less than $0.01, making frequent cashouts economically viable.

Solution for low-latency: hybrid architecture. Off-chain cashout: player signs a cashout request → game server stores the signed timestamp → during on-chain settlement, the game server proves the player requested cashout before the crash. This requires trust in the game server but with cryptographic accountability.

Off-chain batch settlement

struct CashoutRecord {
    address player;
    uint64 multiplier;
    bytes signature;
}

function settleBatch(
    uint256 roundId,
    CashoutRecord[] calldata cashouts
) external onlyOperator {
    Round storage round = rounds[roundId];
    require(round.status == RoundStatus.CRASHED, "Round not crashed");
    
    for (uint i = 0; i < cashouts.length; i++) {
        CashoutRecord calldata c = cashouts[i];
        Bet storage bet = bets[roundId][c.player];
        
        require(!bet.cashedOut, "Already settled");
        require(c.multiplier <= round.crashPoint, "Invalid multiplier");
        
        _verifyCashoutSignature(roundId, c.player, c.multiplier, c.signature);
        
        bet.cashedOut = true;
        bet.cashoutMultiplier = c.multiplier;
        
        uint256 payout = bet.amount * c.multiplier / 100;
        payable(c.player).transfer(payout);
    }
}

Network comparison for blockchain Crash

Network Block time Gas cost (typical) Suitable for MVP Summary
Ethereum L1 12-15 sec High (~$50/tx) No Only for high-rollers due to latency and fees
Arbitrum One ~250 ms Low ($0.01-$0.05) Yes Best balance: speed, security, ecosystem
Polygon PoS ~2 sec Very low ($0.001) Yes Even cheaper, but less decentralized
Solana ~400 ms Minimal ($0.0001) Yes Maximum speed, but Rust development is harder

Hybrid cashout and batch settlement can save up to $5000 monthly on gas with high player activity. Average fee on Arbitrum — $0.01-0.03 per cashout, making microtransactions profitable.

Our work process

  1. Analysis and specification — defining mechanics, house edge, RNG, latency requirements.
  2. Smart contract design — architecture, pattern selection (commitment, VRF, batch settlement).
  3. Contract implementation — Solidity, Foundry, thorough testing (unit, integration, fork).
  4. Backend and frontend development — Node.js game server, WebSocket, React with real-time graphics.
  5. Audit and formal verification — Slither, Echidna, Mythril, third-party auditor if needed.
  6. Deployment and monitoring — contracts on mainnet, Tenderly setup, dashboards.
  7. Regulatory compliance — document preparation for license, KYC/AML integration.
Stage Duration Result
Analysis and specification 1-2 weeks Requirements document, UI mockups
Contract design 1-2 weeks Architecture, ERC implementation
Contract implementation 3-4 weeks Ready contracts, tests, CI
Backend and frontend 4-6 weeks Game server, WebSocket, UI
Audit and verification 2-3 weeks Audit report, fixes
Deployment and monitoring 1 week Contracts on network, monitoring

What is included in the work (deliverables)

  • Source code of smart contracts (Solidity) with full test suite.
  • Detailed documentation on architecture, formulas, verification procedure.
  • Game server (Node.js) with WebSocket and contract integration.
  • Frontend (React) with visualization and wallet (MetaMask, WalletConnect).
  • Deployment and management guide (Tenderly, Etherscan).
  • Launch support (24/7 for the first week).

Our experience and metrics

Over 5 years, we have developed blockchain solutions for GameFi. Our portfolio includes 10+ projects, including Crash, Dice, and NFT lotteries. Our contracts have been audited by leading firms and processed over 1 million transactions. Order a smart contract audit before release — it reduces risks by 90%. To launch your own Crash game, contact us for a consultation.

Estimated timelines

  • MVP (Chainlink VRF, manual on-chain cashout, basic UI): 4–6 weeks.
  • Production (hybrid cashout, batch settlement, bankroll management, regulatory compliance): 10–14 weeks.

Cost is calculated individually based on scope and chosen stack. For an accurate estimate, contact us — we will prepare a commercial proposal. Get a consultation before starting: we'll discuss architecture and KPIs.

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.