forked from ker0olos/fable
-
Notifications
You must be signed in to change notification settings - Fork 0
/
addTokens.ts
128 lines (96 loc) · 2.61 KB
/
addTokens.ts
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
/// <reference lib="deno.unstable" />
import { inventoriesByUser, usersByDiscordId } from './indices.ts';
import db, { kv, MAX_PULLS } from './mod.ts';
import { KvError } from '../src/errors.ts';
import type * as Schema from './schema.ts';
export const COSTS = {
THREE: 4,
FOUR: 12,
FIVE: 28,
};
export async function addTokens(
user: Schema.User,
amount: number,
vote?: boolean,
): Promise<Schema.User> {
user.availableTokens ??= 0;
user.availableTokens = user.availableTokens + amount;
if (vote) {
user.lastVote = new Date().toISOString();
}
let res = { ok: false }, retires = 0;
while (!res.ok && retires < 5) {
res = await kv.atomic()
.set(['users', user._id], user)
.set(usersByDiscordId(user.id), user)
.commit();
if (res.ok) {
return user;
}
retires += 1;
}
throw new KvError('failed to update user');
}
export async function addPulls(
instance: Schema.Instance,
user: Schema.User,
amount: number,
): Promise<Schema.Inventory> {
user.availableTokens ??= 0;
if (amount > user.availableTokens) {
throw new Error('INSUFFICIENT_TOKENS');
}
user.availableTokens = user.availableTokens - amount;
let res = { ok: false }, retires = 0;
while (!res.ok && retires < 5) {
const { inventory, inventoryCheck } = await db.rechargePulls(
instance,
user,
false,
);
inventory.availablePulls = Math.min(99, inventory.availablePulls + amount);
if (inventory.availablePulls >= MAX_PULLS) {
inventory.rechargeTimestamp = undefined;
}
res = await kv.atomic()
.check(inventoryCheck)
//
.set(['inventories', inventory._id], inventory)
.set(inventoriesByUser(inventory.instance, user._id), inventory)
//
.set(['users', user._id], user)
.set(usersByDiscordId(user.id), user)
//
.commit();
if (res.ok) {
return inventory;
}
retires += 1;
}
throw new KvError('failed to update inventory');
}
export async function addGuarantee(
user: Schema.User,
guarantee: number,
): Promise<Schema.User> {
const cost = guarantee === 5
? COSTS.FIVE
: guarantee === 4
? COSTS.FOUR
: COSTS.THREE;
user.guarantees ??= [];
user.availableTokens ??= 0;
if (cost > user.availableTokens) {
throw new Error('INSUFFICIENT_TOKENS');
}
user.availableTokens = user.availableTokens - cost;
user.guarantees.push(guarantee);
const update = await kv.atomic()
.set(['users', user._id], user)
.set(usersByDiscordId(user.id), user)
.commit();
if (update.ok) {
return user;
}
throw new KvError('failed to update user');
}