-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.ts
483 lines (424 loc) · 19.4 KB
/
index.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
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
import { EventHandlerContext } from '@subsquid/substrate-processor'
import { Store } from '@subsquid/typeorm-store'
import * as ss58 from '@subsquid/ss58'
import { Account, AccountBalance, Asset, HistoricalAccountBalance, HistoricalAsset,
HistoricalMarket, HistoricalPool, Market, Pool, Weight } from '../../model'
import { calcSpotPrice, getAssetId } from '../helper'
import { getPoolActiveEvent, getPoolClosedEvent, getPoolCreateEvent, getPoolExitEvent, getPoolJoinEvent,
getSwapExactAmountInEvent, getSwapExactAmountOutEvent} from './types'
export async function poolActive(ctx: EventHandlerContext<Store, {event: {args: true}}>) {
const {store, block, event} = ctx
const {poolId} = getPoolActiveEvent(ctx)
let pool = await store.get(Pool, { where: { poolId: +poolId.toString() } })
if (!pool) return
pool.poolStatus = 'Active'
console.log(`[${event.name}] Saving pool: ${JSON.stringify(pool, null, 2)}`)
await store.save<Pool>(pool)
let hp = new HistoricalPool()
hp.id = event.id + '-' + pool.poolId
hp.poolId = pool.poolId
hp.poolStatus = pool.poolStatus
hp.event = event.name.split('.')[1]
hp.blockNumber = block.height
hp.timestamp = new Date(block.timestamp)
console.log(`[${event.name}] Saving historical pool: ${JSON.stringify(hp, null, 2)}`)
await store.save<HistoricalPool>(hp)
}
export async function poolClosed(ctx: EventHandlerContext<Store, {event: {args: true}}>) {
const {store, block, event} = ctx
const {poolId} = getPoolClosedEvent(ctx)
let pool = await store.get(Pool, { where: { poolId: +poolId.toString() } })
if (!pool) return
pool.poolStatus = 'Closed'
console.log(`[${event.name}] Saving pool: ${JSON.stringify(pool, null, 2)}`)
await store.save<Pool>(pool)
let hp = new HistoricalPool()
hp.id = event.id + '-' + pool.poolId
hp.poolId = pool.poolId
hp.poolStatus = pool.poolStatus
hp.event = event.name.split('.')[1]
hp.blockNumber = block.height
hp.timestamp = new Date(block.timestamp)
console.log(`[${event.name}] Saving historical pool: ${JSON.stringify(hp, null, 2)}`)
await store.save<HistoricalPool>(hp)
}
export async function poolCreate(ctx: EventHandlerContext<Store, {event: {args: true}}>) {
const {store, block, event} = ctx
const {cpep, swapPool, amount} = getPoolCreateEvent(ctx)
const hab = await store.get(HistoricalAccountBalance, { where: { assetId: 'Ztg', event: 'NewAccount',
blockNumber: block.height } })
let pool = new Pool()
pool.id = event.id + '-' + cpep.poolId
pool.poolId = +cpep.poolId.toString()
pool.accountId = hab ? hab.accountId : null
pool.marketId = +swapPool.marketId.toString()
pool.poolStatus = swapPool.poolStatus.__kind
pool.scoringRule = swapPool.scoringRule.__kind
pool.swapFee = swapPool.swapFee ? swapPool.swapFee.toString() : ''
pool.totalSubsidy = swapPool.totalSubsidy ? swapPool.totalSubsidy.toString() : ''
pool.totalWeight = swapPool.totalWeight ? swapPool.totalWeight.toString() : ''
pool.weights = []
pool.ztgQty = amount !== BigInt(0) ? amount : BigInt(1000000000000)
pool.volume = BigInt(0)
pool.createdAt = new Date(block.timestamp)
pool.baseAsset = swapPool.baseAsset.__kind
let acc = await store.get(Account, { where: { accountId: hab?.accountId } })
if (acc) {
acc.poolId = pool.poolId
console.log(`[${event.name}] Saving account: ${JSON.stringify(acc, null, 2)}`)
await store.save<Account>(acc)
}
let market = await store.get(Market, { where: { marketId: pool.marketId } })
if (market) {
market.poolId = pool.poolId
console.log(`[${event.name}] Saving market: ${JSON.stringify(market, null, 2)}`)
await store.save<Market>(market)
let hm = new HistoricalMarket()
hm.id = event.id + '-' + market.marketId
hm.marketId = market.marketId
hm.event = event.name.split('.')[1]
hm.poolId = market.poolId
hm.blockNumber = block.height
hm.timestamp = new Date(block.timestamp)
console.log(`[${event.name}] Saving historical market: ${JSON.stringify(hm, null, 2)}`)
await store.save<HistoricalMarket>(hm)
}
if (swapPool.weights && swapPool.weights[swapPool.weights.length - 1][0].__kind == 'Ztg') {
const tokenWeightIn = +swapPool.weights[swapPool.weights.length - 1][1].toString()
await Promise.all(
swapPool.weights.map(async wt => {
let weight = new Weight()
weight.assetId = getAssetId(wt[0])
weight.len = wt[1]
pool.weights.push(weight)
if (weight.assetId.length > 5) {
let asset = await store.get(Asset, { where: { assetId: weight.assetId } })
if (!asset) { return }
let ab = await store.findOneBy(AccountBalance, { account: { accountId: acc?.accountId }, assetId: asset.assetId })
const tokenBalanceOut = ab ? +ab.balance.toString() : 1000000000000
const spotPrice = calcSpotPrice(+pool.ztgQty.toString(),tokenWeightIn,tokenBalanceOut,+weight.len.toString())
asset.poolId = pool.poolId
asset.price = +spotPrice.toString()
asset.amountInPool = BigInt(tokenBalanceOut)
console.log(`[${event.name}] Saving asset: ${JSON.stringify(asset, null, 2)}`)
await store.save<Asset>(asset)
let ha = new HistoricalAsset()
ha.id = event.id + '-' + asset.id.substring(asset.id.lastIndexOf('-')+1)
ha.accountId = ss58.codec('zeitgeist').encode(cpep.who)
ha.assetId = asset.assetId
ha.newPrice = asset.price
ha.newAmountInPool = asset.amountInPool
ha.dPrice = ha.newPrice
ha.dAmountInPool = ha.newAmountInPool
ha.event = event.name.split('.')[1]
ha.blockNumber = block.height
ha.timestamp = new Date(block.timestamp)
console.log(`[${event.name}] Saving historical asset: ${JSON.stringify(ha, null, 2)}`)
await store.save<HistoricalAsset>(ha)
}
})
)
}
console.log(`[${event.name}] Saving pool: ${JSON.stringify(pool, null, 2)}`)
await store.save<Pool>(pool)
let hp = new HistoricalPool()
hp.id = event.id + '-' + pool.poolId
hp.poolId = pool.poolId
hp.event = event.name.split('.')[1]
hp.ztgQty = pool.ztgQty
hp.volume = pool.volume
hp.blockNumber = block.height
hp.timestamp = new Date(block.timestamp)
console.log(`[${event.name}] Saving historical pool: ${JSON.stringify(hp, null, 2)}`)
await store.save<HistoricalPool>(hp)
}
export async function poolExit(ctx: EventHandlerContext<Store, {event: {args: true}}>) {
const {store, block, event} = ctx
const {pae, walletId} = getPoolExitEvent(ctx)
let pool = await store.get(Pool, { where: { poolId: +pae.cpep.poolId.toString() } })
if (!pool) return
const oldZtgQty = pool.ztgQty
const newZtgQty = oldZtgQty - BigInt(pae.transferred[pae.transferred.length - 1].toString())
pool.ztgQty = newZtgQty
console.log(`[${event.name}] Saving pool: ${JSON.stringify(pool, null, 2)}`)
await store.save<Pool>(pool)
let hp = new HistoricalPool()
hp.id = event.id + '-' + pool.poolId
hp.poolId = pool.poolId
hp.event = event.name.split('.')[1]
hp.ztgQty = pool.ztgQty
hp.blockNumber = block.height
hp.timestamp = new Date(block.timestamp)
console.log(`[${event.name}] Saving historical pool: ${JSON.stringify(hp, null, 2)}`)
await store.save<HistoricalPool>(hp)
const numOfPoolWts = pool.weights.length
if (numOfPoolWts > 0 && pool.weights[numOfPoolWts-1]!.assetId == 'Ztg') {
const tokenWeightIn = +pool.weights[numOfPoolWts-1]!.len.toString()
await Promise.all(
pool.weights.map(async (wt, idx) => {
if (idx >= pae.transferred.length - 1) return
let asset = await store.get(Asset, { where: { assetId: wt!.assetId } })
if (!asset || !asset.amountInPool || !asset.price) return
const assetWt = +wt!.len.toString()
const oldAssetQty = asset.amountInPool
const newAssetQty = oldAssetQty - BigInt(pae.transferred[idx].toString())
const oldPrice = asset.price
const newPrice = calcSpotPrice(+newZtgQty.toString(), tokenWeightIn, +newAssetQty.toString(), assetWt)
asset.price = newPrice
asset.amountInPool = newAssetQty
console.log(`[${event.name}] Saving asset: ${JSON.stringify(asset, null, 2)}`)
await store.save<Asset>(asset)
let ha = new HistoricalAsset()
ha.id = event.id + '-' + asset.id.substring(asset.id.lastIndexOf('-')+1)
ha.accountId = walletId
ha.assetId = asset.assetId
ha.newPrice = asset.price
ha.newAmountInPool = asset.amountInPool
ha.dPrice = newPrice - oldPrice
ha.dAmountInPool = newAssetQty - oldAssetQty
ha.event = event.name.split('.')[1]
ha.blockNumber = block.height
ha.timestamp = new Date(block.timestamp)
console.log(`[${event.name}] Saving historical asset: ${JSON.stringify(ha, null, 2)}`)
await store.save<HistoricalAsset>(ha)
})
);
}
}
export async function poolJoin(ctx: EventHandlerContext<Store, {event: {args: true}}>) {
const {store, block, event} = ctx
const {pae, walletId} = getPoolJoinEvent(ctx)
let pool = await store.get(Pool, { where: { poolId: +pae.cpep.poolId.toString() } })
if (!pool) return
const oldZtgQty = pool.ztgQty
const newZtgQty = oldZtgQty + BigInt(pae.transferred[pae.transferred.length - 1].toString())
pool.ztgQty = newZtgQty
console.log(`[${event.name}] Saving pool: ${JSON.stringify(pool, null, 2)}`)
await store.save<Pool>(pool)
let hp = new HistoricalPool()
hp.id = event.id + '-' + pool.poolId
hp.poolId = pool.poolId
hp.event = event.name.split('.')[1]
hp.ztgQty = pool.ztgQty
hp.blockNumber = block.height
hp.timestamp = new Date(block.timestamp)
console.log(`[${event.name}] Saving historical pool: ${JSON.stringify(hp, null, 2)}`)
await store.save<HistoricalPool>(hp)
const numOfPoolWts = pool.weights.length
if (numOfPoolWts > 0 && pool.weights[numOfPoolWts-1]!.assetId == 'Ztg') {
const tokenWeightIn = +pool.weights[numOfPoolWts-1]!.len.toString()
await Promise.all(
pool.weights.map(async (wt, idx) => {
if (idx >= pae.transferred.length - 1) return
let asset = await store.get(Asset, { where: { assetId: wt!.assetId } })
if (!asset || !asset.amountInPool || !asset.price) return
const assetWt = +wt!.len.toString()
const oldAssetQty = asset.amountInPool
const newAssetQty = oldAssetQty + BigInt(pae.transferred[idx].toString())
const oldPrice = asset.price
const newPrice = calcSpotPrice(+newZtgQty.toString(), tokenWeightIn, +newAssetQty.toString(), assetWt)
asset.price = newPrice
asset.amountInPool = newAssetQty
console.log(`[${event.name}] Saving asset: ${JSON.stringify(asset, null, 2)}`)
await store.save<Asset>(asset)
let ha = new HistoricalAsset()
ha.id = event.id + '-' + asset.id.substring(asset.id.lastIndexOf('-')+1)
ha.accountId = walletId
ha.assetId = asset.assetId
ha.newPrice = asset.price
ha.newAmountInPool = asset.amountInPool
ha.dPrice = newPrice - oldPrice
ha.dAmountInPool = newAssetQty - oldAssetQty
ha.event = event.name.split('.')[1]
ha.blockNumber = block.height
ha.timestamp = new Date(block.timestamp)
console.log(`[${event.name}] Saving historical asset: ${JSON.stringify(ha, null, 2)}`)
await store.save<HistoricalAsset>(ha)
})
);
}
}
export async function swapExactAmountIn(ctx: EventHandlerContext<Store>) {
const {store, block, event} = ctx
const {swapEvent, walletId} = getSwapExactAmountInEvent(ctx)
let pool = await store.get(Pool, { where: { poolId: +swapEvent.cpep.poolId.toString() } })
if (!pool) return
let assetBought = swapEvent.assetOut
let assetSold = swapEvent.assetIn
if (!assetBought && !assetSold) {
if (event.call && event.call.args.assetOut && event.call.args.assetIn) {
assetBought = event.call.args.assetOut
assetSold = event.call.args.assetIn
} else if (event.extrinsic) {
const args = event.extrinsic.call.args
if (!args.calls) {
assetBought = args.assetOut
assetSold = args.assetIn
} else {
for (let ext of args.calls as Array<{ __kind: string, value: any }> ) {
const { __kind: method, value: { __kind, assetIn, assetOut, maxPrice, poolId} } = ext;
if (method == 'Swaps' && __kind == 'swap_exact_amount_in' &&
poolId == swapEvent.cpep.poolId.toString() && maxPrice == swapEvent.maxPrice) {
assetBought = assetOut
assetSold = assetIn
break
}
}
}
}
}
const assetBoughtQty = BigInt(swapEvent.assetAmountOut.toString())
const assetSoldQty = BigInt(swapEvent.assetAmountIn.toString())
let ztgQty = pool.ztgQty
let oldVolume = pool.volume
let newVolume = oldVolume
if (assetBought.__kind == 'Ztg' || assetSold.__kind == 'Ztg') {
ztgQty = assetBought.__kind == 'Ztg' ? ztgQty - assetBoughtQty : ztgQty + assetSoldQty
newVolume = assetBought.__kind == 'Ztg' ? oldVolume + assetBoughtQty : oldVolume + assetSoldQty
pool.ztgQty = ztgQty
pool.volume = newVolume
console.log(`[${event.name}] Saving pool: ${JSON.stringify(pool, null, 2)}`)
await store.save<Pool>(pool)
let hp = new HistoricalPool()
hp.id = event.id + '-' + pool.poolId
hp.poolId = pool.poolId
hp.event = event.name.split('.')[1]
hp.ztgQty = pool.ztgQty
hp.volume = pool.volume
hp.blockNumber = block.height
hp.timestamp = new Date(block.timestamp)
console.log(`[${event.name}] Saving historical pool: ${JSON.stringify(hp, null, 2)}`)
await store.save<HistoricalPool>(hp)
}
const numOfPoolWts = pool.weights.length
if (numOfPoolWts > 0 && pool.weights[numOfPoolWts-1]!.assetId == 'Ztg') {
const ztgWeight = +pool.weights[numOfPoolWts-1]!.len.toString()
await Promise.all(
pool.weights.map(async wt => {
if (!wt) return
const asset = await store.get(Asset, { where: { assetId: wt.assetId } })
if (!asset || !asset.amountInPool || !asset.price) return
const assetWeight = +wt.len.toString()
const oldAssetQty = asset.amountInPool
const oldPrice = asset.price
let newAssetQty = oldAssetQty
if (wt.assetId == getAssetId(assetBought)) {
newAssetQty = oldAssetQty - assetBoughtQty
} else if (wt.assetId == getAssetId(assetSold)) {
newAssetQty = oldAssetQty + assetSoldQty
}
const newPrice = calcSpotPrice(+ztgQty.toString(),ztgWeight,+newAssetQty.toString(),assetWeight)
asset.price = newPrice
asset.amountInPool = newAssetQty
console.log(`[${event.name}] Saving asset: ${JSON.stringify(asset, null, 2)}`)
await store.save<Asset>(asset)
let ha = new HistoricalAsset()
ha.id = event.id + '-' + asset.id.substring(asset.id.lastIndexOf('-')+1)
ha.accountId = newAssetQty == oldAssetQty ? null : walletId
ha.assetId = asset.assetId
ha.ztgTraded = newAssetQty == oldAssetQty ? BigInt(0) : newVolume - oldVolume
ha.newPrice = asset.price
ha.newAmountInPool = asset.amountInPool
ha.dPrice = newPrice - oldPrice
ha.dAmountInPool = newAssetQty - oldAssetQty
ha.event = event.name.split('.')[1]
ha.blockNumber = block.height
ha.timestamp = new Date(block.timestamp)
console.log(`[${event.name}] Saving historical asset: ${JSON.stringify(ha, null, 2)}`)
await store.save<HistoricalAsset>(ha)
})
)
}
}
export async function swapExactAmountOut(ctx: EventHandlerContext<Store>) {
const {store, block, event} = ctx
const {swapEvent, walletId} = getSwapExactAmountOutEvent(ctx)
let pool = await store.get(Pool, { where: { poolId: +swapEvent.cpep.poolId.toString() } })
if (!pool) return
let assetBought = swapEvent.assetOut
let assetSold = swapEvent.assetIn
if (!assetBought && !assetSold) {
if (event.call && event.call.args.assetOut && event.call.args.assetIn) {
assetBought = event.call.args.assetOut
assetSold = event.call.args.assetIn
} else if (event.extrinsic) {
const args = event.extrinsic.call.args
if (!args.calls) {
assetBought = args.assetOut
assetSold = args.assetIn
} else {
for (let ext of args.calls as Array<{ __kind: string, value: any }> ) {
const { __kind: method, value: { __kind, assetIn, assetOut, maxPrice, poolId} } = ext;
if (method == 'Swaps' && __kind == 'swap_exact_amount_out' &&
poolId == swapEvent.cpep.poolId.toString() && maxPrice == swapEvent.maxPrice) {
assetBought = assetOut
assetSold = assetIn
break
}
}
}
}
}
const assetBoughtQty = BigInt(swapEvent.assetAmountOut.toString())
const assetSoldQty = BigInt(swapEvent.assetAmountIn.toString())
let ztgQty = pool.ztgQty
let oldVolume = pool.volume
let newVolume = oldVolume
if (assetBought.__kind == 'Ztg' || assetSold.__kind == 'Ztg') {
ztgQty = assetBought.__kind == 'Ztg' ? ztgQty - assetBoughtQty : ztgQty + assetSoldQty
newVolume = assetBought.__kind == 'Ztg' ? oldVolume + assetBoughtQty : oldVolume + assetSoldQty
pool.ztgQty = ztgQty
pool.volume = newVolume
console.log(`[${event.name}] Saving pool: ${JSON.stringify(pool, null, 2)}`)
await store.save<Pool>(pool)
let hp = new HistoricalPool()
hp.id = event.id + '-' + pool.poolId
hp.poolId = pool.poolId
hp.event = event.name.split('.')[1]
hp.ztgQty = pool.ztgQty
hp.volume = pool.volume
hp.blockNumber = block.height
hp.timestamp = new Date(block.timestamp)
console.log(`[${event.name}] Saving historical pool: ${JSON.stringify(hp, null, 2)}`)
await store.save<HistoricalPool>(hp)
}
const numOfPoolWts = pool.weights.length
if (numOfPoolWts > 0 && pool.weights[numOfPoolWts-1]!.assetId == 'Ztg') {
const ztgWeight = +pool.weights[numOfPoolWts-1]!.len.toString()
await Promise.all(
pool.weights.map(async wt => {
if (!wt) return
const asset = await store.get(Asset, { where: { assetId: wt.assetId } })
if (!asset || !asset.amountInPool || !asset.price) return
const assetWeight = +wt.len.toString()
const oldAssetQty = asset.amountInPool
const oldPrice = asset.price
let newAssetQty = oldAssetQty
if (wt.assetId == getAssetId(assetBought)) {
newAssetQty = oldAssetQty - assetBoughtQty
} else if (wt.assetId == getAssetId(assetSold)) {
newAssetQty = oldAssetQty + assetSoldQty
}
const newPrice = calcSpotPrice(+ztgQty.toString(),ztgWeight,+newAssetQty.toString(),assetWeight)
asset.price = newPrice
asset.amountInPool = newAssetQty
console.log(`[${event.name}] Saving asset: ${JSON.stringify(asset, null, 2)}`)
await store.save<Asset>(asset)
let ha = new HistoricalAsset()
ha.id = event.id + '-' + asset.id.substring(asset.id.lastIndexOf('-')+1)
ha.accountId = newAssetQty == oldAssetQty ? null : walletId
ha.assetId = asset.assetId
ha.ztgTraded = newAssetQty == oldAssetQty ? BigInt(0) : newVolume - oldVolume
ha.newPrice = asset.price
ha.newAmountInPool = asset.amountInPool
ha.dPrice = newPrice - oldPrice
ha.dAmountInPool = newAssetQty - oldAssetQty
ha.event = event.name.split('.')[1]
ha.blockNumber = block.height
ha.timestamp = new Date(block.timestamp)
console.log(`[${event.name}] Saving historical asset: ${JSON.stringify(ha, null, 2)}`)
await store.save<HistoricalAsset>(ha)
})
)
}
}