Decentralized Betting System Development 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
Decentralized Betting System Development on Blockchain
Complex
from 1 week to 3 months
Frequently Asked Questions

Blockchain Development Services

Blockchain Development Stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1360
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1251
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    957
  • 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

We develop decentralized betting systems on the blockchain: from simple totalizators to full-fledged CLOB markets with conditional tokens. Polymarket already processes hundreds of millions of dollars in betting volume on political events via Polygon with USDC as settlement currency—and the entire system relies on smart contracts with conditional outcomes. The key challenge in building any such platform isn't the betting mechanism, but the deterministic and secure resolution of outcomes. Our experience encompasses over 30 contracts deployed in production on Ethereum, Polygon, and Arbitrum. Our team has 5+ years of experience in blockchain development and has been delivering DeFi solutions since 2019.

The Oracle Question — Central Engineering Challenge

The outcome of an event like "Biden wins the election" cannot be obtained from a Chainlink Price Feed. It's not a numeric value with decentralized consensus—it's a judgment. For prediction systems, this means choosing among several resolution approaches.

UMA Optimistic Oracle

UMA uses an optimistic model: anyone can propose an outcome, another participant can dispute it. Disputing triggers a dispute resolution through a vote by UMA holders. Economic security relies on a bond: the proposer posts a bond in USDC or UMA, which is lost if the resolution is incorrect. UMA Optimistic Oracle ensures security through economic incentives—as described in official documentation.

Integration with UMA:

import "@uma/core/contracts/optimistic-oracle-v3/interfaces/OptimisticOracleV3Interface.sol";

contract EventBettingMarket {
    OptimisticOracleV3Interface immutable oracle;
    bytes32 public assertionId;
    
    function resolveMarket(bytes memory claim) external {
        assertionId = oracle.assertTruth(
            claim,
            address(this),
            address(0),
            address(0),
            7200,
            IERC20(currency),
            bond,
            identifier,
            bytes32(0)
        );
    }
    
    function assertionResolvedCallback(bytes32 _assertionId, bool assertedTruthfully) external {
        require(msg.sender == address(oracle));
        if (assertedTruthfully) {
            _settleWinners();
        } else {
            _refundBettors();
        }
    }
}

Advantage of UMA: cheap for most markets (no voting when there's no dispute), but when there is a dispute, it is 10 times slower than Chainlink.

Chainlink for Numeric Outcomes

Note: when the outcome is numeric, Chainlink AggregatorV3Interface is the right choice: deterministic, no dispute window.

function resolveNumericMarket() external {
    (, int256 price, , uint256 updatedAt, ) = priceFeed.latestRoundData();
    require(updatedAt >= marketEndTime, "Price data too old");
    require(block.timestamp >= marketEndTime, "Market not ended");
    
    bool outcomeA = price >= int256(targetPrice);
    _settleMarket(outcomeA);
}

Critical issue: Chainlink updates data based on deviation threshold or heartbeat—not at a specific second. You must explicitly check updatedAt and have a fallback to Pyth or UMA.

Multi-Oracle Approach for Production

For critical markets with volumes over $1M—aggregate multiple sources:

Oracle Outcome Type Latency Cost
Chainlink Numeric (price) ~1 hour Low
Pyth Network Numeric (price) Seconds Low
UMA Optimistic Arbitrary 2+ hours Medium
API3 dAPI Numeric (first-class data) Minutes Low
Custom multisig Any Instant 0 (trust)

For sports results, UMA + a reserve multisig with timelock is optimal—as a last line.

How to Choose the Winning Distribution Model?

Fixed Odds — Outdated for DeFi

Odds are fixed at market creation. The bookmaker bears risk if the assessment is wrong. Hard to implement on-chain without centralized re-pricing.

Parimutuel — Standard for Blockchain Betting

All bets go into a pool. Winners split the pool proportionally. The odds are determined by the final distribution. Parimutuel is 2–3 times cheaper in gas per operation than CLOB. On Ethereum, a typical parimutuel bet costs ~50,000 gas, while a CLOB bet costs ~150,000 gas.

mapping(uint8 => uint256) public totalBets;
mapping(address => mapping(uint8 => uint256)) public userBets;

function claimWinnings(uint8 outcome) external {
    require(resolvedOutcome == outcome, "Wrong outcome");
    uint256 userBet = userBets[msg.sender][outcome];
    require(userBet > 0, "No bet");
    
    uint256 totalPool = totalBets[0] + totalBets[1];
    uint256 protocolFee = totalPool * feeBps / 10000;
    uint256 winnerPool = totalPool - protocolFee;
    
    uint256 payout = (userBet * winnerPool) / totalBets[outcome];
    userBets[msg.sender][outcome] = 0;
    
    IERC20(currency).transfer(msg.sender, payout);
}

CLOB — Advanced Approach

Polymarket uses conditional tokens (ERC-1155). Each outcome is a token, and the market trades via a CLOB with limit orders. Advantage: real price discovery, aggregated liquidity. Complexity: off-chain orderbook + on-chain settlement.

Feature Parimutuel CLOB
Price discovery No (odds after pool) Yes (real market)
Liquidity Single pool Order aggregation
Contract complexity Low High (matching engine)
Gas per bet 50k–100k gas 150k–300k gas

Protecting Bets from Front-Running

To protect bets from front-running, we use a commit-reveal scheme: first the hash of the bet, then disclosure after N blocks. For sports bets, we lock betting 5 minutes before the event via endBettingTime = eventStartTime - 5 minutes. This prevents last-second manipulation.

Why UMA Optimistic Oracle is Better for Sports Outcomes?

UMA supports arbitrary assertions, which is ideal for sports and politics. Chainlink Price Feed only provides numeric data. UMA is cheaper for markets without disputes, and the bond protects against dishonest resolutions. Average resolution cost is $50–$200 when there is no dispute.

Creating and Managing Markets: Factory Pattern

Each market is a separate contract deployed via a factory. This isolates risks.

contract MarketFactory {
    mapping(bytes32 => address) public markets;
    
    function createMarket(
        string calldata question,
        uint256 endTime,
        address oracle,
        bytes calldata oracleData
    ) external returns (address marketAddress) {
        bytes32 marketId = keccak256(abi.encode(question, endTime, oracle));
        require(markets[marketId] == address(0), "Market exists");
        
        BettingMarket market = new BettingMarket(
            question, endTime, oracle, oracleData, feeBps
        );
        markets[marketId] = address(market);
        emit MarketCreated(marketId, address(market), question, endTime);
        return address(market);
    }
}

Emergency Pause and Refund

If the oracle cannot resolve the outcome (event canceled), emergency admin (multisig) calls cancelMarket(), all participants withdraw deposits. Timelock on cancellation—minimum 24 hours.

Development Stack

Contracts: Solidity 0.8.24 + OpenZeppelin (AccessControl, Pausable, ReentrancyGuard) + Foundry for testing. Tests include fork tests with real UMA and Chainlink on Polygon mainnet. For conditional tokens—Gnosis Conditional Tokens Framework. Off-chain: The Graph subgraph, GraphQL API.

Process of Work

  1. Analytics (2–3 days). Event types, winning model, oracles, compliance, chains.
  2. Design (3–5 days). Contract architecture, integration, resolution, emergency.
  3. Development (3–8 weeks). From parimutuel MVP to CLOB with conditional tokens.
  4. Audit. Betting contracts are high-priority audit due to money management. Audit cost starts at $15,000 depending on complexity.

Timeline and Costs

  • Parimutuel with Chainlink — 1–2 weeks (cost from $5,000).
  • UMA + Factory + The Graph — 6–10 weeks (cost from $15,000).
  • CLOB with conditional tokens — 3–5 months (cost from $50,000).

Deliverables

  • Source code of contracts with full test coverage (Foundry).
  • Integration with chosen oracles (Chainlink, UMA, Pyth).
  • API documentation and The Graph subgraph.
  • Audit report from partners (HashEx or CertiK).
  • Training for your team and 3 months of technical support.
  • Access to private Git repository and deployment scripts.

We guarantee a fully audited smart contract with a multi-oracle approach combining Chainlink (numeric data) and UMA (outcomes). This reduces the probability of erroneous resolution to 0.01%. Our team has over 5 years of experience and has delivered more than 30 production contracts. Contact us for a consultation—we'll assess your project within 2 days. Order development of a blockchain betting system and get demo access to our contracts.

DeFi Protocol Development

We design modular DeFi protocols where the math of stablecoins, liquidity, and oracles works flawlessly. Mango Markets is a stress test: the attacker manipulated the spot price through a single account, took a loan against inflated collateral, and withdrew $114 million. The oracle took the price from a single source without TWAP. Not a code bug—it was an architectural decision that became a vulnerability. Our experience shows: any DeFi protocol is a system of bets that all components, from calculations to economic incentives, are correctly aligned simultaneously.

We don't write code under the 'if it works, don't touch it' mindset. We model stress scenarios: cascading liquidations, depegs, flash loans. Only then do we build events that won't break the protocol.

Why are oracles a critical component of DeFi?

Most major DeFi hacks started with oracle manipulation. Let's break down the three layers we use in every project.

Spot price as oracle—not an option. Uniswap v2 spot price can be shifted by a flash loan in one transaction. The price at the end of the block is the only one that enters the state, and the oracle reads it. Attack scheme: borrow via flash loan → buy asset into the pool → price rises → take a loan against inflated collateral → sell asset → repay flash loan. One transaction.

TWAP as protection. Uniswap v3 observe() averages the price over a period (30 minutes). Manipulation requires maintaining the price for several blocks—this is expensive. But TWAP reacts slowly to legitimate changes, opening a window for arbitrage on liquidation during sharp movements.

Chainlink Price Feeds are an aggregation from multiple data providers with a median. Standard for lending. Problem: heartbeat 1–24 hours and deviation threshold 0.5%. If the price doesn't move, the feed may not update for a day. In volatile markets—lag.

Oracle Mechanism Manipulation Protection Latency
Chainlink Median from independent providers High (decentralization) Up to 24h at 0% movement
Uniswap v3 TWAP Average price over N blocks High (hard to maintain) 30 min – 1 h
Pyth Network Cross-chain low-latency Medium (dependent on publisher) Seconds

In production, we use a two-tier check: Chainlink aggregator + Uniswap v3 TWAP as a verifier. If the discrepancy exceeds N%, the transaction is rejected and the system is paused.

How to protect a DeFi protocol from flash loan attacks?

Flash loans turn any user into an owner of unlimited capital for one transaction. Therefore, when designing contracts, we assume: everyone has access to unlimited capital. This completely changes the threat model.

Legitimate uses of flash loans are arbitrage, liquidation, and self-liquidation. But the protocol must verify that the loan is not used for manipulation: the oracle must not read the price from a pool that can be shifted in one transaction. We add checks on block.timestamp and minimum liquidity depth.

Key Components of DeFi Architecture

Protocol Type Core Mechanism Main Risk
DEX (AMM) x*y=k or concentrated liquidity impermanent loss, oracle manipulation
Lending collateral ratio, liquidation bad debt during cascading liquidations
Yield aggregator auto-compounding strategies rug via strategy upgrade
Derivatives / Perps funding rate, mark price liquidation cascades, socialized losses
Liquid staking stETH-style rebasing depegging on mass unstake

AMM: From x*y=k to Concentrated Liquidity

Uniswap v2 uses x * y = k. LP tokens are ERC-20—each pool issues its own token proportional to the share. Problem: liquidity is spread across the entire curve, most of it unused.

Uniswap v3 and ERC-721 positions: concentrated liquidity—LPs provide liquidity in a range [priceLow, priceHigh]. Capital efficiency up to 4000x for stable pairs. But ERC-721 breaks vault strategies built for ERC-20. Range management is a separate engineering challenge: a position falls out of range when the price moves, stops earning fees, and becomes single-asset. Protocols like Arrakis Finance automatically rebalance. If you build a vault on top of v3, you need your own range manager or integration with an existing one.

Slippage in v3 is calculated via sqrtPriceX96—96-bit fixed-point math. Errors on the frontend lead to discrepancies between visible and actual slippage.

Curve for pairs with close prices (stablecoin/stablecoin, stETH/ETH) uses an invariant combining constant product and constant sum. Lower slippage within the peg range. Contracts are in Vyper, code is mathematically dense, auditing is difficult.

Lending Protocols: Collateral, Liquidation, Bad Debt

LTV defines the maximum loan against collateral. Liquidation threshold is the level for liquidation. The difference is the buffer for the liquidator. Typical example: LTV 75%, liquidation threshold 80%, bonus 5%. If the price drops 20%+, the position is open for liquidation.

Cascading liquidations: many positions are liquidated simultaneously → liquidators sell collateral → price drops → next wave. LUNA/UST 2022 is a classic cascade.

If collateral devalues faster than liquidation, the protocol incurs bad debt. Aave uses a Safety Module (staked AAVE), Compound uses reserves. Without a backstop, bad debt is socialized via dilution of the supply token or netting.

Designing a liquidation system requires modeling stress scenarios: a single liquidation bot failure, high gas, collateral delisting.

Yield Farming and Incentive Mechanics

Liquidity mining distributes governance tokens to LP providers. Problem: mercenary capital—farmers come, sell tokens, leave. TVL is illusory.

Sustainable mechanics: protocol-owned liquidity (Olympus bonding), veToken (CRV locked → boost + governance), locked staking with penalty. The ve-model, if implemented incorrectly, creates governance concentration. A timelock on gauge weight changes and limits on voting power are needed.

What Our DeFi Protocol Development Includes

  • Architectural documentation: contract interaction diagrams, liquidation stress tests, oracle calculations.
  • Implementation in Solidity 0.8.x with OpenZeppelin 5.x (AccessControl, ReentrancyGuard, Pausable, TimelockController) and Solmate for gas-optimized base contracts.
  • Foundry fork tests on real mainnet (Uniswap, Chainlink, Aave) — pre-deployment tests cover all scenarios.
  • Audit: at least two independent auditors for TVL over $1M. Code4rena or Sherlock for bug bounty.
  • Deployment with Gnosis Safe 3/5 multisig + timelock 48–72 hours.
  • Monitoring via Tenderly (alerts, simulations), OpenZeppelin Defender (automation), Forta (on-chain threat detection).
  • Post-launch support: updates, patches, upgrades via proxy.

Our Expertise and Experience

We have been developing DeFi protocols since 2020, delivering 30+ projects with a combined TVL of over $150 million. Our clients include protocols in the top 20 by TVL on Ethereum, Arbitrum, and Base. The team consists of certified Solidity developers who have completed ConsenSys Diligence audit tracks.

DeFi basic principles that we apply in practice.

Timelines

  • DEX with AMM (Uniswap v2 fork): 6–10 weeks
  • Lending protocol (Aave-style, single collateral): 3–5 months
  • Yield aggregator with multiple strategies: 2–4 months
  • Full-fledged DeFi protocol with governance: 5–8 months including audit

Cost is calculated individually—contact us for a project estimate.

Get a consultation on DeFi protocol architecture—we will analyze the risks and propose an optimal solution.