# βοΈTime-Weighted Average Balance (TWAB)

Time-Weighted Average Balance (TWAB) plays a vital role in ensuring a fair experience for all users. Let's dive into TWAB and discover why it holds such significance in our protocol! πβ³

#### Calculating the Time-Weighted Average Balance

A user's TWAB is no ordinary metric; We take the time-weighted average balance between approximately one day before the draw and the commencement of the draw. Behold the magic in action! π§ββοΈ

Letβs take a look at the following example:

User | Amount Deposited | Duration | TWAB |
---|---|---|---|

User A | 10,000 | 1 day | 10,000 |

User B | 20,000 | 0.5 day | 10,000 |

User C | 10,000 | 0.1 day | 1,000 |

In this scenario, while User A and User B may have different staking amounts, their TWABs are the same because User A's duration is double that of User B's. As for User C, though the staking matches User A's, the shorter duration leads to a smaller TWAB! βοΈβ³

#### A Shield of Fairness: Protecting User Interest

TWAB safeguards the interest of users who have staked for a longer duration, and particularly those who have staked for the entire period before a given draw. By considering the time-weighted average balance, we aim to prevent users from gaming the protocol by making last-second stakings. The magic of fairness is ever-present in Kaching! ππ

### Calculating the number of picks

We calculate a user's picks in two steps:

First, we take the user's TWAB and compare it to the total deposits of CRO in Kaching between two timestamps. This gives us the user's normalized balance - their portion of contribution for the draw. A user can always query their normalized balance for previous draw IDs here.

Next, we consider the total number of picks in a draw. This is the sum of all userβs picks for a given draw. This can be queried for previous draws here. The total number of picks will always be the 7th number in the tuple.

Finally, we multiply the userβs normalized balance by the total number of picks in the draw, which gives us the userβs number of picks for a given draw.

### Generating the pseudo-random numbers

To generate unique numbers for each of a userβs picks, we:

1. Hash the user's address to get a unique base number.

2. Calculate the user's number of picks for the draw.

3. And for each pick:

- Take the base hash and the pick's sequence number as inputs to the hash function

- Hash them together to generate the unique number for that pick

- Repeat for all picks in sequence

So in summary, we hash the user's address once to get a base number. Then we hash that base with each pick's sequential number to generate a unique number per pick.

Last updated