betting 0.2.6

A crate to manage twitch-style bets (aka 'Parimutuel betting')
Documentation
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
use crate::{utils, amount::Amount, BetError, AccountUpdate, Bet, AccountStatus, bet_connection::BetConnection, bet_transaction::BetTransaction, BetInfo, Position};
use rusqlite::{Connection, Result, Transaction, params};
use std::collections::HashMap;
use itertools::izip;

#[derive(Debug, Clone)]
pub struct Bets {
    db_path: String,
}

impl Bets {
    pub fn new(db_path: &str) -> Result<Self, BetError> {
        let conn = Connection::open(db_path)?;
        conn.execute(
            "CREATE TABLE IF NOT EXISTS Account (
                server INTEGER,
                user INTEGER,
                balance INTEGER NOT NULL,
                PRIMARY KEY(server, user)
            )",
            [],
        )?;
        conn.execute(
            "CREATE TABLE IF NOT EXISTS Bet (
                uuid INTEGER PRIMARY KEY,
                server INTEGER,
                author INTEGER NOT NULL,
                is_open INTEGER NOT NULL,
                desc TEXT
            )",
            [],
        )?;
        conn.execute(
            "CREATE TABLE IF NOT EXISTS Outcome (
                bet INTEGER,
                number INTEGER,
                desc TEXT,
                PRIMARY KEY(bet, number)
            )",
            [],
        )?;
        conn.execute(
            "CREATE TABLE IF NOT EXISTS Wager (
                bet INTEGER,
                outcome INTEGER,
                server INTEGER,
                user INTEGER,
                amount INTEGER NOT NULL,
                FOREIGN KEY(bet, outcome) REFERENCES Outcome(bet, number) ON DELETE CASCADE,
                FOREIGN KEY(server, user) REFERENCES Account(server, user) ON DELETE CASCADE,
                PRIMARY KEY(user, bet)
            )",
            [],
        )?;
        conn.execute(
            "CREATE TABLE IF NOT EXISTS ToDelete (
                bet INTEGER PRIMARY KEY REFERENCES Bet(uuid) ON DELETE CASCADE
            )",
            [],
        )?;
        conn.execute(
            "DELETE FROM Bet
            WHERE EXISTS (
                SELECT bet 
                FROM ToDelete 
                WHERE ToDelete.bet = Bet.uuid
            )",
            [],
        )?;
        Ok(Bets {
            db_path: db_path.to_string(),
        })
    }

    /// Creates an account if it doesn't already exist (will do nothing if it does)
    pub fn create_account(&self, server: u64, user: u64, amount: u64) -> Result<(), BetError> {
        let conn = Connection::open(&self.db_path)?;
        conn.execute(
            "INSERT OR IGNORE
            INTO Account (server, user, balance) 
            VALUES (?1, ?2, ?3)",
            [server, user, amount],
        )?;
        Ok(())
    }

    /// Will delete every bet from server and set every balance to the same amount
    pub fn reset(&self, server: u64, amount: u64) -> Result<(), BetError> {
        let mut conn = Connection::open(&self.db_path)?;
        let tx = conn.transaction()?;
        tx.execute(
            "DELETE
            FROM Bet
            WHERE server = ?1",
            [server],
        )?;
        tx.execute(
            "UPDATE Account
            SET balance = ?1
            WHERE server = ?2",
            [amount, server],
        )?;
        Ok(tx.commit()?)
    }

    pub fn global_income(&self, income: u64) -> Result<(), BetError> {
        let conn = Connection::open(&self.db_path)?;
        conn.execute(
            "UPDATE Account
            SET balance = balance + ?1", 
            [income]
        )?;
        Ok(())
    }

    pub fn income(&self, server: u64, income: u64) -> Result<Vec<AccountUpdate>, BetError> {
        let conn = Connection::open(&self.db_path)?;
        let mut stmt = conn.prepare(
            "UPDATE Account
            SET balance = balance + ?1
            WHERE server = ?2
            RETURNING server, user, balance"
        ).unwrap();
        let mut account_updates = Vec::new();
        let mut rows = stmt.query([server, income])?;
        while let Some(row) = rows.next()? {
            account_updates.push(AccountUpdate {
                server: row.get::<usize, u64>(0)?,
                user: row.get::<usize, u64>(1)?,
                balance: row.get::<usize, u64>(2)?,
                diff: income as i64,
            });
        }
        Ok(account_updates)
    }

    pub fn create_bet<S1, S2>(
        &self,
        bet_uuid: u64,
        server: u64,
        author: u64,
        desc: S1,
        outcomes: &[S2],
    ) -> Result<(), BetError>
    where S1: ToString, S2: ToString {
        let desc = desc.to_string();
        let mut conn = Connection::open(&self.db_path)?;
        let tx = conn.transaction()?;
        tx.execute(
            "INSERT 
            INTO Bet (uuid, server, author, is_open, desc) 
            VALUES (?1, ?2, ?3, ?4, ?5)",
            params![bet_uuid, server, author, 1, desc],
        )?;
        for (i, opt) in outcomes.into_iter().enumerate() {
            tx.execute(
                "INSERT 
                INTO Outcome (bet, number, desc) 
                VALUES (?1, ?2, ?3)",
                params![bet_uuid, i, opt.to_string()],
            )?;
        }
        Ok(tx.commit()?)
    }

    pub fn outcomes_of_bet(&self, bet: u64) -> Result<Vec<u64>, BetError> {
        let conn = Connection::open(&self.db_path)?;
        conn.outcomes_of_bet(bet)
    }

    pub fn bet_on<A>(
        &self,
        bet: u64,
        outcome: usize,
        user: u64,
        amount: A,
    ) -> Result<(AccountUpdate, Bet), BetError>
    where A: Into<Amount> {
        let amount: Amount = amount.into();
        let mut conn = Connection::open(&self.db_path)?;
        // check if the bet is open
        let bet_info = conn.bet_info(bet)?;
        if !bet_info.is_open {
            return Err(BetError::BetLocked);
        }
        conn.assert_bet_not_deleted(bet)?;
        // compute the amount to bet
        let balance = conn.balance(bet_info.server, user)?;
        let amount = match amount {
            Amount::FLAT(value) => {
                if value > balance {
                    return Err(BetError::NotEnoughMoney);
                }
                value
            },
            Amount::FRACTION(part) => {
                assert!(0. <= part && part <= 1.);
                let value = f32::ceil(balance as f32 * part) as u64;
                if value == 0 {
                    return Err(BetError::NotEnoughMoney);
                }
                value
            }
        };
        // bet
        let tx = conn.transaction()?;
        let acc_update = tx.change_balance(bet_info.server, user, -(amount as i64))?;
        tx.execute(
            "INSERT or ignore
            INTO Wager (bet, outcome, server, user, amount)
            VALUES (?1, ?2, ?3, ?4, ?5)",
            params![bet, outcome, bet_info.server, user, 0],
        )?;
        tx.execute(
            "UPDATE Wager
            SET amount = amount + ?1
            WHERE bet = ?2 AND outcome = ?3 AND user = ?4
            ",
            params![amount, bet, outcome, user],
        )?;
        tx.commit()?;
        Ok((
            acc_update,
            Bet {
                bet: bet.clone(),
                desc: bet_info.desc,
                outcomes: conn.outcomes_statuses(bet)?,
                is_open: bet_info.is_open,
                server: bet_info.server,
                author: bet_info.author,
            },
        ))
    }

    pub fn lock_bet(&self, bet: u64) -> Result<(), BetError> {
        let conn = Connection::open(&self.db_path)?;
        conn.execute(
            "UPDATE Bet
            SET is_open = 0
            WHERE uuid = ?1",
            [bet],
        )?;
        Ok(())
    }

    fn delete_bet(
        tx: &Transaction,
        bet: u64,
    ) -> Result<(), BetError> {
        tx.execute(
            "INSERT 
            INTO ToDelete (bet)
            VALUES (?1)",
            [bet],
        )?;
        tx.execute("DELETE FROM Wager
        WHERE bet = ?1
        ", [bet])?;
        Ok(())
    }

    pub fn abort_bet(&self, bet: u64) -> Result<Vec<AccountUpdate>, BetError> {
        let bet = bet;
        let mut conn = Connection::open(&self.db_path)?;
        conn.assert_bet_not_deleted(bet)?;
        let bet_info = conn.bet_info(bet)?;
        let outcomes = conn.outcomes_statuses(bet)?;
        let wagers: Vec<(u64, u64)> = outcomes
            .iter()
            .flat_map(|outcome_status| outcome_status.wagers.clone())
            .collect();
        let mut account_updates = Vec::new();
        let tx = conn.transaction()?;
        for (user, amount) in wagers {
            account_updates.push(tx.change_balance(bet_info.server, user, amount as i64)?);
        }
        // delete the bet
        Bets::delete_bet(
            &tx, bet
        )?;
        tx.commit()?;
        Ok(account_updates)
    }

    pub fn resolve(
        &self,
        bet: u64,
        winning_outcome: usize,
    ) -> Result<Vec<AccountUpdate>, BetError> {
        let mut conn = Connection::open(&self.db_path)?;
        let bet_info = conn.bet_info(bet)?;
        // retrieve the total of the bet and the winning parts
        conn.assert_bet_not_deleted(bet)?;
        let outcomes_statuses = conn.outcomes_statuses(bet)?;
        let mut winners: Vec<u64> = Vec::new();
        let mut wins: Vec<u64> = Vec::new();
        let mut total = 0;
        for (i, outcome_status) in outcomes_statuses.iter().enumerate() {
            let outcome_sum = outcome_status
                .wagers
                .iter()
                .fold(0, |init, wager| init + wager.1);
            total += outcome_sum;
            if i == winning_outcome {
                for (winner, win) in &outcome_status.wagers {
                    winners.push(*winner);
                    wins.push(*win);
                }
            }
        }
        // compute the gains for each winners
        let gains = utils::lrm(total, &wins);
        // update the accounts
        let mut account_updates = Vec::new();
        let tx = conn.transaction()?;
        for (user, gain) in izip!(winners, gains) {
            account_updates.push(tx.change_balance(bet_info.server, user, gain as i64)?);
        }
        // delete the bet
        Bets::delete_bet(&tx, bet)?;
        tx.commit()?;
        Ok(account_updates)
    }

    pub fn position(&self, user: u64, bet: u64) -> Result<Position, BetError> {
        let conn = Connection::open(&self.db_path)?;
        let (outcome, amount) = conn
        .prepare(
            "SELECT outcome, amount 
                FROM Wager
                WHERE user = ?1 AND bet = ?2
                ",
        )
        .unwrap().query_row([user, bet], |row| Ok((
            row.get::<usize, usize>(0)?, row.get::<usize, u64>(1)?
        )))?;
        Ok(Position { outcome, amount })
    }

    pub fn balance(&self, server: u64, user: u64) -> Result<u64, BetError> {
        let conn = Connection::open(&self.db_path)?;
        conn.balance(server, user)
    }

    pub fn account(&self, server: u64, user: u64) -> Result<AccountStatus, BetError> {
        let conn = Connection::open(&self.db_path)?;
        let balance = conn
        .prepare(
            "SELECT balance 
                FROM Account
                WHERE server = ?1 AND user = ?2
                ",
        )
        .unwrap().query_row([server, user], |row| row.get::<usize, u64>(0))?;
        let mut stmt = conn.prepare(
            "SELECT amount
            FROM Wager
            WHERE server = ?1 AND user = ?2"
        ).unwrap();
        let mut rows = stmt.query_map([server, user], |row| row.get::<usize, u64>(0))?;
        let mut in_bet = 0;
        while let Some(amount_res) = rows.next() {
            in_bet += amount_res?;
        }
        Ok(AccountStatus { user, balance, in_bet })
    }

    pub fn accounts(&self, server: u64) -> Result<Vec<AccountStatus>, BetError> {
        let conn = Connection::open(&self.db_path)?;
        // Map <user, balance>
        let mut accounts = HashMap::new();
        let mut stmt = conn
            .prepare(
                "SELECT user, balance 
                    FROM Account
                    WHERE server = ?1
                    ",
            )
            .unwrap();
        let mut rows = stmt.query([server])?;
        while let Some(row) = rows.next()? {
            accounts.insert(row.get::<usize, u64>(0)?, row.get::<usize, u64>(1)?);
        }
        // Map <user, total wagered>
        let mut stmt = conn
            .prepare(
                "SELECT user, amount 
                    FROM Wager
                    WHERE server = ?1",
            )
            .unwrap();
        let mut rows = stmt.query([server])?;
        let mut wagers = HashMap::new();
        while let Some(row) = rows.next()? {
            let user = row.get::<usize, u64>(0)?;
            let amount = match wagers.get(&user) {
                Some(amount) => *amount,
                None => 0,
            };
            wagers.insert(user, amount + row.get::<usize, u64>(1)?);
        }
        // return the account statuses
        Ok(accounts
            .into_iter()
            .map(|(user, balance)| AccountStatus {
                user: user,
                balance: balance,
                in_bet: *wagers.get(&user).unwrap_or(&0),
            })
            .collect())
    }

    pub fn get_info(&self, bet_uuid: u64) -> Result<BetInfo, BetError> {
        let conn = Connection::open(&self.db_path)?;
        conn.bet_info(bet_uuid)
    }
}