Building Fair PvP Games on Blockchain with Smart Contracts

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
Building Fair PvP Games on Blockchain with Smart Contracts
Complex
~1-2 weeks
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

In blockchain PvP games, the central challenge is ensuring fairness with hidden moves and low latency for real-time gameplay. Our smart contract PvP solutions ensure fair play. On-chain transactions are expensive ($0.1–$1 per move) and slow (>12 seconds). Simply leaving logic on the server means giving up trustless properties. We develop blockchain PvP games with smart contracts that ensure fair matchmaking, hidden moves via commit-reveal, and lightning-fast off-chain moves through state channels. Our experience: over 5 years in Web3 gaming, 50+ successful projects, a team of senior engineers focused on game mechanics. Our turnkey solution includes everything from architecture to deployment within 4-6 weeks for basic games. Typical development costs start at $15,000 for a simple 1v1 game, with state channels adding $10,000. Gas costs on Arbitrum are ~$0.01 per transaction, making state channel closures extremely affordable. We guarantee security and fair play with audited contracts. Get a blockchain architect consultation: tell us about your game, we'll pick the optimal stack and estimate the cost.

How commit-reveal solves the hidden move problem

In card games and strategies, each opponent's move must remain hidden until applied. On blockchain, all data is public, so the commit-reveal pattern is used. Players first send a hash of their action with a secret, then reveal it. If someone fails to reveal in time, they automatically lose. This eliminates peeking and back-running.

Example implementation in Solidity (using Foundry):

Click to expand Solidity example
contract PvPGame {
    struct GameState {
        address player1;
        address player2;
        bytes32 p1CommitHash;  // hash(action + secret)
        bytes32 p2CommitHash;
        uint8 p1Action;        // revealed after both commit
        uint8 p2Action;
        Phase phase;
        uint256 commitDeadline;
        uint256 revealDeadline;
    }
    
    enum Phase { WAITING, COMMIT, REVEAL, RESOLVED }
    
    // Phase 1: both players send hash(action + secret)
    function commitAction(uint256 gameId, bytes32 commitHash) external {
        GameState storage game = games[gameId];
        require(game.phase == Phase.COMMIT, "Not commit phase");
        require(block.timestamp <= game.commitDeadline, "Commit deadline passed");
        
        if (msg.sender == game.player1) {
            game.p1CommitHash = commitHash;
        } else if (msg.sender == game.player2) {
            game.p2CommitHash = commitHash;
        } else revert("Not a player");
        
        // If both committed — transition to reveal
        if (game.p1CommitHash != bytes32(0) && game.p2CommitHash != bytes32(0)) {
            game.phase = Phase.REVEAL;
            game.revealDeadline = block.timestamp + REVEAL_WINDOW;
        }
    }
    
    // Phase 2: reveal actual actions
    function revealAction(uint256 gameId, uint8 action, bytes32 secret) external {
        GameState storage game = games[gameId];
        require(game.phase == Phase.REVEAL, "Not reveal phase");
        
        bytes32 expectedHash = keccak256(abi.encodePacked(action, secret));
        
        if (msg.sender == game.player1) {
            require(game.p1CommitHash == expectedHash, "Hash mismatch");
            game.p1Action = action;
        } else if (msg.sender == game.player2) {
            require(game.p2CommitHash == expectedHash, "Hash mismatch");
            game.p2Action = action;
        }
        
        // If both revealed — resolve
        if (game.p1Action != 0 && game.p2Action != 0) {
            _resolveGame(gameId);
        }
    }
    
    // If player doesn't reveal in time — forfeit
    function claimTimeout(uint256 gameId) external {
        GameState storage game = games[gameId];
        require(game.phase == Phase.REVEAL, "Not reveal phase");
        require(block.timestamp > game.revealDeadline, "Deadline not passed");
        
        // The player who didn't reveal loses
        address winner;
        if (game.p1Action == 0 && game.p2Action != 0) {
            winner = game.player2;
        } else if (game.p2Action == 0 && game.p1Action != 0) {
            winner = game.player1;
        } else {
            // Both not revealed — refund stakes
            _refundBothPlayers(gameId);
            return;
        }
        
        _payWinner(gameId, winner);
    }
}

Why state channels are optimal for real-time PvP

On-chain, each move costs gas and takes >12 seconds. State channels allow thousands of moves between two players without fees, with only the deposit at stake. After the game, the channel is closed with a single on-chain transaction. Our smart contracts optimize gas usage, achieving up to 90% savings. Typical gas savings with state channels amount to $0.5–$1 per move, which for 1000 moves equals $500–$1000 saved. Compare:

Criteria On-chain State channel
Move time 12+ seconds <50 ms
Fee $0.1–$1 $0 (open/close only)
Throughput ~15 tx/s 1000+ moves/s
Trustlessness Full High (requires dispute slot)

State channels are 1000x faster than on-chain transactions, critical for real-time strategies. Gas savings reach up to 90% when using state channels.

How we protect the game from cheaters

For on-chain PvP, all logic is in the smart contract — cheating is impossible. For off-chain + on-chain settlement, server-side validation is needed. We implement checks for turn order, move validity, timestamps, and replay protection. For hidden data, we use zk-SNARKs: a player proves the correctness of a move without revealing it.

class GameValidator {
  async validateMove(
    gameState: GameState,
    move: Move,
    playerId: string
  ): Promise<ValidationResult> {
    // 1. Check turn order
    if (gameState.currentTurn !== playerId) {
      return { valid: false, reason: "Not your turn" };
    }
    
    // 2. Check move validity per game rules
    const allowedMoves = this.getAllowedMoves(gameState, playerId);
    if (!allowedMoves.includes(move.type)) {
      return { valid: false, reason: "Invalid move" };
    }
    
    // 3. Check that move hasn't already been made (replay protection)
    if (this.moveCache.has(move.id)) {
      return { valid: false, reason: "Duplicate move" };
    }
    
    // 4. Check timestamp (move not older than N seconds)
    if (Date.now() - move.timestamp > MAX_MOVE_AGE_MS) {
      return { valid: false, reason: "Move too old" };
    }
    
    return { valid: true };
  }
}

How the tournament system is implemented

contract PvPTournament {
    struct Tournament {
        uint256 entryFee;
        uint256 maxPlayers;
        address[] participants;
        TournamentType tournamentType; // SINGLE_ELIMINATION, ROUND_ROBIN, SWISS
        uint256 prizePool;
        TournamentStatus status;
    }
    
    // Prize distribution (in basis points)
    uint256[] public prizeDistribution = [5000, 3000, 1500, 500]; // 50%, 30%, 15%, 5%
    
    function registerForTournament(uint256 tournamentId) external payable {
        Tournament storage t = tournaments[tournamentId];
        require(t.participants.length < t.maxPlayers, "Tournament full");
        require(msg.value == t.entryFee, "Wrong entry fee");
        
        t.participants.push(msg.sender);
        t.prizePool += msg.value;
    }
    
    function distributePrizes(uint256 tournamentId, address[] calldata rankedPlayers) 
        external onlyAdmin 
    {
        Tournament storage t = tournaments[tournamentId];
        
        for (uint i = 0; i < prizeDistribution.length && i < rankedPlayers.length; i++) {
            uint256 prize = (t.prizePool * prizeDistribution[i]) / 10000;
            payable(rankedPlayers[i]).transfer(prize);
        }
    }
}

How matchmaking works

For high-load PvP games, we use Redis sorted sets. Each player enters a queue with a rating (MMR). When the rating matches another player, they are automatically paired into a smart contract. This blockchain-based matchmaking allows processing thousands of requests per second without bottlenecks. The queue is stored off-chain, but the match is confirmed by an on-chain transaction.

Development process

  1. Analysis — description of game mechanics and economy
  2. Design — smart contract architecture, data schema
  3. Development — writing contracts in Solidity, testing in Foundry
  4. Audit — security check, fuzzing, formal verification
  5. Deployment — publishing on chosen L2, infrastructure setup, frontend integration

What's included in the work

  • Architectural documentation (diagrams, contract specifications)
  • Source code of smart contracts (Solidity, Foundry)
  • Full test suite (unit, integration, fuzz)
  • Integration with Chainlink VRF for randomness
  • State channel setup (if required)
  • Deployment on chosen EVM L2 and monitoring setup
  • Security audit (Slither, Mythril, fuzzing, manual review) by independent firms
  • Scripts for contract verification in explorer
  • Team training (1-2 sessions, documentation)
  • Support for 1 month after deployment

Timelines

  • 1v1 game (Coinflip, RPS, basic card): 4-6 weeks
  • State Channel PvP: +3-4 weeks
  • Tournament system: +3-4 weeks
  • Complex card/strategy game: 3-5 months
  • Security audit: mandatory, +4-6 weeks

Technology stack

Component Technology
Smart contracts Solidity + Foundry, State Channels
Randomness Chainlink VRF v2.5
Real-time comm. WebSocket (Socket.io)
Game server Node.js + TypeScript
Matchmaking Redis sorted sets
Frontend React / Unity WebGL
EVM L2 Arbitrum / Base / Polygon
Anti-cheat Server-side validation + zkProofs
Gas optimization Techniques like calldata packing, storage packing

commit-reveal — standard protocol for hidden data submission.

Our turnkey solution includes everything from architecture to deployment within 4-6 weeks for basic games. Write us for a free project estimate. Get a blockchain architect consultation — tell us about your game, we'll pick the optimal stack and estimate the cost.

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.