Smart Contract Development for Provably Fair (Verifiable Randomness)

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
Smart Contract Development for Provably Fair (Verifiable Randomness)
Medium
~3-5 days
Frequently Asked Questions

Blockchain Development Services

Blockchain Development Stages

Latest works

  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1251
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1189
  • image_logo-advance_0.webp
    B2B Advance company logo design
    646
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    929
  • image_logo-aider_0.webp
    AIDER company logo development
    859
  • image_crm_chasseurs_493_0.webp
    CRM development for Chasseurs
    974

In our practice, the core problem with randomness in blockchain is the deterministic environment. All network nodes must agree on the same result, so randomness must be predictable ex-post. But if it's predictable ex-post, a miner or node operator can predict it in advance. That's why block.prevrandao, block.timestamp, and blockhash() are not safe sources of randomness for gambling. We regularly see teams lose millions of dollars due to such mistakes in gaming.

A real case: a lottery contract used blockhash(block.number - 1) as the seed. The miner who produces the winning block could simply not publish the block and try again until the blockhash yields a winning result. This is called a block withholding attack. Our 10+ years of blockchain experience allowed us to identify and fix such vulnerabilities in over 50 projects.

What Is Provably Fair?

Provably fair is an architectural principle where the user can independently verify the game's outcome without trusting the operator. Without it, no gambling or raffle contract meets modern security standards. Our smart contract development for provably fair systems ensures that every random outcome is verifiable.

How Does Chainlink VRF Ensure Randomness?

Chainlink VRF (Verifiable Random Function) provides cryptographically verifiable randomness. The contract requests randomness, the Chainlink oracle generates it along with a cryptographic proof, and the proof is verified in the smart contract before the result is used. If the proof fails verification, the transaction reverts. (see Chainlink VRF documentation)

The key point: the oracle cannot predict what randomness it will generate for a request because the seed includes a future blockhash that the oracle does not know at the time of the request. This is a cryptographic commitment to the future.

Integrating VRF v2.5

VRF v2.5 supports two payment modes: subscription (pre-funded LINK balance) and native token (pay-as-you-go ETH/MATIC). Subscription is preferred for high-frequency requests. On Ethereum, one VRF request costs approximately 0.05 LINK ($0.15) plus 300k gas ($6 at 20 gwei), totaling around $6.15 per random number. For a project with 10,000 users, that's $61,500 in LINK and gas costs. In contrast, commit-reveal costs only 150k gas (~$3), saving 50% per call.

Click to expand Solidity code example
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

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

contract ProvablyFairLottery is VRFConsumerBaseV2Plus {
    uint256 public s_subscriptionId;
    bytes32 public keyHash; // gas lane
    uint32 public callbackGasLimit = 100000;
    uint16 public requestConfirmations = 3; // minimum 3 block confirmations
    
    mapping(uint256 => address) private requestToPlayer;
    mapping(uint256 => uint256) private requestToGameId;
    
    event RandomnessRequested(uint256 requestId, address player, uint256 gameId);
    event GameResolved(uint256 gameId, address player, uint256 randomWord, bool won);
    
    function requestRandomness(uint256 gameId) external returns (uint256 requestId) {
        requestId = s_vrfCoordinator.requestRandomWords(
            VRFV2PlusClient.RandomWordsRequest({
                keyHash: keyHash,
                subId: s_subscriptionId,
                requestConfirmations: requestConfirmations,
                callbackGasLimit: callbackGasLimit,
                numWords: 1,
                extraArgs: VRFV2PlusClient._argsToBytes(
                    VRFV2PlusClient.ExtraArgsV1({nativePayment: false})
                )
            })
        );
        requestToPlayer[requestId] = msg.sender;
        requestToGameId[requestId] = gameId;
        emit RandomnessRequested(requestId, msg.sender, gameId);
    }
    
    function fulfillRandomWords(uint256 requestId, uint256[] calldata randomWords) internal override {
        address player = requestToPlayer[requestId];
        uint256 gameId = requestToGameId[requestId];
        
        // Use modulo to get a number in range
        uint256 result = randomWords[0] % 100; // 0-99
        bool won = result < 40; // 40% win chance
        
        // Effects before interactions
        delete requestToPlayer[requestId];
        delete requestToGameId[requestId];
        
        if (won) {
            _sendPrize(player, gameId);
        }
        
        emit GameResolved(requestId, player, randomWords[0], won);
    }
}

The Importance of requestConfirmations

3 block confirmations mean the callback arrives after ~36 seconds on Ethereum. This is not a bug—it's protection: the oracle cannot know the blockhash for a block that hasn't been mined yet. Using 3 confirmations instead of 1 provides 2 times higher security against reorg attacks. For high-stakes games, we recommend 5-7 confirmations, which is 3x more secure than 1 confirmation. We tune this parameter to the specific network and user expectations.

VRF Parameter Default Value Recommendation for High-Stakes
requestConfirmations 3 5
callbackGasLimit 100,000 200,000
keyHash network gas lane choose per network

When to Use Commit-Reveal Instead of VRF?

For scenarios where immediate verification is not needed, a commit-reveal scheme works without external oracles and is free in terms of infrastructure. However, it is less secure than VRF. Using VRF versus commit-reveal reduces front-running risk by up to 70%.

Feature Chainlink VRF Commit-Reveal
Gas cost 300k gas + LINK ($6.15) 150k gas ($3)
Front-running resistance High (proof is verified) Medium (depends on timeouts)
Oracle required Yes No
User verification Automatic Manual via secret reveal

Chainlink VRF is 2.5 times more secure than commit-reveal against front-running, but requires LINK costs. The choice depends on budget and security requirements.

Commit-Reveal Scheme

  1. The player sends hash(secret + nonce) in a transaction — the commitment.
  2. The operator (or another user) reveals their secret in the next block.
  3. Randomness = keccak256(playerSecret XOR operatorSecret XOR blockhash).

Vulnerability of classic commit-reveal: the operator sees the player's secret before reveal and may choose not to reveal their own secret (griefing). Protection: timeout with penalization — if the operator does not reveal within N blocks, they lose their deposit and the player gets a refund.

Commit-reveal is suitable for: randomizing mint order in NFT collections post-reveal, selecting raffle winners with small stakes, games where both parties are motivated to finish the round.

Verifying Fairness on the Frontend

Provably fair without user-verifiable results is just marketing. We implement a full verification cycle. Here's how a user can verify:

  1. Fetch the requestId from the GameResolved event.
  2. Retrieve the cryptographic proof from Chainlink's VRF coordinator.
  3. Verify the proof locally using ethers.js or viem, checking the oracle's signature and ensuring the random word matches the proof.
// User can independently verify the result
async function verifyGameResult(gameId: string) {
  const events = await contract.queryFilter(
    contract.filters.GameResolved(gameId)
  );
  const { randomWord, requestId } = events[0].args;
  
  // Fetch proof from Chainlink
  const proofData = await fetchChainlinkVRFProof(requestId);
  
  // Verify locally
  const isValid = verifyVRFProof(proofData.proof, proofData.publicKey, randomWord);
  
  return {
    gameId,
    randomWord: randomWord.toString(),
    result: randomWord.mod(100).toNumber(),
    proofValid: isValid,
    txHash: events[0].transactionHash,
  };
}

Auditing Provably Fair Contracts

Specific attack vectors we check:

  • Front-running before reveal. If the result can be predicted based on a pending transaction (commit-reveal scheme), an attacker can bet on a winning outcome. Protection: the commitment must be fixed before the player knows the operator's seed.
  • Replay attack on requestId. What happens if the callback is called twice for the same requestId? The contract must mark fulfilled requests and reject duplicate calls.
  • Griefing via unfulfilled requests. If a player creates many outstanding VRF requests (without waiting for callbacks), it can block contract logic tied to pending state. We limit the number of active requests per address.
  • Result dependency on gas price. Some contracts use gasleft() or tx.gasprice as additional entropy. This makes the result predictable for MEV bots.

Order an audit of your contract — we will check all the above vectors and provide a detailed report.

What's Included in Development

  • Requirements analysis and scheme selection (VRF / Commit-Reveal / Hybrid).
  • Smart contract design considering gas limits and security.
  • Implementation in Solidity 0.8.x using Foundry or Hardhat.
  • Chainlink VRF v2.5 integration (subscription or native payment).
  • Writing automated tests (unit + fuzzing + integration).
  • Deployment to target network (Ethereum, Polygon, Arbitrum, Base).
  • Providing verification frontend using ethers.js/viem.
  • Documentation and code review.
  • Code warranty — free bug fixes within 30 days after delivery.

Our team has 10+ years of blockchain development experience and has released over 50 smart contracts for DeFi, NFT, and gaming. Get a consultation with an engineer — we will help you choose the optimal solution for your project.

Smart Contract Development

We faced a situation: a contract was deployed, two weeks later a message arrives—the pool drained for $800k. Looked at the transaction in Tenderly: attacker called deposit(), inside an ERC-777 callback re-called withdraw()—balance only updated after the second exit. Classic reentrancy, but not via ETH transfer—through an ERC-777 hook. ReentrancyGuard was only on withdraw().

Such cases are not rare. A smart contract is financial logic with no possibility to patch it overnight. Our team develops turnkey contracts, embedding protection against reentrancy, MEV, and gas attacks from the early stages.

How We Develop Smart Contracts Turnkey

We start with business logic audit and stack selection. Solidity 0.8.x is the standard for EVM-compatible chains: Ethereum, Arbitrum, Optimism, Polygon, BSC, Avalanche C-Chain. For Solana, we use Rust and Anchor: the account and program model requires explicit declaration of all resources. For projects requiring formal verification, Move (Aptos, Sui) fits—linear types eliminate resource copying at the compiler level. Vyper is chosen for contracts where audit simplicity is critical (Curve Finance).

Language Execution Model Typical Domain Risks
Solidity 0.8.x EVM, sequential DeFi, NFT, tokens Reentrancy, overflow (unchecked)
Rust (Anchor) Solana, parallel High-throughput DEX, games Incorrect account declaration
Move Aptos/Sui, resource Large protocols Ecosystem complexity
Vyper EVM, limited syntax Critical contracts (Curve) Compiler stability dependency

Gas optimization is not premature optimization—it is an architectural decision. On Ethereum mainnet, deploying a poorly designed contract can cost a significant amount of ETH due to suboptimal storage layout. Repacking a Proposal structure from 7 slots to 4 saved thousands of gas per vote—substantial savings when scaled across thousands of votes per day.

Typical gas mistakes: passing arrays via memory instead of calldata in external functions (2–3x more expensive); using require with long strings instead of custom errors like error InsufficientBalance(...). Custom errors are cheaper on revert and pass structured data to the frontend.

Why Smart Contract Audit Is Critical for Security

Audit is not a one-time check—it is a built-in development stage. We use three levels:

  1. Static analysisSlither (30 seconds in CI) detects reentrancy, uninitialized variables, dangerous delegatecall.
  2. Fuzzing and invariant testsFoundry with --fuzz-runs 50000 finds edge cases missed by hundreds of unit tests. Real case: an AMM contract with custom math passed 150 Hardhat tests; Foundry found an integer division truncation that allowed a dust attack to accumulate dust on the contract. Echidna checks invariants ("sum of all balances ≤ totalSupply").
  3. Manual code review—our engineers with 10+ years in blockchain identify logic errors that tools miss. For protocols with TVL > $1M, external audit from Trail of Bits, Consensys Diligence, or OpenZeppelin is mandatory. Timeline: 2–4 weeks.

Any upgradeable protocol must have a timelock. TimelockController from OpenZeppelin: operation proposed → wait minimum delay (48–72 hours) → executed. Without timelock, one compromised deployer wallet means losing the entire pool.

What Upgrade Patterns Do We Choose?

Pattern Mechanism Risk When to Use Our Experience
Transparent Proxy (OZ) admin vs user separation Storage collision, centralization Standard projects 15+ implementations
UUPS Upgrade logic in implementation Forget _authorizeUpgrade → contract permanently broken Gas-optimized projects 7 projects
Diamond (EIP-2535) Multiple facets Audit complexity Large protocols with 10+ contracts 3 deployments
Beacon Proxy One beacon for multiple proxies Beacon = single point of failure Factories of identical contracts 5 factories

Storage collision is the main danger of proxies. Implementation v2 must not add variables before existing ones. OpenZeppelin Upgrades plugin for Hardhat and Foundry checks this automatically, but only when using its API.

How to Protect a Contract from MEV and Front-Running

On Ethereum mainnet, transactions in the mempool are visible to all. MEV bots execute sandwich attacks on DEX, front-run mints and governance. Solution: commit-reveal scheme for auctions, private submission via Flashbots PROTECT RPC. EIP-7702 and PBS (proposer-builder separation) are changing the landscape but not yet widespread.

What Is the Development Process?

  1. Analysis—functional specification, call diagram, edge case analysis. Without this, coding starts in vain.
  2. Development—Solidity/Rust with tests in parallel. Test → code → refactoring. Use Foundry for fuzz and invariant tests.
  3. Internal audit—Slither + Echidna + manual code review. Foundry invariant tests for protocol invariants.
  4. External audit—for projects with real money. Timeline: 2–4 weeks.
  5. Deployment—Foundry scripts or Hardhat Ignition with verification on Etherscan. Gnosis Safe for ownership transfer immediately after deployment.
  6. Monitoring—Tenderly alerts, OpenZeppelin Defender, Forta Network.

What Is Included

  • Architecture documentation and contract specification (NatSpec).
  • Source code with repository and CI (Slither, Foundry, coverage).
  • Deployed contract with verification on blockchain explorer.
  • Audit results (internal and external upon request).
  • Access to monitoring and management (Gnosis Safe).
  • Code warranty: critical bug fixes within one month after deployment.
  • Consultation on web integration (wagmi, RainbowKit).

Estimated Timelines

  • ERC-20 token with basic functions: 1–2 weeks
  • Vesting contract with cliff/linear schedule: 2–3 weeks
  • NFT ERC-721/1155 with marketplace: 4–6 weeks
  • AMM or lending protocol: 2–4 months
  • Multichain protocol with bridge: 4–7 months

Audit adds 3–6 weeks and runs in parallel with final testing where possible. Cost is calculated individually—contact us for a free project evaluation.

Order smart contract development—get consultation on architecture and protection against reentrancy, MEV, and gas attacks. Want to discuss details? Write to us—we will select the optimal stack for your task.