Skip to content

Commit

Permalink
Merge pull request #386 from sge-network/docs/rephrase
Browse files Browse the repository at this point in the history
Docs / Rephrase spec docs
  • Loading branch information
3eyedraga authored Apr 24, 2024
2 parents 6110522 + 789ce50 commit 4569f41
Show file tree
Hide file tree
Showing 45 changed files with 651 additions and 464 deletions.
15 changes: 13 additions & 2 deletions docs/specs/Bet/01_Overview.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
# **Overview**

The Bet module is responsible for receiving and processing requests to wager and settle bets. In the case of wagering, it validates the request and places the bet.
The **Bet module** handles requests related to betting and bet settlement. Let's break it down:

For the settlement, blockchain automatically queries resolved markets then for each of these markets, checks the result of the market, determines the bet result, and settles the bet using `orderbook` module.
- **Wagering**:
- When a user places a bet, the Bet module validates the request.
- It then processes the bet and records it.

- **Settlement**:
- After a market is resolved, the blockchain automatically queries the results.
- For each market, the Bet module:
- Checks the outcome.
- Determines the bet result.
- Settles the bet using the `orderbook` module.

In summary, the Bet module ensures smooth betting interactions and accurate settlement based on market outcomes.
84 changes: 51 additions & 33 deletions docs/specs/Bet/02_Concepts.md
Original file line number Diff line number Diff line change
@@ -1,52 +1,70 @@
# **Concepts**

Bet module is tasked with placement and settlement of the bets. the user can place bet on a same market multiple times with different or equal odds through commandline or singing and broadcasting the bet placement message.
The **Bet module** is responsible for handling the placement and settlement of bets. Users can place bets on the same market multiple times, either with different or equal odds, using the command line or by singing and broadcasting the bet placement message.

> Wagering will be done using a ticket containing odds info signed by a trusted source. Verifying this ticket will be done in the placement state itself.
> Bet amount can not be less than a minimum amount which is defined for each market. A module parameter is used for this purpose.
> Also, a betting fee has been defined for each market, A module parameter is used for this purpose.
Here are some key points about the betting process:

1. **Wagering and Ticket Verification**:
- Wagering is facilitated through a ticket that contains odds information, signed by a trusted source.
- The verification of this ticket occurs during the placement state itself.

2. **Minimum Bet Amount**:
- Each market defines a minimum bet amount.
- Users cannot place bets below this minimum threshold.
- A module parameter controls this requirement.

3. **Betting Fee**:
- For each market, a specific betting fee has been established.
- Again, a module parameter governs this fee.

---

Before accepting bet some validation should take place:
**Before Accepting a Bet, Validation Steps:**

1. **Market-Level Validation:**
- Ensure the market is active for bet placement.
- Verify that the market is neither resolved nor canceled.
- Confirm that the bet amount (after deducting the betting fee) meets the minimum allowed bet amount.

- Market level validation:
- Market is active for bet placement.
- Market is not already resolved or canceled.
- Bet amount (deducted by betting fee) is not less than the minimum allowed bet amount.
- Bet level validation:
- Provided UUID is valid.
- Odds Value and the validations according to the American, British and decimal odds.
- Check if the max loss multiplier is positive and less than 1.
- OVM level validation:
- All data provided in placement request is valid e.g. odds value.
- KYC Validation:
- If Ignore is false in bet ticket payload, then the status of kyc approval should be true and tx signer and kyc id should be same for a bet to be placed.
- If Ignore is true in bet ticket payload, then kyc validation is not required and bet can be placed without kyc check.
2. **Bet-Level Validation:**
- Validate the provided UUID.
- Check odds values and apply validations based on American, British, and decimal odds.
- Ensure the max loss multiplier is positive and less than 1.

Wager Assumptions:
3. **OVM-Level Validation:**
- Validate all data provided in the placement request, including odds values.

- For bet placement user can raise a request to place a single bet, it can be done for a single bet only.
- When a user is raising a transaction to place a bet, the creator of the transaction is the owner of the bet.
4. **KYC Validation:**
- If the "Ignore" flag in the bet ticket payload is false:
- Verify that KYC approval status is true.
- Confirm that the transaction signer and KYC ID match for the bet to be placed.
- If the "Ignore" flag is true, KYC validation is not required, and the bet can proceed without further checks.

After a bet is accepted:
**Wager Assumptions:**

- Bet amount transfer to the `orderbook_liquidity_pool` module account this is done by the `orderbook` module.
- Betting fee will be transferred to the `bet_fee_collector` module account. this is done by the `orderbook` module.
- Bet fulfillments are being processed by `orderbook` module in the `ProcessWager` keeper's method.
- Users can request to place a single bet only.
- The creator of the transaction is considered the owner of the bet.

**After Bet Acceptance:**

- The bet amount is transferred to the `orderbook_liquidity_pool` module account by the `orderbook` module.
- Betting fees are transferred to the `bet_fee_collector` module account, also managed by the `orderbook` module.
- Bet fulfillments are processed by the `orderbook` module using the `ProcessWager` keeper's method.

## Supported Odds Types

> Note: Let bet_amount be 3564819
**Note:** Let `bet_amount` be 3,564,819.

- ***Decimal(European):*** Calculated as `bet_amount * oddsValue` ex. `3564819 * 1.29 = 4598616.51`.
- ***Fractional(British):*** Calculated as `bet_amount + (bet_amount * fraction)` ex. `3564819 + (3564819 * 2/7) = 4583338.71`.
- ***Moneyline(American):*** Calculated as:
- Positive odds value: `bet_amount + (bet_amount * |oddsValue/100|)` ex. `3564819 + 3564819 * |+350/100| = 16041685.50` the result will be rounded to floor.
- Negative odds value: `bet_amount + (bet_amount * |100/oddsValue|)` ex. `3564819 + 3564819 * |100/-350| = 4583338.71` the result will be rounded to floor.
- **Decimal (European):** Calculated as `bet_amount * oddsValue`. For example, `3,564,819 * 1.29 = 4,598,616.51`.
- **Fractional (British):** Calculated as `bet_amount + (bet_amount * fraction)`. For instance, `3,564,819 + (3,564,819 * 2/7) = 4,583,338.71`.
- **Moneyline (American):** Calculated as follows:
- For positive odds value: `bet_amount + (bet_amount * |oddsValue/100|)`. For instance, with odds of +350, `3,564,819 + 3,564,819 * |350/100| = 16,041,685.50` (rounded down).
- For negative odds value: `bet_amount + (bet_amount * |100/oddsValue|)`. For example, with odds of -350, `3,564,819 + 3,564,819 * |100/-350| = 4,583,338.71` (rounded down).

### Precision

Some of the Online Calculators round the division result to two-digit precision in Fractional and Moneyline calculations. In other words, these online calculators try to convert Moneyline and Fractional odds to Decimal odds and then calculate the payout according to the calculated rounded decimal value. This approach makes a big difference in the resulting payout. SGE-Network is accepting bets with usge that may have a high value in the market. For this kind of value, it is better to have a high-precision calculation in the blockchain code.
Some online calculators employ a two-digit precision when rounding division results in Fractional and Moneyline calculations. Specifically, these tools convert Moneyline and Fractional odds to Decimal odds and then compute the payout based on the rounded decimal value. This approach significantly impacts the resulting payout.

SGE-Network currently accepts bets with the `usge` currency, which may have substantial value in the market. For such high-value scenarios, it is advisable to perform high-precision calculations within the blockchain code.

> Note: The final calculated payout amounts are rounded to 2 digit float values, so we have a small portion of lost benefits/payouts.
> **Note:** The final calculated payout amounts are rounded to two-digit float values, resulting in a slight loss of benefits or payouts.
14 changes: 7 additions & 7 deletions docs/specs/Bet/03_Accounts.md
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
# **Accounts**
# **Account Details**

There is one account in the Bet module.
Within the Bet module, there exists a single account:

- Betting Fee Collector: This account holds the betting fee transferred from the bettor to the `bet_fee_collector` module account.
- **Betting Fee Collector**: This account receives the betting fee transferred from the bettor to the `bet_fee_collector` module account.

During bet placement, betting fee is transferred from the bettor's account to the bet module account in the Bet module.
When placing a bet, the betting fee is moved from the bettor's account to the bet module account in the Bet module.

## Wager Transfer

The bet amount (deducted by betting fee) is transferred to the `orderbook_liquidity_pool` module account in `orderbook` module.
The bet amount (after deducting the betting fee) is then transferred to the `orderbook_liquidity_pool` module account within the `orderbook` module.

## Settlement Transfer

- if the user is winner, the bet amount and payout profit will be transferred from `orderbook_liquidity_pool` module account to the winner's account.
- If the user is loser, the bet amount and fee will not go back to bettor's account.
- If the user is a winner, both the bet amount and the payout profit are transferred from the `orderbook_liquidity_pool` module account to the winner's account.
- However, if the user is a loser, the bet amount and fee remain with the bettor and do not return to their account.
25 changes: 12 additions & 13 deletions docs/specs/Bet/04_State.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,23 @@

## **KVStore**

State in bet module is defined by its KVStore. This KVStore has five prefixes:
The state in the bet module is defined by its **KVStore**. This KVStore consists of five prefixes:

1. All bets of a certain creator, using this pattern, blockchain is able to return list of all bets, bets of a certain creator and a single bet. The key prefix is created dynamically using this combination: `BetListPrefix`+`{Creator Address}`+`{Secuential Bet ID}`

2. Map of BetID and BetUID. this helps to get corresponding ID of the bet by issuing the UID. The keys are UIDs of bets and the values are sequencial generated IDs by blockchain.
3. Pending bets of a certain Market to help batch settlement.
4. Settled bets of a block height to keep track of the settled bets for the oracle services.
5. Bet statistics that contains the count of the total bets used to create next sequencial BetID.
1. **All Bets of a Certain Creator**: Using this pattern, the blockchain can retrieve a list of all bets, bets of a specific creator, and individual bets. The key prefix is dynamically created by combining `BetListPrefix`, the `{Creator Address}`, and the `{Sequential Bet ID}`.
2. **Mapping of BetID to BetUID**: This mapping helps retrieve the corresponding bet ID by issuing the UID. The keys represent UIDs of bets, and the values are sequentially generated IDs by the blockchain.
3. **Pending Bets of a Certain Market**: This prefix assists with batch settlement.
4. **Settled Bets of a Block Height**: Used to track settled bets for oracle services.
5. **Bet Statistics**: Contains the total count of bets, which is used to create the next sequential BetID.

The bet model in the Proto files is as below:

## **Params**

1. `batch_settlement_count`: is the count of bets to be automatically settlement in end-blocker.
2. `max_bet_by_uid_query_count`: is the max count of bets to be returned in the bets by uids query.
3. `constraints` contains criteria of the bet placement.
- `min_amount` minimum bet amount while placement.
- `fee` bet fee amount payable by bettor.
1. **`batch_settlement_count`** represents the number of bets that will be automatically settled during the end-blocker process.
2. **`max_bet_by_uid_query_count`** specifies the maximum number of bets to be returned in the query for bets by user IDs.
3. **`constraints`** section includes the criteria for placing bets:
- **`min_amount`**: This is the minimum bet amount required during placement.
- **`fee`**: The bet fee amount payable by the bettor.

```proto
// Params defines the parameters for the module.
Expand All @@ -40,7 +39,7 @@ message Params {

## **Constraints**

Holds bet placement constraints of the bet module.
Holds wager constraints of the bet module.

```proto
// Constraints is the bet constrains type for the bets
Expand Down
45 changes: 22 additions & 23 deletions docs/specs/Bet/05_State_Transitions.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
# **State Transitions**

This section defines the state transitions of the bet module's KVStore in all scenarios:
## **Wager State Transitions**

## **Wager**
When processing the wager, the following state transitions occur in the `Bet` module's KVStore:

When this is processed:

- If the ticket is valid a new bet will be created with the given data and will be added to the `Bet` module state.
- The pending bet, ID map and statistics will update accordingly.
- `orderbook` module bet placement processor will calculate and transfer bet amount and bet fee to the corresponding module accounts.
1. If the ticket is valid, a new bet is created using the provided data and added to the `Bet` module state.
2. The pending bet, ID map, and statistics are updated accordingly.
3. The `orderbook` module's bet placement processor calculates and transfers the bet amount and fee to the corresponding module accounts.

```go
newBet := &types.Bet{
Expand All @@ -29,44 +27,45 @@ newBet := &types.Bet{

---

## **Settle bet**
## **Bet Settlement Process**

When this is processed:
When processing a bet:

- If corresponding market is aborted or canceled, the bet will be updated in the `Bet` module state as below:
1. If the corresponding market is aborted or canceled, update the `Bet` module state as follows:

```go
bet.Result = types.Bet_RESULT_REFUNDED
bet.Status = types.Bet_STATUS_SETTLED
```

and the `RefundBettor` method of the `orderbook` module will be called to refund the bet amount and bet fee.
Additionally, invoke the `RefundBettor` method from the `orderbook` module to refund the bet amount and bet fee.

- Resolve the bet result based on the market result, and update field `Result` to indicate won or lost, and field `Status` to indicate result is declared. For Example:
2. Determine the bet result based on the market outcome. Update the `Result` field to indicate whether the bet was won or lost, and set the `Status` field to reflect that the result has been declared. For example:

```go
bet.Result = types.Bet_RESULT_WON // or types.Bet_RESULT_LOST
bet.Status = types.Bet_STATUS_RESULT_DECLARED
```

- Call `orderbook` module `BettorLoses` or `BettorWins` methods to unlock fund and payout user based on the bet's result, and update the bet's `Status` field to indicate it is settled:
3. Call the `BettorLoses` or `BettorWins` methods from the `orderbook` module to unlock funds and pay out users based on the bet result. Update the bet's `Status` field to indicate that it has been settled:
```go
bet.Status = types.Bet_STATUS_SETTLED
```
- If the market result is declared, the `WithdrawBetFee` method of the `orderbook` module is being called and transfers the bet fee to the market creator's account balance.
- Store the updated bet in the state.
4. If the market result is declared, invoke the `WithdrawBetFee` method from the `orderbook` module to transfer the bet fee to the market creator's account balance.

5. Finally, store the updated bet information in the state.

---

## **Batch bet settlement**
## Batch Bet Settlement

Batch bet settlement happens in the end-blocker of the bet module:
Batch bet settlement occurs during the final block of the bet module. Follow these steps:

1. Get resolved markets that have the unsettled bets.
- for each market:
1. Settle the bets one by by querying the market bets.
2. Remove the resolved market from the list if there is no more active bet.
3. Call orderbook's win/lose methods to transfer the appropriate amounts.
2. Check the `BatchSettlementCount` parameter of bet module and let the rest of bets for the nex block.
1. Identify resolved markets that still have unsettled bets.
- For each market:
1. Settle the bets by querying the market's bet data.
2. If there are no more active bets in the market, remove it from the list.
3. Use the orderbook's win/lose methods to transfer the appropriate amounts.
2. Verify the `BatchSettlementCount` parameter in the bet module and handle the remaining bets in the next block.
55 changes: 28 additions & 27 deletions docs/specs/Bet/06_Messages.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# **Messages**

In this section, we describe the processing of the Bet messages. the transaction message
handler endpoints is as follows
In this section, we delve into the handling of Bet messages. The endpoints for transaction message handlers are outlined below.

```proto
// Msg defines the Msg service.
Expand All @@ -13,7 +12,7 @@ service Msg {

## **MsgWager**

Within this message, the user specifies the bet information they wish to place.
In this message, users provide the details of the bet they want to place.

```proto
// MsgWager defines a message to place a bet with the given data
Expand Down Expand Up @@ -71,27 +70,29 @@ message MsgWagerResponse { WagerProps props = 1; }
}
```

### **Wager Failure cases**

The transaction will fail if:

- Basic validation fails:
- Invalid creator address
- Empty or invalid bet UID
- Empty amount
- Non positive amount
- Empty or invalid ticket (containing space)
- Provided bet UID is already set
- Empty or invalid odds UID in ticket
- Empty, negative or invalid odds value in ticket
- There is no any market with the given marketUID
- The market is not active for accepting bet (it's not active or status in not `PENDING`)
- The market has expired
- The market does not contain the selected odds
- Bet amount is less than minimum allowed amount
- The creator address is not valid
- There is an error in `ProcessWager` in `orderbook` module

### **What Happens if bet placement fails**

- The input data will not be stored in the `Bet` module and a meaningfull error will be returned to the client.
### **Possible Reasons for Wager Failure**

The transaction may fail due to the following reasons:

1. **Basic Validation Failures**:
- Invalid creator address
- Empty or invalid bet UID
- Empty amount
- Non-positive amount
- Empty or invalid ticket (containing spaces)

2. **Specific Conditions**:
- Provided bet UID is already set
- Empty or invalid odds UID in the ticket
- Empty, negative, or invalid odds value in the ticket
- No market exists with the given market UID
- The market is not active for accepting bets (status is not `PENDING`)
- The market has expired
- The market does not contain the selected odds
- Bet amount is less than the minimum allowed amount
- The creator address is not valid
- An error occurs in the `ProcessWager` function within the `orderbook` module

### **Handling Failed Bet Placement**

If bet placement fails, the input data will not be stored in the `Bet` module. Instead, a meaningful error message will be returned to the client.
2 changes: 1 addition & 1 deletion docs/specs/Bet/07_Events.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# **Events**

The Bet module emits the following events
The **Bet module** generates the subsequent events:

## *MsgWager*

Expand Down
2 changes: 1 addition & 1 deletion docs/specs/House/01_Overview.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
# **Overview**

The House module facilitates users to participate as a house for a specific market.
The **House module** enables users to **act as a representative** for a particular market.
Loading

0 comments on commit 4569f41

Please sign in to comment.