Skip to content

Conversation

@devin-ai-integration
Copy link
Contributor

Pyth Examples Contribution

Type of Contribution

  • New Example Project (Adding a new example to demonstrate Pyth integration)
  • Bug Fix (Fixing an issue in existing examples)
  • Documentation Update (Improving README, comments, or guides)
  • Enhancement (Improving existing functionality or adding features)
  • Hackathon Submission (Submitting a project from a hackathon)

Project Information

Project/Example Name: Lottery with Pyth Entropy

Pyth Product Used:

  • Pyth Price Feeds
  • Pyth Entropy
  • Multiple Products
  • Other: ___________

Blockchain/Platform:

  • Ethereum/EVM (Blast Sepolia, Optimism Sepolia, Arbitrum Sepolia)
  • Solana
  • Aptos
  • Sui
  • Fuel
  • Starknet
  • TON
  • Other: ___________

Description

What does this contribution do?

This PR adds a complete lottery application example that demonstrates advanced usage of Pyth Entropy for provably fair random number generation. Unlike simple lottery implementations, this example ensures each ticket purchase draws its own unique random number from Pyth Entropy, and the winner is determined by which ticket's random number is closest to a final target random number.

The implementation includes:

  • Smart Contract (Lottery.sol): Implements lottery logic using IEntropyV2 interface
  • Frontend Application: Complete Next.js app with Web3 wallet integration
  • Three-Phase System: ACTIVE (ticket sales) → DRAWING (ending) → ENDED (winner selection)
  • Automatic Winner Selection: Contract automatically determines winner via callback

How does it integrate with Pyth?

The contract uses Pyth Entropy V2 (IEntropyV2) for verifiable randomness:

  1. Ticket Purchase: Each buyTicket() call triggers entropy.requestV2() to request a unique random number
  2. Entropy Callbacks: The contract implements IEntropyConsumer.entropyCallback() to receive random numbers
  3. Winner Determination: When the lottery ends, one final random number is requested as the "target", and the ticket with the closest random number wins
  4. Fee Handling: Contract calculates and collects Entropy fees via entropy.getFeeV2()

Key implementation detail: The callback function distinguishes between ticket random numbers and the final winning number using sequence number comparison.

What problem does it solve or demonstrate?

This example demonstrates:

  • Per-Ticket Randomness: Each participant gets verifiable proof of their random number
  • IEntropyV2 Usage: Shows how to use the latest Entropy interface with simplified requestV2() calls
  • Callback Handling: Properly implements the callback pattern for receiving randomness
  • State Management: Managing lottery phases and ticket data on-chain
  • Frontend Integration: Complete Web3 app showing real-time random number reveals

Directory Structure

entropy/lottery/
├── contract/                     # Hardhat project
│   ├── contracts/Lottery.sol     # Main lottery contract
│   ├── ignition/modules/         # Deployment scripts
│   └── README.md
├── app/                          # Next.js frontend
│   ├── app/(home)/
│   │   ├── components/           # Lottery UI components
│   │   └── page.tsx
│   ├── contracts/                # Generated ABIs and hooks
│   └── README.md
└── README.md                     # Main documentation

Testing & Verification

How to Test This Contribution

⚠️ IMPORTANT: This example has been compiled successfully but not tested end-to-end because it requires deployment to a testnet with Pyth Entropy support and waiting for real Entropy callbacks. Manual testing is required.

Prerequisites

  • Node.js v18+
  • Web3 wallet with testnet funds (Blast Sepolia, Optimism Sepolia, or Arbitrum Sepolia)
  • Private key for deployment

Setup & Deployment

  1. Deploy Contract:
cd entropy/lottery/contract
npm install
# Create .env with WALLET_KEY=your_private_key
npx hardhat compile  # ✓ Verified - compiles successfully
npx hardhat ignition deploy ignition/modules/Lottery.ts --network blast-sepolia
# Note deployed address
  1. Configure Frontend:
cd ../app
npm install
# Update contracts/addresses.ts with deployed address
npx wagmi generate
npm run dev
  1. Test Flow:
    • Connect wallet on http://localhost:3000
    • Buy 2-3 tickets (each ~0.001 ETH + Entropy fee)
    • Wait for random numbers to be revealed (~few seconds)
    • End lottery (owner only)
    • Wait for winner determination
    • Winner claims prize

Deployment Information

Networks Configured: Blast Sepolia, Optimism Sepolia, Arbitrum Sepolia

Entropy Addresses Used (from deployment module):

  • Entropy Contract: 0x98046Bd286715D3B0BC227Dd7a956b83D8978603 (Blast Sepolia)
  • Entropy Provider: 0x6CC14824Ea2918f5De5C2f75A9Da968ad4BD6344

Ticket Price: 0.001 ETH (configurable in deployment script)

Checklist

Code Quality

  • Code follows existing patterns in the repository (mirrors coin_flip and growing examples)
  • Proper error handling implemented (custom errors, ReentrancyGuard, Ownable)
  • No hardcoded values for deployment (uses .env, deployment module configuration)

Testing

  • Contract compiles successfully with Hardhat
  • Frontend builds successfully with Next.js
  • ⚠️ End-to-end testing pending - requires testnet deployment

Important Review Points

Critical Areas for Review

  1. Callback Logic (Lottery.sol:127-184):

    • Handles two cases: ticket random numbers vs final winning number
    • Winner selection loops through all tickets - could be gas-intensive with many tickets
    • Edge case: What happens if lottery ends before all ticket callbacks complete?
  2. Winner Calculation (Lottery.sol:236-240):

    function _calculateDifference(bytes32 a, bytes32 b) private pure returns (uint256) {
        uint256 aValue = uint256(a);
        uint256 bValue = uint256(b);
        return aValue > bValue ? aValue - bValue : bValue - aValue;
    }
    • Uses absolute difference - verify this is the desired algorithm
  3. IEntropyV2 Usage:

    • Uses requestV2() without user random number (relies on in-contract PRNG)
    • Security note: This trusts validator to generate randomness honestly
    • Confirm this aligns with Pyth's latest recommendations
  4. Edge Cases:

    • What if endLottery() is called with 0 tickets? ✓ Handled (reverts with NoTicketsSold)
    • What if winner's random number is still unfulfilled? ⚠️ They won't be selected (only fulfilled tickets considered)
  5. Gas Optimization:

    • Winner selection in callback could be expensive with 100+ tickets
    • Consider documenting gas limits or implementing chunked processing

Configuration Verification Needed

  • Verify Entropy contract addresses are correct for Blast Sepolia
  • Test that Entropy provider address is active and reliable
  • Confirm deployment configuration matches testnet requirements

Additional Context

Requested by: Jayant ([email protected]) / @jayantk
Session: https://app.devin.ai/sessions/f9d9e77ce0ca41f1a17358d6092311da

Key Requirements Met:

  • ✅ Each ticket draws a random number (not just one number at the end)
  • ✅ Uses IEntropyV2 interface as specified
  • ✅ Includes both smart contract and frontend
  • ✅ Placed in entropy/ directory

Notes for Reviewers:

  • This is a reference implementation for educational purposes
  • Real production lottery would need additional features (time limits, minimum tickets, etc.)
  • Frontend placeholder address (0x0000...) must be updated post-deployment
  • Documentation is comprehensive with setup instructions and technical details

Thank you for reviewing! Please pay special attention to the callback logic and edge cases around unfulfilled random numbers.

- Implement lottery smart contract using IEntropyV2
- Each ticket purchase draws a unique random number from Entropy
- Winner determined by closest random number to target
- Complete Next.js frontend with Web3 wallet integration
- Support for multiple testnets (Blast, Optimism, Arbitrum Sepolia)
- Comprehensive README with setup instructions and technical details

Co-Authored-By: Jayant <[email protected]>
@devin-ai-integration
Copy link
Contributor Author

🤖 Devin AI Engineer

I'll be helping with this pull request! Here's what you should know:

✅ I will automatically:

  • Address comments on this PR. Add '(aside)' to your comment to have me ignore it.
  • Look at CI failures and help fix them

Note: I can only respond to comments from users who have write access to this repository.

⚙️ Control Options:

  • Disable automatic comment and CI monitoring

@jayantk jayantk closed this Oct 28, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants