-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsportsBetting.sol
97 lines (76 loc) · 3.05 KB
/
sportsBetting.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// SPDX-License-Identifier: MIT
////**** Write a Solidity function to implement a decentralized sports betting platform,
// where users can bet on the outcome of sports events such as football and basketball games ****////
pragma solidity ^0.8.20;
contract SportsBetting{
address public owner;
uint private eventOutcome;
bool public isSettled;
struct Bet{
address bettor;
uint amount;
uint predictedOutcome; // we can use intergers to represent diff outComes;
bool claimed;
}
mapping(uint=>Bet[]) public bets;
event NewBetPlaced(address indexed bettor, uint eventId, uint predictedOutcome, uint amount);
event EventSettled(uint eventId, uint outcome);
modifier OnlyOwner(){
require(owner==msg.sender,"you are not a owner");
_;
}
constructor (){
owner=msg.sender;
}
function placeBet(uint _eventId, uint _predictedOutcome) public payable{
require(!isSettled,"Betting for this event is closed");
require(msg.value > 0,"Amount must be greater than 0");
bets[_eventId].push(Bet({
bettor: msg.sender,
amount: msg.value,
predictedOutcome: _predictedOutcome,
claimed: false
}));
emit NewBetPlaced(msg.sender, _eventId, _predictedOutcome, msg.value);
}
function settleBet(uint _eventId, uint _Outcome) public OnlyOwner{
require(!isSettled,"Betting for this event is closed");
eventOutcome = _Outcome;
isSettled = true;
emit EventSettled(_eventId, _Outcome);
}
function ClaimWinning(uint _eventId) external{
require(isSettled==true,"This betting event is not settled yet");
require(bets[_eventId].length >= 2,"minimum two bettors required");
uint winningAmount = 0;
address payable winner;
address payable loser;
bool isTie= false;
for(uint i=0; i<bets[_eventId].length; i++){
Bet storage bet = bets[_eventId][i];
if(bet.predictedOutcome == eventOutcome && !bet.claimed){
if(winner == address(0)){
winner = payable(bet.bettor);
winningAmount = bet.amount * 2; // Sum up the winning amounts (assuming 1:1 odds)
} else{
loser=payable(bet.bettor);
isTie = true;
}
bet.claimed = true;
}
}
require(winningAmount > 0 || isTie ,"No winning bets for this outcome");
if(winningAmount > 0 && !isTie){
winner.transfer(winningAmount);
loser.transfer(0);
} else if(isTie){
for(uint i=0; i<bets[_eventId].length; i++){
Bet storage bet = bets[_eventId][i];
if(!bet.claimed){
bet.claimed = true;
}
payable(bet.bettor).transfer(bet.amount); //Return the bet amount to each player in a tie
}
}
}
}