-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbalances.ts
More file actions
293 lines (249 loc) · 7.47 KB
/
Copy pathbalances.ts
File metadata and controls
293 lines (249 loc) · 7.47 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
import type { Context } from 'hono'
import { zeroAddress } from 'viem'
import { z } from 'zod'
import { db } from '../db'
import { erc20Queue } from '../queues/workers/erc20'
import { ethQueue } from '../queues/workers/eth'
export async function addCheckBalanceTasksToQueue() {
const accounts = await db.selectFrom('accounts').selectAll().execute()
const tokens = await db.selectFrom('tokens').selectAll().execute()
const balancesOfOffchainAccounts = await db
.selectFrom('balances')
.selectAll()
.where(
'owner',
'in',
accounts.filter((a) => a.address === null).map((a) => a.id)
)
.execute()
const ethTasks = []
const erc20Tasks = []
for (const account of accounts) {
for (const token of tokens) {
// Handle offchain accounts
if (account.address === null) {
const balance = balancesOfOffchainAccounts.find(
(b) => b.owner === account.id && b.token === token.id
)
// We'll run into an error later if we don't have a balance for an offchain account,
// so we'll just not add it to the queue in the first place.
if (!balance) {
continue
}
}
if (token.address === zeroAddress) {
// Native ETH
ethTasks.push({
owner: account,
chainId: token.chain,
})
} else {
// ERC20s
erc20Tasks.push({
token: token.address,
owner: account,
chainId: token.chain,
})
}
}
}
await ethQueue.addBulk(
ethTasks.map((task) => ({
name: `${task.chainId}:${task.owner.id}`,
data: task,
}))
)
await erc20Queue.addBulk(
erc20Tasks.map((task) => ({
name: `${task.chainId}:${task.owner.id}:${task.token}`,
data: task,
}))
)
}
export async function fetchBalances(c: Context) {
await addCheckBalanceTasksToQueue()
return c.json({ success: true })
}
export async function getBalances(c: Context) {
const { balances, tokens, chains } = await db
.transaction()
.execute(async (trx) => {
// Get all balances, grouped by token (address + chain)
const balances = (await trx
.selectFrom('balances')
.select([
'token',
trx.fn.sum('balance').as('balance'),
trx.fn.sum('ethValue').as('ethValue'),
])
.where('balance', '>', 0)
.groupBy(['token'])
.orderBy('ethValue', 'desc')
.execute()) as {
// For some reason kysely infers `balance` and `ethValue` incorrectly
token: number
balance: number
ethValue: number
}[]
const tokens = await trx
.selectFrom('tokens')
.selectAll()
.where(
'id',
'in',
balances.map((b) => b.token)
)
.execute()
const chains = await trx.selectFrom('chains').selectAll().execute()
return { balances, tokens, chains }
})
const tokensWithChain = tokens.map((t) => ({
...t,
chain: chains.find((c) => c.id === t.chain)!,
}))
const enhancedBalances = balances.map((b) => ({
balance: b.balance,
ethValue: b.ethValue,
ethValuePerToken: b.ethValue / b.balance,
...tokensWithChain.find((t) => t.id === b.token)!,
}))
// Note: this isn't technically precise because different tokens could have
// the same address on different chains, but i've never seen that happen in
// practice, so I'd rather optimize for UX by combining stuff like (W)ETH
// across chains. Worst case, the totalEthValue will still be accurate
// (I think) just with a slightly different breakdown.
// const combinedBalances = enhancedBalances.reduce(
// (acc, balance) => {
// const existing = acc.find((b) => b.address === balance.address)
// if (existing) {
// existing.balance += balance.balance
// existing.ethValue += balance.ethValue
// } else {
// acc.push({ ...balance })
// }
// return acc
// },
// [] as typeof enhancedBalances
// )
const totalEthValue = enhancedBalances.reduce((acc, b) => acc + b.ethValue, 0)
return c.json({ totalEthValue, tokens: enhancedBalances })
}
export async function getEthValueByAccount(c: Context) {
const { balances, accounts } = await db.transaction().execute(async (trx) => {
const balances = await trx
.selectFrom('balances')
.select(['owner', db.fn.sum('ethValue').as('ethValue')])
.where('ethValue', '>', 0)
.groupBy(['owner'])
.orderBy('ethValue', 'desc')
.execute()
const accounts = await trx
.selectFrom('accounts')
.select(['id', 'address', 'name'])
.where(
'id',
'in',
balances.map((b) => b.owner)
)
.execute()
return { balances, accounts }
})
const data = balances.map((b) => ({
ethValue: Number(b.ethValue),
owner: accounts.find((a) => a.id === b.owner)!,
}))
return c.json(data)
}
export async function getNetworthTimeSeries(c: Context) {
const networth = await db
.selectFrom('networth')
.selectAll()
.where('usdValue', 'is not', null)
.limit(60)
.orderBy('timestamp', 'desc')
.execute()
return c.json(networth.reverse())
}
export async function getOffchainBalances(c: Context) {
const { accounts, balances, tokens } = await db
.transaction()
.execute(async (trx) => {
const accounts = await trx
.selectFrom('accounts')
.selectAll()
.where('address', 'is', null)
.execute()
const balances = await trx
.selectFrom('balances')
.selectAll()
.where(
'owner',
'in',
accounts.map((a) => a.id)
)
.execute()
const tokens = await trx
.selectFrom('tokens')
.selectAll()
.where(
'id',
'in',
balances.map((b) => b.token)
)
.execute()
return { accounts, balances, tokens }
})
const enhancedBalances = balances.map((b) => ({
...b,
owner: accounts.find((a) => a.id === b.owner)!,
token: tokens.find((t) => t.id === b.token)!,
}))
return c.json(enhancedBalances)
}
const editOffchainAccountSchema = z.object({
account: z.number(),
token: z.number(),
amount: z.number(),
})
export async function editOffchainBalance(c: Context) {
const safeParse = editOffchainAccountSchema.safeParse(await c.req.json())
if (!safeParse.success) {
return c.json({ error: safeParse.error }, 400)
}
const { account, token, amount } = safeParse.data
const realAccount = await db
.selectFrom('accounts')
.selectAll()
.where('id', '=', account)
.executeTakeFirst()
if (!realAccount || !!realAccount.address) {
return c.json({ error: 'Cannot edit balances for onchain accounts' }, 400)
}
await db
.insertInto('balances')
.values({
token,
owner: account,
balance: amount,
ethValue: 0,
})
.onConflict((oc) => oc.doUpdateSet({ balance: amount, ethValue: 0 }))
.execute()
return c.json({ success: true })
}
const deleteOffchainBalanceSchema = z.object({
account: z.coerce.number(),
token: z.coerce.number(),
})
export async function deleteOffchainBalance(c: Context) {
const safeParse = deleteOffchainBalanceSchema.safeParse(await c.req.json())
if (!safeParse.success) {
return c.json({ error: safeParse.error }, 400)
}
await db
.deleteFrom('balances')
.where('owner', '=', safeParse.data.account)
.where('token', '=', safeParse.data.token)
.execute()
return c.json({ success: true })
}