forked from tradingbootcamp/platform
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.rs
More file actions
2449 lines (2182 loc) · 83.9 KB
/
db.rs
File metadata and controls
2449 lines (2182 loc) · 83.9 KB
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::{env, fmt::Display, path::Path, str::FromStr};
use futures::TryStreamExt;
use futures_core::stream::BoxStream;
use itertools::Itertools;
use rand::{distributions::WeightedIndex, prelude::Distribution};
use rust_decimal::{Decimal, RoundingStrategy};
use rust_decimal_macros::dec;
use sqlx::{
sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions, SqliteSynchronous},
types::{time::OffsetDateTime, Text},
Connection, FromRow, Sqlite, SqliteConnection, SqlitePool, Transaction,
};
use tokio::sync::broadcast::error::RecvError;
use tracing::instrument;
use crate::websocket_api;
// should hopefully keep the WAL size nice and small and avoid blocking writers
const CHECKPOINT_PAGE_LIMIT: i64 = 512;
#[derive(Clone, Debug)]
pub struct DB {
pool: SqlitePool,
}
type SqlxResult<T> = Result<T, sqlx::Error>;
impl DB {
#[instrument(err)]
pub async fn init() -> anyhow::Result<Self> {
let connection_options = SqliteConnectOptions::from_str(&env::var("DATABASE_URL")?)?
.create_if_missing(true)
.journal_mode(SqliteJournalMode::Wal)
.synchronous(SqliteSynchronous::Normal)
// This should work with the default idle timeout and max lifetime
.optimize_on_close(true, None)
.pragma("optimize", "0x10002")
// already checkpointing in the background
.pragma("wal_autocheckpoint", "0");
let mut management_conn = SqliteConnection::connect_with(&connection_options).await?;
// Ignore missing to enable migration squashing
let mut migrator = sqlx::migrate::Migrator::new(Path::new("./migrations")).await?;
migrator
.set_ignore_missing(true)
.run(&mut management_conn)
.await?;
let (release_tx, mut release_rx) = tokio::sync::broadcast::channel(1);
let pool = SqlitePoolOptions::new()
.min_connections(8)
.max_connections(64)
.after_release(move |_, _| {
let release_tx = release_tx.clone();
Box::pin(async move {
if let Err(e) = release_tx.send(()) {
tracing::error!("release_tx.send failed: {:?}", e);
};
Ok(true)
})
})
.connect_with(connection_options)
.await?;
// checkpointing task
tokio::spawn(async move {
let mut released_connections = 0;
let mut remaining_pages = 0;
loop {
match release_rx.recv().await {
Ok(()) => {
released_connections += 1;
}
#[allow(clippy::cast_possible_wrap)]
Err(RecvError::Lagged(n)) => {
released_connections += n as i64;
}
Err(RecvError::Closed) => {
break;
}
};
let approx_wal_pages = remaining_pages + released_connections * 8;
if approx_wal_pages < CHECKPOINT_PAGE_LIMIT {
continue;
}
match sqlx::query_as::<_, WalCheckPointRow>("PRAGMA wal_checkpoint(PASSIVE)")
.fetch_one(&mut management_conn)
.await
{
Err(e) => {
tracing::error!("wal_checkpoint failed: {:?}", e);
}
Ok(row) => {
released_connections = 0;
remaining_pages = row.log - row.checkpointed;
tracing::info!(
"wal_checkpoint: busy={} log={} checkpointed={}",
row.busy,
row.log,
row.checkpointed
);
}
}
}
});
Ok(Self { pool })
}
#[instrument(err, skip(self))]
pub async fn get_account(&self, account_id: i64) -> SqlxResult<Option<Account>> {
sqlx::query_as!(
Account,
r#"SELECT id, name, kinde_id IS NOT NULL as "is_user: bool" FROM account WHERE id = ?"#,
account_id
)
.fetch_optional(&self.pool)
.await
}
#[instrument(err, skip(self))]
pub async fn redeem(
&self,
fund_id: i64,
redeemer_id: i64,
amount: Decimal,
) -> SqlxResult<RedeemStatus> {
if amount.scale() > 2 || amount.is_zero() {
return Ok(RedeemStatus::InvalidAmount);
}
let (mut transaction, transaction_info) = self.begin_write().await?;
let redeemables =
sqlx::query!(r#"SELECT * FROM "redeemable" WHERE "fund_id" = ?"#, fund_id)
.fetch_all(transaction.as_mut())
.await?;
if redeemables.is_empty() {
return Ok(RedeemStatus::MarketNotRedeemable);
}
let settled = sqlx::query_scalar!(
r#"SELECT EXISTS (SELECT 1 FROM market JOIN redeemable ON (market.id = fund_id or market.id = constituent_id) WHERE fund_id = ? AND settled_price IS NOT NULL) as "exists!: bool""#,
fund_id
).fetch_one(transaction.as_mut())
.await?;
if settled {
return Ok(RedeemStatus::MarketSettled);
}
let fund_position_change = -amount;
let amount = Text(amount);
sqlx::query!(
r#"INSERT INTO "redemption" ("redeemer_id", "fund_id", "transaction_id", "amount") VALUES (?, ?, ?, ?)"#,
redeemer_id,
fund_id,
transaction_info.id,
amount
).execute(transaction.as_mut())
.await?;
let Text(current_fund_position) = sqlx::query_scalar!(
r#"SELECT position as "position: Text<Decimal>" FROM "exposure_cache" WHERE "account_id" = ? AND "market_id" = ?"#,
redeemer_id,
fund_id,
)
.fetch_optional(transaction.as_mut())
.await?
.unwrap_or_default();
let new_fund_position = Text(current_fund_position + fund_position_change);
sqlx::query!(
r#"INSERT INTO exposure_cache (account_id, market_id, position, total_bid_size, total_offer_size, total_bid_value, total_offer_value) VALUES (?, ?, ?, '0', '0', '0', '0') ON CONFLICT DO UPDATE SET position = ?"#,
redeemer_id,
fund_id,
new_fund_position,
new_fund_position
).execute(transaction.as_mut()).await?;
for redeemable in redeemables {
let constituent_position_change = amount.0 * Decimal::from(redeemable.multiplier);
let Text(current_exposure) = sqlx::query_scalar!(
r#"SELECT position as "position: Text<Decimal>" FROM "exposure_cache" WHERE "account_id" = ? AND "market_id" = ?"#,
redeemer_id,
redeemable.constituent_id,
)
.fetch_optional(transaction.as_mut())
.await?
.unwrap_or_default();
let new_exposure = Text(current_exposure + constituent_position_change);
sqlx::query!(
r#"INSERT INTO exposure_cache (account_id, market_id, position, total_bid_size, total_offer_size, total_bid_value, total_offer_value) VALUES (?, ?, ?, '0', '0', '0', '0') ON CONFLICT DO UPDATE SET position = ?"#,
redeemer_id,
redeemable.constituent_id,
new_exposure,
new_exposure
).execute(transaction.as_mut()).await?;
}
let Text(redeem_fee) = sqlx::query_scalar!(
r#"SELECT redeem_fee as "redeem_fee: Text<Decimal>" FROM market WHERE id = ?"#,
fund_id
)
.fetch_one(transaction.as_mut())
.await?;
let Some(portfolio) = get_portfolio(&mut transaction, redeemer_id).await? else {
return Ok(RedeemStatus::RedeemerNotFound);
};
if portfolio.available_balance < redeem_fee {
return Ok(RedeemStatus::InsufficientFunds);
}
let new_balance = Text(portfolio.total_balance - redeem_fee);
sqlx::query!(
r#"UPDATE account SET balance = ? WHERE id = ?"#,
new_balance,
redeemer_id,
)
.execute(transaction.as_mut())
.await?;
transaction.commit().await?;
Ok(RedeemStatus::Success { transaction_info })
}
#[instrument(err, skip(self))]
pub async fn create_account(
&self,
user_id: i64,
owner_id: i64,
account_name: String,
) -> SqlxResult<CreateAccountStatus> {
if account_name.trim().is_empty() {
return Ok(CreateAccountStatus::EmptyName);
}
let mut transaction = self.pool.begin().await?;
let result = sqlx::query_scalar!(
r#"INSERT INTO account (name, balance) VALUES (?, '0') RETURNING id"#,
account_name
)
.fetch_one(transaction.as_mut())
.await;
let is_valid_owner = owner_id == user_id
|| sqlx::query_scalar!(
r#"SELECT EXISTS(SELECT 1 FROM account_owner WHERE account_id = ? AND owner_id = ?) as "exists!: bool""#,
owner_id,
user_id
)
.fetch_one(transaction.as_mut())
.await?;
if !is_valid_owner {
return Ok(CreateAccountStatus::InvalidOwner);
}
match result {
Ok(account_id) => {
sqlx::query!(
r#"INSERT INTO account_owner (owner_id, account_id) VALUES (?, ?)"#,
owner_id,
account_id
)
.execute(transaction.as_mut())
.await?;
transaction.commit().await?;
Ok(CreateAccountStatus::Success(Account {
id: account_id,
name: account_name,
is_user: false,
}))
}
Err(sqlx::Error::Database(db_err)) => {
if db_err.message().contains("UNIQUE constraint failed") {
transaction.rollback().await?;
Ok(CreateAccountStatus::NameAlreadyExists)
} else {
Err(sqlx::Error::Database(db_err))
}
}
Err(e) => Err(e),
}
}
#[instrument(err, skip(self))]
pub async fn share_ownership(
&self,
existing_owner_id: i64,
of_account_id: i64,
to_account_id: i64,
) -> SqlxResult<ShareOwnershipStatus> {
let owner_is_user = sqlx::query_scalar!(
r#"SELECT EXISTS(SELECT 1 FROM account WHERE id = ? AND kinde_id IS NOT NULL) as "exists!: bool""#,
existing_owner_id
)
.fetch_one(&self.pool)
.await?;
if !owner_is_user {
return Ok(ShareOwnershipStatus::OwnerNotAUser);
}
let is_direct_owner = sqlx::query_scalar!(
r#"SELECT EXISTS(SELECT 1 FROM account_owner WHERE owner_id = ? AND account_id = ?) as "exists!: bool""#,
existing_owner_id,
of_account_id
)
.fetch_one(&self.pool)
.await?;
if !is_direct_owner {
return Ok(ShareOwnershipStatus::NotOwner);
}
let recipient_is_user = sqlx::query_scalar!(
r#"SELECT EXISTS(SELECT 1 FROM account WHERE id = ? AND kinde_id IS NOT NULL) as "exists!: bool""#,
to_account_id
)
.fetch_one(&self.pool)
.await?;
if !recipient_is_user {
return Ok(ShareOwnershipStatus::RecipientNotAUser);
}
let res = sqlx::query!(
r#"INSERT INTO account_owner (account_id, owner_id) VALUES (?, ?) ON CONFLICT DO NOTHING"#,
of_account_id,
to_account_id
)
.execute(&self.pool)
.await?;
if res.rows_affected() == 0 {
Ok(ShareOwnershipStatus::AlreadyOwner)
} else {
Ok(ShareOwnershipStatus::Success)
}
}
#[instrument(err, skip(self))]
pub async fn get_owned_accounts(&self, user_id: i64) -> SqlxResult<Vec<i64>> {
sqlx::query_scalar!(
r#"SELECT ao2.account_id as "account_id!" FROM account_owner ao1 JOIN account_owner ao2 ON ao1.account_id = ao2.owner_id WHERE ao1.owner_id = ? UNION SELECT account_id FROM account_owner WHERE owner_id = ? UNION SELECT ?"#,
user_id,
user_id,
user_id
)
.fetch_all(&self.pool)
.await
}
#[instrument(err, skip(self))]
pub async fn ensure_user_created<'a>(
&self,
kinde_id: &str,
requested_name: Option<&str>,
initial_balance: Decimal,
) -> SqlxResult<EnsureUserCreatedStatus> {
let balance = Text(initial_balance);
// First try to find user by kinde_id
let existing_user = sqlx::query!(
r#"SELECT id as "id!", name FROM account WHERE kinde_id = ?"#,
kinde_id
)
.fetch_optional(&self.pool)
.await?;
if let Some(user) = existing_user {
if requested_name.is_none_or(|requested_name| user.name == requested_name) {
return Ok(EnsureUserCreatedStatus::Unchanged { id: user.id });
}
}
let Some(requested_name) = requested_name else {
return Ok(EnsureUserCreatedStatus::NoNameProvidedForNewUser);
};
let conflicting_account = sqlx::query!(
r#"SELECT id FROM account WHERE name = ? AND (kinde_id != ? OR kinde_id IS NULL)"#,
requested_name,
kinde_id
)
.fetch_optional(&self.pool)
.await?;
let final_name = if conflicting_account.is_some() {
format!("{}-{}", requested_name, &kinde_id[3..10])
} else {
requested_name.to_string()
};
let id = sqlx::query_scalar!(
"INSERT INTO account (kinde_id, name, balance) VALUES (?, ?, ?) ON CONFLICT DO UPDATE SET name = ? RETURNING id",
kinde_id,
final_name,
balance,
final_name,
)
.fetch_one(&self.pool)
.await?;
Ok(EnsureUserCreatedStatus::CreatedOrUpdated {
id,
name: final_name,
})
}
/// # Errors
/// Fails is there's a database error
pub async fn get_portfolio(&self, account_id: i64) -> SqlxResult<Option<Portfolio>> {
let mut transaction = self.pool.begin().await?;
match get_portfolio_with_credits(&mut transaction, account_id).await {
Ok(result) => {
transaction.commit().await?;
Ok(result)
}
Err(sqlx::Error::Database(db_err)) => {
// Probably credits need to be updated
tracing::warn!("get portfolio database error: {db_err:?}");
let mut transaction = self.pool.begin().await?;
// Ensure write mode with a no-op write query
sqlx::query!(r#"INSERT INTO "transaction" (id) VALUES (0) ON CONFLICT DO NOTHING"#)
.execute(transaction.as_mut())
.await?;
let result = get_portfolio_with_credits(&mut transaction, account_id).await;
transaction.commit().await?;
result
}
Err(error) => Err(error),
}
}
#[must_use]
pub fn get_all_accounts(&self) -> BoxStream<SqlxResult<Account>> {
sqlx::query_as!(
Account,
r#"SELECT id, name, kinde_id IS NOT NULL as "is_user: bool" FROM account"#
)
.fetch(&self.pool)
}
#[instrument(err, skip(self))]
pub async fn get_all_markets(&self) -> SqlxResult<Vec<MarketWithRedeemables>> {
let markets = sqlx::query_as!(Market, r#"SELECT market.id as id, name, description, owner_id, transaction_id, "transaction".timestamp as transaction_timestamp, min_settlement as "min_settlement: _", max_settlement as "max_settlement: _", settled_price as "settled_price: _", redeem_fee as "redeem_fee: _" FROM market join "transaction" on (market.transaction_id = "transaction".id) ORDER BY market.id"#)
.fetch_all(&self.pool)
.await?;
let redeemables = sqlx::query_as!(
Redeemable,
r#"SELECT fund_id, constituent_id, multiplier FROM redeemable ORDER BY fund_id"#
)
.fetch_all(&self.pool)
.await?;
let redeemables_chunked = redeemables
.into_iter()
.chunk_by(|redeemable| redeemable.fund_id);
markets
.into_iter()
.merge_join_by(redeemables_chunked.into_iter(), |market, (fund_id, _)| {
market.id.cmp(fund_id)
})
.map(|joined| {
let (left, right) = joined.left_and_right();
let Some(market) = left else {
return Err(sqlx::Error::RowNotFound);
};
Ok(MarketWithRedeemables {
market,
redeemables: right
.map(|(_, redeemables)| redeemables.collect())
.unwrap_or_default(),
})
})
.collect()
}
#[must_use]
pub fn get_all_live_orders(&self) -> BoxStream<SqlxResult<Order>> {
sqlx::query_as!(Order, r#"SELECT id as "id!", market_id, owner_id, transaction_id, size as "size: _", price as "price: _", side as "side: _" FROM "order" WHERE CAST(size AS REAL) > 0 ORDER BY market_id"#)
.fetch(&self.pool)
}
#[must_use]
pub fn get_all_transactions(&self) -> BoxStream<SqlxResult<TransactionInfo>> {
sqlx::query_as!(
TransactionInfo,
r#"SELECT id, timestamp FROM "transaction" ORDER BY id"#
)
.fetch(&self.pool)
}
#[instrument(err, skip(self))]
pub async fn get_live_market_orders(&self, market_id: i64) -> SqlxResult<Vec<Order>> {
sqlx::query_as!(Order, r#"SELECT id as "id!", market_id, owner_id, transaction_id, size as "size: _", price as "price: _", side as "side: _" FROM "order" WHERE market_id = ? AND CAST(size AS REAL) > 0"#, market_id)
.fetch_all(&self.pool)
.await
}
#[instrument(err, skip(self))]
pub async fn get_market_trades(&self, market_id: i64) -> SqlxResult<GetMarketTradesStatus> {
if !self.market_exists(market_id).await? {
return Ok(GetMarketTradesStatus::MarketNotFound);
};
let trades = sqlx::query_as!(Trade, r#"SELECT t.id as "id!", t.market_id, t.buyer_id, t.seller_id, t.transaction_id, t.size as "size: _", t.price as "price: _", tr.timestamp as "transaction_timestamp" FROM trade t JOIN "transaction" tr ON t.transaction_id = tr.id WHERE t.market_id = ?"#, market_id)
.fetch_all(&self.pool)
.await?;
Ok(GetMarketTradesStatus::Success(trades))
}
#[instrument(err, skip(self))]
pub async fn get_full_market_orders(
&self,
market_id: i64,
) -> SqlxResult<GetMarketOrdersStatus> {
if !self.market_exists(market_id).await? {
return Ok(GetMarketOrdersStatus::MarketNotFound);
};
let mut transaction = self.pool.begin().await?;
let orders = sqlx::query_as!(
Order,
r#"SELECT id as "id!", market_id, owner_id, transaction_id, size as "size: _", price as "price: _", side as "side: _" FROM "order" WHERE market_id = ? ORDER BY id"#,
market_id
)
.fetch_all(transaction.as_mut())
.await?;
let sizes = sqlx::query_as!(
Size,
r#"SELECT transaction_id, order_id, size as "size: _" FROM order_size WHERE order_id IN (SELECT id FROM "order" WHERE market_id = ?) ORDER BY order_id"#,
market_id
)
.fetch_all(transaction.as_mut())
.await?;
let orders = orders
.into_iter()
.zip_eq(sizes.into_iter().chunk_by(|size| size.order_id).into_iter())
.map(|(order, (order_id, sizes))| {
debug_assert_eq!(order_id, order.id);
let sizes = sizes.collect();
(order, sizes)
})
.collect();
Ok(GetMarketOrdersStatus::Success(orders))
}
#[instrument(err, skip(self))]
pub async fn get_transfers(&self, account_id: i64) -> SqlxResult<Vec<Transfer>> {
sqlx::query_as!(Transfer, r#"
SELECT transfer.id as "id!", initiator_id, from_account_id, to_account_id, transaction_id, amount as "amount: _", note, "transaction".timestamp as "transaction_timestamp"
FROM transfer
JOIN "transaction" ON (transfer.transaction_id = "transaction".id)
WHERE from_account_id = ? OR to_account_id = ?"#,
account_id,
account_id)
.fetch_all(&self.pool)
.await
}
#[instrument(err, skip(self))]
pub async fn market_exists(&self, id: i64) -> SqlxResult<bool> {
sqlx::query_scalar!(
r#"SELECT EXISTS(SELECT 1 FROM market WHERE id = ?) as "exists!: bool""#,
id
)
.fetch_one(&self.pool)
.await
}
#[instrument(err, skip(self))]
pub async fn make_transfer(
&self,
initiator_id: i64,
from_account_id: i64,
to_account_id: i64,
amount: Decimal,
note: &str,
) -> SqlxResult<MakeTransferStatus> {
if from_account_id == to_account_id {
return Ok(MakeTransferStatus::SameAccount);
}
let amount = amount.normalize();
if amount <= dec!(0) || amount.scale() > 4 {
return Ok(MakeTransferStatus::InvalidAmount);
}
let (mut transaction, transaction_info) = self.begin_write().await?;
let initiator_is_user = sqlx::query_scalar!(
r#"SELECT EXISTS(SELECT 1 FROM account WHERE id = ? AND kinde_id IS NOT NULL) as "exists!: bool""#,
initiator_id
)
.fetch_one(transaction.as_mut())
.await?;
if !initiator_is_user {
return Ok(MakeTransferStatus::InitiatorNotUser);
}
let Some(from_account_portfolio) =
get_portfolio_with_credits(&mut transaction, from_account_id).await?
else {
return Ok(MakeTransferStatus::FromAccountNotFound);
};
if from_account_portfolio.available_balance < amount {
return Ok(MakeTransferStatus::InsufficientFunds);
}
let Some(to_account_portfolio) =
get_portfolio_with_credits(&mut transaction, to_account_id).await?
else {
return Ok(MakeTransferStatus::ToAccountNotFound);
};
let is_user_to_user_transfer =
initiator_id == from_account_id && to_account_portfolio.owner_credits.is_empty();
if let Some(withdrawal_owner_credit) = from_account_portfolio
.owner_credits
.iter()
.find(|credit| credit.owner_id == to_account_id)
{
if withdrawal_owner_credit.credit.0 < amount {
return Ok(MakeTransferStatus::InsufficientCredit);
}
let new_credit = withdrawal_owner_credit.credit.0 - amount;
if let Some(status) = execute_credit_transfer(
&mut transaction,
initiator_id,
&to_account_portfolio,
&from_account_portfolio,
new_credit,
)
.await?
{
return Ok(status);
}
} else if let Some(deposit_owner_credit) = to_account_portfolio
.owner_credits
.iter()
.find(|credit| credit.owner_id == from_account_id)
{
let new_credit = deposit_owner_credit.credit.0 + amount;
if let Some(status) = execute_credit_transfer(
&mut transaction,
initiator_id,
&from_account_portfolio,
&to_account_portfolio,
new_credit,
)
.await?
{
return Ok(status);
}
} else if !is_user_to_user_transfer {
return Ok(MakeTransferStatus::AccountNotOwned);
}
let from_account_new_balance = Text(from_account_portfolio.total_balance - amount);
let to_account_new_balance = Text(to_account_portfolio.total_balance + amount);
sqlx::query!(
r#"UPDATE account SET balance = ? WHERE id = ?"#,
from_account_new_balance,
from_account_id
)
.execute(transaction.as_mut())
.await?;
sqlx::query!(
r#"UPDATE account SET balance = ? WHERE id = ?"#,
to_account_new_balance,
to_account_id
)
.execute(transaction.as_mut())
.await?;
let amount = Text(amount);
let transfer = sqlx::query_as!(
Transfer,
r#"INSERT INTO transfer (initiator_id, from_account_id, to_account_id, transaction_id, amount, note) VALUES (?, ?, ?, ?, ?, ?) RETURNING id, initiator_id, from_account_id, to_account_id, transaction_id, ? as "transaction_timestamp!: _", amount as "amount: _", note"#,
initiator_id,
from_account_id,
to_account_id,
transaction_info.id,
amount,
note,
transaction_info.timestamp
)
.fetch_one(transaction.as_mut())
.await?;
transaction.commit().await?;
Ok(MakeTransferStatus::Success(transfer))
}
#[instrument(err, skip(self))]
pub async fn create_market(
&self,
name: &str,
description: &str,
owner_id: i64,
mut min_settlement: Decimal,
mut max_settlement: Decimal,
redeemable_for: &[websocket_api::Redeemable],
mut redeem_fee: Decimal,
) -> SqlxResult<CreateMarketStatus> {
if redeemable_for
.iter()
.any(|redeemable| redeemable.multiplier == 0)
{
return Ok(CreateMarketStatus::InvalidMultiplier);
}
let (mut transaction, transaction_info) = self.begin_write().await?;
if !redeemable_for.is_empty() {
if redeem_fee < Decimal::ZERO {
return Ok(CreateMarketStatus::InvalidRedeemFee);
}
min_settlement = Decimal::ZERO;
max_settlement = Decimal::ZERO;
for redeemable in redeemable_for {
let Some(constituent) = sqlx::query!(
r#"SELECT min_settlement as "min_settlement: Text<Decimal>", max_settlement as "max_settlement: Text<Decimal>", settled_price IS NOT NULL as "settled: bool" FROM market WHERE id = ?"#,
redeemable.constituent_id
)
.fetch_optional(transaction.as_mut())
.await? else {
return Ok(CreateMarketStatus::ConstituentNotFound);
};
if constituent.settled {
return Ok(CreateMarketStatus::ConstituentSettled);
}
// Handle negative multipliers correctly
let min_settlement_payout =
constituent.min_settlement.0 * Decimal::from(redeemable.multiplier);
let max_settlement_payout =
constituent.max_settlement.0 * Decimal::from(redeemable.multiplier);
min_settlement += min_settlement_payout.min(max_settlement_payout);
max_settlement += min_settlement_payout.max(max_settlement_payout);
}
} else if !redeem_fee.is_zero() {
return Ok(CreateMarketStatus::InvalidRedeemFee);
}
min_settlement = min_settlement.normalize();
max_settlement = max_settlement.normalize();
redeem_fee = redeem_fee.normalize();
if min_settlement >= max_settlement {
return Ok(CreateMarketStatus::InvalidSettlements);
}
if min_settlement.scale() > 2 || max_settlement.scale() > 2 {
return Ok(CreateMarketStatus::InvalidSettlements);
}
if max_settlement.mantissa() > 1_000_000_000_000
|| min_settlement.mantissa() > 1_000_000_000_000
{
return Ok(CreateMarketStatus::InvalidSettlements);
}
if redeem_fee.scale() > 4 || redeem_fee.mantissa() > 1_000_000_000_000 {
return Ok(CreateMarketStatus::InvalidRedeemFee);
}
let min_settlement = Text(min_settlement);
let max_settlement = Text(max_settlement);
let redeem_fee = Text(redeem_fee);
let market = sqlx::query_as!(
Market,
r#"INSERT INTO market (name, description, owner_id, transaction_id, min_settlement, max_settlement, redeem_fee) VALUES (?, ?, ?, ?, ?, ?, ?) RETURNING id, name, description, owner_id, transaction_id, ? as "transaction_timestamp!: _", min_settlement as "min_settlement: _", max_settlement as "max_settlement: _", settled_price as "settled_price: _", redeem_fee as "redeem_fee: _""#,
name,
description,
owner_id,
transaction_info.id,
min_settlement,
max_settlement,
redeem_fee,
transaction_info.timestamp
)
.fetch_one(transaction.as_mut())
.await?;
let mut redeemables = Vec::new();
for redeemable in redeemable_for {
let redeemable = sqlx::query_as!(
Redeemable,
r#"INSERT INTO redeemable (fund_id, constituent_id, multiplier) VALUES (?, ?, ?) RETURNING fund_id, constituent_id, multiplier as "multiplier: _""#,
market.id,
redeemable.constituent_id,
redeemable.multiplier,
)
.fetch_one(transaction.as_mut())
.await?;
redeemables.push(redeemable);
}
transaction.commit().await?;
Ok(CreateMarketStatus::Success(MarketWithRedeemables {
market,
redeemables,
}))
}
#[instrument(err, skip(self))]
pub async fn settle_market(
&self,
id: i64,
mut settled_price: Decimal,
owner_id: i64,
) -> SqlxResult<SettleMarketStatus> {
let (mut transaction, transaction_info) = self.begin_write().await?;
let mut market = sqlx::query_as!(
Market,
r#"SELECT market.id as id, name, description, owner_id, transaction_id, "transaction".timestamp as transaction_timestamp, min_settlement as "min_settlement: _", max_settlement as "max_settlement: _", settled_price as "settled_price: _", redeem_fee as "redeem_fee: _" FROM market join "transaction" on (market.transaction_id = "transaction".id) WHERE market.id = ? AND owner_id = ?"#,
id,
owner_id
)
.fetch_one(transaction.as_mut())
.await?;
if market.settled_price.is_some() {
return Ok(SettleMarketStatus::AlreadySettled);
}
if market.owner_id != owner_id {
return Ok(SettleMarketStatus::NotOwner);
}
let constituent_settlements = sqlx::query!(
r#"SELECT settled_price as "settled_price: Text<Decimal>", multiplier FROM redeemable JOIN market ON (constituent_id = market.id) WHERE fund_id = ?"#,
id
)
.fetch_all(transaction.as_mut())
.await?;
if !constituent_settlements.is_empty() {
if let Some(constituent_sum) = constituent_settlements
.iter()
.map(|c| c.settled_price.map(|p| p.0 * Decimal::from(c.multiplier)))
.sum::<Option<Decimal>>()
{
settled_price = constituent_sum;
} else {
return Ok(SettleMarketStatus::ConstituentNotSettled);
};
}
let settled_price = settled_price.normalize();
if settled_price.scale() > 2 {
return Ok(SettleMarketStatus::InvalidSettlementPrice);
}
if market.min_settlement.0 > settled_price || market.max_settlement.0 < settled_price {
return Ok(SettleMarketStatus::InvalidSettlementPrice);
}
let settled_price = Text(settled_price);
sqlx::query!(
r#"UPDATE market SET settled_price = ? WHERE id = ?"#,
settled_price,
id,
)
.execute(transaction.as_mut())
.await?;
market.settled_price = Some(settled_price);
let canceled_orders = sqlx::query_scalar!(
r#"UPDATE "order" SET size = '0' WHERE market_id = ? AND CAST(size AS REAL) > 0 RETURNING id"#,
id
)
.fetch_all(transaction.as_mut())
.await?;
for canceled_order_id in canceled_orders {
sqlx::query!(
r#"INSERT INTO order_size (order_id, transaction_id, size) VALUES (?, ?, '0')"#,
canceled_order_id,
transaction_info.id
)
.execute(transaction.as_mut())
.await?;
}
let account_positions = sqlx::query!(
r#"DELETE FROM exposure_cache WHERE market_id = ? RETURNING account_id, position as "position: Text<Decimal>""#,
id
)
.fetch_all(transaction.as_mut())
.await?;
for account_position in &account_positions {
let Text(current_balance) = sqlx::query_scalar!(
r#"SELECT balance as "balance: Text<Decimal>" FROM account WHERE id = ?"#,
account_position.account_id
)
.fetch_one(transaction.as_mut())
.await?;
let new_balance = Text(current_balance + account_position.position.0 * settled_price.0);
sqlx::query!(
r#"UPDATE account SET balance = ? WHERE id = ?"#,
new_balance,
account_position.account_id
)
.execute(transaction.as_mut())
.await?;
}
transaction.commit().await?;
let affected_accounts = account_positions
.into_iter()
.map(|row| row.account_id)
.collect();
Ok(SettleMarketStatus::Success {
affected_accounts,
transaction_info,
})
}
#[instrument(err, skip(self))]
pub async fn create_order(
&self,
market_id: i64,
owner_id: i64,
price: Decimal,
size: Decimal,
side: Side,
) -> SqlxResult<CreateOrderStatus> {
let price = price.normalize();
let size = size.normalize();
if price.scale() > 2 || price.mantissa() > 1_000_000_000_000 {
return Ok(CreateOrderStatus::InvalidPrice);
}
if size <= dec!(0) || size.scale() > 2 || size.mantissa() > 1_000_000_000_000 {
return Ok(CreateOrderStatus::InvalidSize);
}
let (mut transaction, transaction_info) = self.begin_write().await?;
let market = sqlx::query!(
r#"SELECT min_settlement as "min_settlement: Text<Decimal>", max_settlement as "max_settlement: Text<Decimal>", settled_price IS NOT NULL as "settled: bool" FROM market WHERE id = ?"#,
market_id
)
.fetch_optional(transaction.as_mut())
.await?;
let Some(market) = market else {
return Ok(CreateOrderStatus::MarketNotFound);
};
if market.settled {
return Ok(CreateOrderStatus::MarketSettled);
}
if price < market.min_settlement.0 || price > market.max_settlement.0 {
return Ok(CreateOrderStatus::InvalidPrice);
}
update_exposure_cache(
&mut transaction,
true,
&OrderFill {
id: 0,
owner_id,
market_id,
size_filled: Decimal::ZERO,
size_remaining: size,
price,
side,
},
)
.await?;
let portfolio = get_portfolio(&mut transaction, owner_id).await?;
let Some(portfolio) = portfolio else {
return Ok(CreateOrderStatus::AccountNotFound);
};
if portfolio.available_balance.is_sign_negative() {
return Ok(CreateOrderStatus::InsufficientFunds);
}