8000 GitHub - arkadia-park/1vs1-contract
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

arkadia-park/1vs1-contract

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

6 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐Ÿค  WesternShootout Smart Contract

License: MIT Network: Polygon Amoy

๐Ÿ“œ Overview

WesternShootout is a feature-rich smart contract that enables 1vs1 wagered gameplay with automated prize distribution, dispute resolution, and comprehensive player statistics tracking. The contract manages multiple concurrent game sessions, player matchmaking, and secure prize distribution while maintaining a complete history of games and player statistics on-chain.

Contract Address (Polygon AMOY): 0x17B6f309E57F684F643C4C3F8A91C6a8219C53f0

โœจ Key Features

  • ๐ŸŽฎ Multi-game Support: Run multiple concurrent games simultaneously
  • ๐Ÿ’ฐ Customizable Wagers: Each game can have its own wager amount
  • โฑ๏ธ Timeout Mechanism: Fair handling of abandoned or stalled games
  • โš–๏ธ Dispute Resolution: Contest results with arbiter voting system
  • ๐Ÿš€ Gas Optimized: Efficient data structures and operations
  • ๐Ÿ“Š On-chain Statistics: Comprehensive player performance tracking
  • ๐Ÿ” Game Discovery: Find games matching specific criteria
  • ๐Ÿ”„ Automatic Matchmaking: Join existing games or create new ones

๐Ÿ—๏ธ Contract Architecture

Game States

  • Waiting: New game waiting for players to join
  • Ready: Two players have joined, game is in progress
  • Completed: Game has ended with a winner declared
  • TimedOut: Game was abandoned and resolved via timeout
  • Disputed: Game outcome is being contested by a player

Core Components

1. Game Structure

Each game contains:

  • Unique game ID
  • Player addresses (player1 & player2)
  • Winner address
  • Wager amount
  • Fee amount
  • Current state
  • Timestamps (creation, ready state, dispute)
  • Dispute information and votes

2. Player Statistics

Tracks for each player:

  • Total wins
  • Total losses
  • Games played
  • Timeouts
  • Disputes initiated

3. Arbiter System

For dispute resolution:

  • List of approved arbiters
  • Voting mechanism
  • Dispute tracking
  • Resolution based on majority vote

๐ŸŽฏ Main Functions

For Players

Game Participation

  • joinGame(uint256 gameId): Join a specific game by ID
  • findAndJoinGame(): Automatically find or create a game matching your wager

Game Information

  • getPlayerGames(address player): Get all games a player is participating in
  • getGameDetails(uint256 gameId): Get complete information about a game
  • findAvailableGames(uint256 wagerAmount, uint256 limit): Find games with specific wager

Dispute Handling

  • initiateDispute(uint256 gameId): Contest the outcome of a completed game
  • getDisputeInfo(uint256 gameId): Get information about a dispute

For Game Operators

Game Management

  • createGame(uint256 wagerAmount): Create a new game with specified wager
  • createGames(uint256 count, uint256 wagerAmount): Create multiple games at once
  • declareWinner(uint256 gameId, address winner): Declare the winner of a game
  • cancelGame(uint256 gameId): Cancel an incomplete game and refund players

Configuration

  • setDefaultWager(uint256 newDefaultWager): Set the default wager amount
  • setGameTimeout(uint256 newTimeout): Set the timeout duration
  • setDisputeWindow(uint256 newWindow): Set the dispute window duration

Timeout Handling

  • resolveTimedOutGame(uint256 gameId): Resolve a game that has timed out
  • getTimedOutGames(uint256 limit): Get a list of games that have timed out
  • isGameTimedOut(uint256 gameId): Check if a specific game has timed out

For Arbiters

Dispute Resolution

  • voteOnDispute(uint256 gameId, address votedWinner, string calldata reason): Vote on a disputed game
  • getVoteDetails(uint256 gameId, uint256 voteIndex): Get details of a specific vote

Arbiter Management

  • addArbiter(address arbiter): Add a new arbiter (owner only)
  • removeArbiter(address arbiter): Remove an arbiter (owner only)
  • getArbiters(uint256 offset, uint256 limit): Get the list of arbiters

๐Ÿ“ก Events

The contract emits the following events:

  • GameCreated: When a new game is created
  • PlayerJoined: When a player joins a game
  • WinnerDeclared: When a winner is declared
  • GameTimedOut: When a game times out
  • DisputeInitiated: When a player initiates a dispute
  • DisputeVoteCast: When an arbiter votes on a dispute
  • DisputeResolved: When a dispute is resolved
  • ArbiterAdded: When a new arbiter is added
  • ArbiterRemoved: When an arbiter is removed

๐Ÿ”ง Integration Guide

Basic Integration

  1. Connect to the Contract
// Using ethers.js
const contractAddress = "0x17B6f309E57F684F643C4C3F8A91C6a8219C53f0";
const westernShootout = new ethers.Contract(contractAddress, WesternShootoutABI, provider);
  1. Create or Join a Game
// Create a new game with 0.01 POL wager
const tx = await westernShootout.createGame(ethers.utils.parseEther("0.01"));
await tx.wait();

// Or find and join a game with 0.01 POL wager
const tx = await westernShootout.findAndJoinGame({
  value: ethers.utils.parseEther("0.01")
});
await tx.wait();
  1. Monitor Game Events
// Listen for PlayerJoined events
westernShootout.on("PlayerJoined", (gameId, player) => {
  console.log(`Player ${player} joined game ${gameId}`);
});

// Listen for WinnerDeclared events
westernShootout.on("WinnerDeclared", (gameId, winner, payout, fee) => {
  console.log(`Game ${gameId} won by ${winner} with payout ${payout}`);
});
  1. Declare Winner
// Only callable by contract owner
const tx = await westernShootout.declareWinner(gameId, winnerAddress);
await tx.wait();

Advanced Integration

  1. Handle Timeouts
// Check if a game has timed out
const isTimedOut = await westernShootout.isGameTimedOut(gameId);

// Get time remaining before timeout
const timeRemaining = await westernShootout.getTimeRemaining(gameId);

// Resolve a timed out game (owner only)
if (isTimedOut) {
  const tx = await westernShootout.resolveTimedOutGame(gameId);
  await tx.wait();
}
  1. Dispute Resolution
// Initiate a dispute (must be a player in the game)
const tx = await westernShootout.initiateDispute(gameId);
await tx.wait();

// Vote on a dispute (must be an arbiter)
const tx = await westernShootout.voteOnDispute(gameId, playerAddress, "Evidence shows this player won");
await tx.wait();

// Get dispute information
const disputeInfo = await westernShootout.getDisputeInfo(gameId);
  1. Query Player Statistics
const playerStats = await westernShootout.playerStats(playerAddress);
console.log(`Wins: ${playerStats.wins}`);
console.log(`Losses: ${playerStats.losses}`);
console.log(`Games Played: ${playerStats.gamesPlayed}`);
console.log(`Timeouts: ${playerStats.timeouts}`);
console.log(`Disputes: ${playerStats.disputes}`);

๐ŸŽฎ Unreal Engine 5 Integration

WesternShootout is designed to integrate seamlessly with Unreal Engine 5 games using ThirdWeb Engine.

Setup with ThirdWeb Engine

  1. Initialize ThirdWeb Engine
// In your game initialization
void AMyGameMode::InitializeBlockchain()
{
    // Initialize ThirdWeb with Polygon Amoy network
    ThirdWebSubsystem = GEngine->GetEngineSubsystem<UThirdWebSubsystem>();
    ThirdWebSubsystem->Initialize(EChain::PolygonAmoy);
    
    // Connect to WesternShootout contract
    ContractAddress = TEXT("0x17B6f309E57F684F643C4C3F8A91C6a8219C53f0");
    ThirdWebSubsystem->ConnectToContract(ContractAddress, WesternShootoutABI);
}
  1. Create Blueprint Functions
// Create a game with wager
UFUNCTION(BlueprintCallable, Category = "Blockchain")
void CreateGame(float WagerAmount)
{
    FString FunctionName = TEXT("createGame");
    TArray<FString> Params;
    Params.Add(FString::Printf(TEXT("%f"), WagerAmount * 1e18)); // Convert to wei
    
    ThirdWebSubsystem->CallContractFunction(ContractAddress, FunctionName, Params, true);
}

// Join a game
UFUNCTION(BlueprintCallable, Category = "Blockchain")
void JoinGame(int32 GameId, float WagerAmount)
{
    FString FunctionName = TEXT("joinGame");
    TArray<FString> Params;
    Params.Add(FString::Printf(TEXT("%d"), GameId));
    
    ThirdWebSubsystem->CallContractFunction(
        ContractAddress, 
        FunctionName, 
        Params, 
        true, 
        WagerAmount * 1e18 // Value in wei
    );
}
  1. Listen for Events
// Set up event listeners
void AMyGameMode::SetupEventListeners()
{
    ThirdWebSubsystem->ListenForContractEvent(
        ContractAddress,
        TEXT("PlayerJoined"),
        FOnContractEventReceived::CreateUObject(this, &AMyGameMode::OnPlayerJoined)
    );
    
    ThirdWebSubsystem->ListenForContractEvent(
        ContractAddress,
        TEXT("WinnerDeclared"),
        FOnContractEventReceived::CreateUObject(this, &AMyGameMode::OnWinnerDeclared)
    );
}

// Event handler
void AMyGameMode::OnPlayerJoined(const FString& EventData)
{
    // Parse event data and update game state
    // ...
    
    // Update UI
    if (GameLobbyWidget)
    {
        GameLobbyWidget->UpdatePlayerList();
    }
}

Game Implementation Examples

Example: Western Duel Game

  1. Game Flow
Player enters lobby โ†’ Connects wallet โ†’ Creates/joins game โ†’ 
Waits for opponent โ†’ Plays duel โ†’ Winner determined โ†’ 
Result submitted to blockchain โ†’ Prizes distributed
  1. Timeout Handling
Game starts โ†’ Timer begins counting down โ†’ 
If player disconnects โ†’ Warning displayed โ†’ 
If timeout occurs โ†’ resolveTimedOutGame called โ†’ 
Players receive partial refunds
  1. Dispute Resolution
Game ends โ†’ Result declared โ†’ Losing player can dispute โ†’ 
Dispute evidence collected โ†’ Arbiters vote โ†’ 
Majority decision enforced โ†’ Winner receives prize

๐Ÿ” Security Features

  • โœ… Secure fund handling with proper balance checks
  • โœ… State validation to prevent invalid operations
  • โœ… Owner-only sensitive operations
  • โœ… Protected winner declaration
  • โœ… Automated fee calculation and distribution
  • โœ… Timeout protection against abandoned games
  • โœ… Dispute resolution for contested outcomes
  • โœ… Gas-optimized operations

๐Ÿงช Testing on Polygon Amoy

To interact with the contract on Polygon Amoy testnet:

  1. 633A

    Get Test POL

  2. Connect to Amoy Network

  3. Test Transactions

    • Start with small wager amounts
    • Monitor transaction status on the explorer
    • Check game state after each operation

๐Ÿ“š Development Resources

๐Ÿค Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ“ž Contact

For questions or support, please open an issue on this repository or contact us at:


Built with โค๏ธ by the Arkadia Park team

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published
0