Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add bet payout hook #7

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions app/src/lib/types/pocketbase.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export enum Collections {
Mfas = '_mfas',
Otps = '_otps',
Superusers = '_superusers',
BetPool = 'betPool',
Bets = 'bets',
Events = 'events',
Standings = 'standings',
Expand Down Expand Up @@ -89,6 +90,15 @@ export type SuperusersRecord = {
verified?: boolean;
};

export type BetPoolRecord = {
amount?: number;
created?: IsoDateString;
event: RecordIdString;
id: string;
team: RecordIdString;
updated?: IsoDateString;
};

export type BetsRecord = {
amount: number;
created?: IsoDateString;
Expand Down Expand Up @@ -128,6 +138,7 @@ export type EventsRecord = {
id: string;
location: string;
sport: EventsSportOptions;
standingsUpdated?: boolean;
startTime: IsoDateString;
teams: RecordIdString[];
title: string;
Expand Down Expand Up @@ -175,6 +186,8 @@ export type MfasResponse<Texpand = unknown> = Required<MfasRecord> & BaseSystemF
export type OtpsResponse<Texpand = unknown> = Required<OtpsRecord> & BaseSystemFields<Texpand>;
export type SuperusersResponse<Texpand = unknown> = Required<SuperusersRecord> &
AuthSystemFields<Texpand>;
export type BetPoolResponse<Texpand = unknown> = Required<BetPoolRecord> &
BaseSystemFields<Texpand>;
export type BetsResponse<Texpand = unknown> = Required<BetsRecord> & BaseSystemFields<Texpand>;
export type EventsResponse<Texpand = unknown> = Required<EventsRecord> & BaseSystemFields<Texpand>;
export type StandingsResponse<Texpand = unknown> = Required<StandingsRecord> &
Expand All @@ -190,6 +203,7 @@ export type CollectionRecords = {
_mfas: MfasRecord;
_otps: OtpsRecord;
_superusers: SuperusersRecord;
betPool: BetPoolRecord;
bets: BetsRecord;
events: EventsRecord;
standings: StandingsRecord;
Expand All @@ -203,6 +217,7 @@ export type CollectionResponses = {
_mfas: MfasResponse;
_otps: OtpsResponse;
_superusers: SuperusersResponse;
betPool: BetPoolResponse;
bets: BetsResponse;
events: EventsResponse;
standings: StandingsResponse;
Expand All @@ -219,6 +234,7 @@ export type TypedPocketBase = PocketBase & {
collection(idOrName: '_mfas'): RecordService<MfasResponse>;
collection(idOrName: '_otps'): RecordService<OtpsResponse>;
collection(idOrName: '_superusers'): RecordService<SuperusersResponse>;
collection(idOrName: 'betPool'): RecordService<BetPoolResponse>;
collection(idOrName: 'bets'): RecordService<BetsResponse>;
collection(idOrName: 'events'): RecordService<EventsResponse>;
collection(idOrName: 'standings'): RecordService<StandingsResponse>;
Expand Down
12 changes: 12 additions & 0 deletions app/src/routes/api/user/bet/+server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,18 @@ const handlePOST: RequestHandler = async ({ request, locals }) => {
.create({ user: locals.user.id, team: teamId, event: eventId, amount });
}

let betPool = (
await pb.collection('betPool').getFullList({
filter: `team="${teamId}" && event="${eventId}"`
})
).at(0);

if (betPool) {
await pb.collection('betPool').update(betPool.id, { amount: betPool.amount + amount });
Copy link
Contributor

@Radian6405 Radian6405 Jan 11, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if the amount is a string here the bets amount gets added as a string (amount is any rn not a number)
so consecutive bets of 10 lead betPool.amount + amount to become 1010

also same issue in line 38 for bet.amount + amount

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point, I've added validation middleware using zod.

} else {
await pb.collection('betPool').create({ event: eventId, team: teamId, amount });
}

await pb.collection('users').update(userid, { balance: locals.user.balance - amount });
return json(newBet);
};
Expand Down
52 changes: 52 additions & 0 deletions db/hooks/bet_status_update.pb.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
onRecordUpdate((e) => {
const event = e.record;
if (!event.getBool("standingsUpdated")) {
return e.next();
}

const winners = $app
.findAllRecords(
"standings",
$dbx.exp("position == 1 AND event == {:id}", { id: event.id })
)
.map((standing) => standing.get("team"));

const bets = $app.findAllRecords(
"bets",
$dbx.exp("event == {:id}", { id: event.id })
);

const wonBets = bets.filter((bet) => winners.includes(bet.get("team")));

const betPools = $app.findAllRecords(
"betPool",
$dbx.exp("event == {:id}", { id: event.id })
);

let totalPool = 0;
let wonPool = 0;

// one passTM
for (const betPool of betPools) {
totalPool += betPool.getInt("amount");
if (winners.includes(betPool.get("team")))
wonPool += betPool.getInt("amount");
}

if (wonPool === 0) {
return e.next();
}

for (const bet of wonBets) {
const amount = bet.getInt("amount");
const payout = Math.floor((amount * totalPool) / wonPool);

// not using the user expands on bets since it might have stale data (which means money could be disappearing)
// does this make things safe from race conditions? i hope so
const user = $app.findRecordById("users", bet.get("user"));
user.set("balance", user.getInt("balance") + payout);
$app.save(user);
}

e.next();
}, "events");
95 changes: 95 additions & 0 deletions db/migrations/1735284047_collections_snapshot.js
Original file line number Diff line number Diff line change
Expand Up @@ -926,6 +926,15 @@ migrate((app) => {
"thumbs": [],
"type": "file"
},
{
"hidden": false,
"id": "bool847678146",
"name": "standingsUpdated",
"presentable": false,
"required": false,
"system": false,
"type": "bool"
},
{
"hidden": false,
"id": "autodate2990389176",
Expand Down Expand Up @@ -1230,6 +1239,92 @@ migrate((app) => {
"type": "base",
"updateRule": null,
"viewRule": null
},
{
"createRule": null,
"deleteRule": null,
"fields": [
{
"autogeneratePattern": "[a-z0-9]{15}",
"hidden": false,
"id": "text3208210256",
"max": 15,
"min": 15,
"name": "id",
"pattern": "^[a-z0-9]+$",
"presentable": false,
"primaryKey": true,
"required": true,
"system": true,
"type": "text"
},
{
"cascadeDelete": false,
"collectionId": "pbc_1687431684",
"hidden": false,
"id": "relation1001261735",
"maxSelect": 1,
"minSelect": 0,
"name": "event",
"presentable": false,
"required": true,
"system": false,
"type": "relation"
},
{
"cascadeDelete": false,
"collectionId": "pbc_1568971955",
"hidden": false,
"id": "relation3303056927",
"maxSelect": 1,
"minSelect": 0,
"name": "team",
"presentable": false,
"required": true,
"system": false,
"type": "relation"
},
{
"hidden": false,
"id": "number2392944706",
"max": null,
"min": 0,
"name": "amount",
"onlyInt": false,
"presentable": false,
"required": false,
"system": false,
"type": "number"
},
{
"hidden": false,
"id": "autodate2990389176",
"name": "created",
"onCreate": true,
"onUpdate": false,
"presentable": false,
"system": false,
"type": "autodate"
},
{
"hidden": false,
"id": "autodate3332085495",
"name": "updated",
"onCreate": true,
"onUpdate": true,
"presentable": false,
"system": false,
"type": "autodate"
}
],
"id": "pbc_1788541978",
"indexes": [],
"listRule": null,
"name": "betPool",
"system": false,
"type": "base",
"updateRule": null,
"viewRule": null
}
];

Expand Down
1 change: 1 addition & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ services:
volumes:
- ./db/migrations:/pb/pb_migrations
- ./db/data:/pb/pb_data
- ./db/hooks:/pb/pb_hooks
profiles:
- dev

Expand Down